问:
Target all users in two OU's and remove Distribution Lists
hoping to get a little help here – I looked around the site but didn’t see anything quite like this (please direct me if there IS and I missed it).

I need to incorporate a new step in our user offboarding process, which would remove them from any AD Distribution Lists.  I would like to set this up as a scheduled task to run once a night against two OU’s where the inactivated user accounts can be found.

I’d like to run this by pointing it at the USERS instead of the OU where the Distro Lists live, because I suspect that we’ll ultimately get the request to remove these users from OTHER types of group as well.

This snippet will remove AD Distro Lists from a single user, but leave all other types of AD groups alone:

```<code>#  GroupCategory 0 = Distro List
#  GroupCategory 1 = Security Group

#  GroupScope 0 = DomainLocal
#  GroupScope 1 = Global
#  GroupScope 2 = Universal

$user = "userlogon"
Get-ADPrincipalGroupMembership -Identity $user|
Where {$_.GroupCategory -eq 0} |
ForEach {Remove-ADPrincipalGroupMembership -Identity $user -MemberOf $_ -Confirm:$false}
</code>```

THIS snippet will look at an OU and return some info (just my example for using a variable with -searchbase):

```<code>$OUs = 'OU=PendingDeletion,OU=Users,DC=Stuff,DC=Place,DC=net','OU=HoldForReview,OU=Users,DC=Stuff,DC=Place,DC=net'

$OU | ForEach {Get-ADGroup -Filter * -Properties ManagedBy -SearchBase $_ } |
 Select Name, ManagedBy |
 Sort -Property Name
 Out-GridView
</code>```

BUT – Does it hold together that in order to complete my objective, I would do something like this?!  I'm a bit out of my depth here, any advice for a re-write is appreciated:

```<code>$OUs = 'OU=PendingDeletion,OU=Users,DC=Stuff,DC=Place,DC=net','OU=HoldForReview,OU=Users,DC=Stuff,DC=Place,DC=net'
 $user = "*"

$OUs | ForEach {
        Get-ADPrincipalGroupMembership -Identity $user|
        Where {$_.GroupCategory -eq 0} |
        ForEach {Remove-ADPrincipalGroupMembership -Identity $user -MemberOf $_ -Confirm:$false}
              }
</code>```

There’s always a couple of ways to do stuff in PoSh, so I’m sure there’s a less-complicated way to do the same thing.  If anyone has a different approach please feel free to suggest an alternative.

Thanks for taking a look!

答:
I think I'd take this a little differently, by getting the group membership of all users, then grouping by AD group, and processing each group that way. Seems like it would be a lot fewer calls to AD. So I'd start out getting all of the users, just like BenH, except I would include their MemberOf property. Then I'd build a list of potential groups and filter down to just the Distribution Lists. I'd make a Hashtable of those as the keys, and make the value an array of each user that is in that group. Then loop through that removing the value of each from the associated key.</p>

```<code>$OUs = 'OU=PendingDeletion,OU=Users,DC=Stuff,DC=Place,DC=net','OU=HoldForReview,OU=Users,DC=Stuff,DC=Place,DC=net'
$Users = ForEach ($OU in $OUs) {
    Get-ADUser -Filter * -SearchBase $OU -Properties MemberOf
}
$UsersByGroup = @{}
ForEach($Group in ($Users.MemberOf | Select -Unique | Get-ADGroup | Where{ $_.GroupCategory -eq 0 })) {
    $UsersByGroup.Add($Group.DistinguishedName,($Users | Where{ $Group.DistinguishedName -in $_.MemberOf}))
}
$UsersByGroup.Keys | ForEach{
    Remove-ADGroupMember -Identity $_ -Members $UsersByGroup[$_] -Confirm:$false
}
</code>```

Body:
hoping to get a little help here – I looked around the site but didn’t see anything quite like this (please direct me if there IS and I missed it).

I need to incorporate a new step in our user offboarding process, which would remove them from any AD Distribution Lists.  I would like to set this up as a scheduled task to run once a night against two OU’s where the inactivated user accounts can be found.

I’d like to run this by pointing it at the USERS instead of the OU where the Distro Lists live, because I suspect that we’ll ultimately get the request to remove these users from OTHER types of group as well.

This snippet will remove AD Distro Lists from a single user, but leave all other types of AD groups alone:

#  GroupCategory 0 = Distro List
#  GroupCategory 1 = Security Group

#  GroupScope 0 = DomainLocal
#  GroupScope 1 = Global
#  GroupScope 2 = Universal

$user = "userlogon"
Get-ADPrincipalGroupMembership -Identity $user|
Where {$_.GroupCategory -eq 0} |
ForEach {Remove-ADPrincipalGroupMembership -Identity $user -MemberOf $_ -Confirm:$false}

THIS snippet will look at an OU and return some info (just my example for using a variable with -searchbase):

$OUs = 'OU=PendingDeletion,OU=Users,DC=Stuff,DC=Place,DC=net','OU=HoldForReview,OU=Users,DC=Stuff,DC=Place,DC=net'

$OU | ForEach {Get-ADGroup -Filter * -Properties ManagedBy -SearchBase $_ } |
 Select Name, ManagedBy |
 Sort -Property Name
 Out-GridView

BUT – Does it hold together that in order to complete my objective, I would do something like this?!  I'm a bit out of my depth here, any advice for a re-write is appreciated:

$OUs = 'OU=PendingDeletion,OU=Users,DC=Stuff,DC=Place,DC=net','OU=HoldForReview,OU=Users,DC=Stuff,DC=Place,DC=net'
 $user = "*"

$OUs | ForEach {
        Get-ADPrincipalGroupMembership -Identity $user|
        Where {$_.GroupCategory -eq 0} |
        ForEach {Remove-ADPrincipalGroupMembership -Identity $user -MemberOf $_ -Confirm:$false}
              }

There’s always a couple of ways to do stuff in PoSh, so I’m sure there’s a less-complicated way to do the same thing.  If anyone has a different approach please feel free to suggest an alternative.

Thanks for taking a look!

Body:
I think I'd take this a little differently, by getting the group membership of all users, then grouping by AD group, and processing each group that way. Seems like it would be a lot fewer calls to AD. So I'd start out getting all of the users, just like BenH, except I would include their MemberOf property. Then I'd build a list of potential groups and filter down to just the Distribution Lists. I'd make a Hashtable of those as the keys, and make the value an array of each user that is in that group. Then loop through that removing the value of each from the associated key.

$OUs = 'OU=PendingDeletion,OU=Users,DC=Stuff,DC=Place,DC=net','OU=HoldForReview,OU=Users,DC=Stuff,DC=Place,DC=net'
$Users = ForEach ($OU in $OUs) {
    Get-ADUser -Filter * -SearchBase $OU -Properties MemberOf
}
$UsersByGroup = @{}
ForEach($Group in ($Users.MemberOf | Select -Unique | Get-ADGroup | Where{ $_.GroupCategory -eq 0 })) {
    $UsersByGroup.Add($Group.DistinguishedName,($Users | Where{ $Group.DistinguishedName -in $_.MemberOf}))
}
$UsersByGroup.Keys | ForEach{
    Remove-ADGroupMember -Identity $_ -Members $UsersByGroup[$_] -Confirm:$false
}


来源: stackexchange

问:
PHP SHA3 functionality
Is there a framework or function that allows me to use SHA3-512?
I don't want a extension like Strawbrary</p>

答:
Yes sure simply you can use hash function in php</p>

```<code><?php
echo hash('sha3-512' , 'String you want to hash');
</code>```

ContentLicense: CC BY-SA 3.0

Title: PHP SHA3 functionality

Body:
Yes sure simply you can use hash function in php

<?php
echo hash('sha3-512' , 'String you want to hash');


答:
Below is for BigQuery Standard SQL  </p>

<pre class="lang-sql prettyprint-override"><code>#standardSQL
SELECT
  MIN(datetime) AS min_time,
  MAX(datetime) AS max_time,
  TIMESTAMP_DIFF(MAX(datetime), MIN(datetime), SECOND) AS idle
FROM (
  SELECT *, SUM(speed) OVER(ORDER BY datetime) AS grp
  FROM `dbtest.YourTable`
)
WHERE speed = 0
GROUP BY grp
HAVING COUNT(1) > 1
-- ORDER BY grp DESC
</code>```

<p>You can play/test with dummy data in example from your question   </p>

<pre class="lang-sql prettyprint-override"><code>#standardSQL
WITH yourTable AS (
  SELECT 0 AS speed, TIMESTAMP '2017-01-31 23:59:53 UTC' AS datetime UNION ALL
  SELECT 0, TIMESTAMP '2017-01-31 23:59:43 UTC' UNION ALL
  SELECT 0.05, TIMESTAMP '2017-01-31 23:59:33 UTC' UNION ALL
  SELECT 0, TIMESTAMP '2017-01-31 23:59:23 UTC' UNION ALL
  SELECT 0.02, TIMESTAMP '2017-01-31 23:59:13 UTC' UNION ALL
  SELECT 0.02, TIMESTAMP '2017-01-31 23:59:03 UTC' UNION ALL
  SELECT 0, TIMESTAMP '2017-01-31 23:58:53 UTC' UNION ALL
  SELECT 0, TIMESTAMP '2017-01-31 23:58:43 UTC' UNION ALL
  SELECT 0, TIMESTAMP '2017-01-31 23:58:33 UTC' UNION ALL
  SELECT 0, TIMESTAMP '2017-01-31 23:58:23 UTC' UNION ALL
  SELECT 0, TIMESTAMP '2017-01-31 23:58:13 UTC' UNION ALL
  SELECT 0.02, TIMESTAMP '2017-01-31 23:58:03 UTC' UNION ALL
  SELECT 0.02, TIMESTAMP '2017-01-31 23:57:53 UTC' UNION ALL
  SELECT 0, TIMESTAMP '2017-01-31 23:57:43 UTC' UNION ALL
  SELECT 0.02, TIMESTAMP '2017-01-31 23:57:33 UTC' UNION ALL
  SELECT 0, TIMESTAMP '2017-01-31 23:57:23 UTC' UNION ALL
  SELECT 0.02, TIMESTAMP '2017-01-31 23:57:22 UTC' UNION ALL
  SELECT 0.02, TIMESTAMP '2017-01-31 23:57:13 UTC' UNION ALL
  SELECT 0, TIMESTAMP '2017-01-31 23:57:09 UTC' UNION ALL
  SELECT 0.02, TIMESTAMP '2017-01-31 23:57:08 UTC' UNION ALL
  SELECT 0, TIMESTAMP '2017-01-31 23:57:03 UTC' UNION ALL
  SELECT 0, TIMESTAMP '2017-01-31 23:56:53 UTC' UNION ALL
  SELECT 0, TIMESTAMP '2017-01-31 23:56:51 UTC' UNION ALL
  SELECT 0, TIMESTAMP '2017-01-31 23:56:43 UTC' UNION ALL
  SELECT 0, TIMESTAMP '2017-01-31 23:56:34 UTC' UNION ALL
  SELECT 0, TIMESTAMP '2017-01-31 23:56:33 UTC' UNION ALL
  SELECT 0, TIMESTAMP '2017-01-31 23:56:23 UTC' UNION ALL
  SELECT 0, TIMESTAMP '2017-01-31 23:56:18 UTC'
)
SELECT
  MIN(datetime) AS min_time,
  MAX(datetime) AS max_time,
  TIMESTAMP_DIFF(MAX(datetime), MIN(datetime), SECOND) AS idle
FROM (
  SELECT *, SUM(speed) OVER(ORDER BY datetime) AS grp
  FROM yourTable
)
WHERE speed = 0
GROUP BY grp
HAVING COUNT(1) > 1
-- ORDER BY grp DESC
</code>```

Title: Get groups of idling times, BigQuery

Body:
I need to get groups of idling times, where speed is 0 and there is minimum two such consecutive records, i.e.:

+---------------------+---------------------+------+
|      min time       |      max time       | idle |
+---------------------+---------------------+------+
| 2017-01-31 23:59:43 | 2017-01-31 23:59:53 |   10 |
| 2017-01-31 23:58:13 | 2017-01-31 23:58:53 |   40 |
| 2017-01-31 23:56:18 | 2017-01-31 23:57:03 |   45 |
+---------------------+---------------------+------+

ideally with totals of idling times in seconds.

Data sample:

+-------+-------------------------+
| speed |        datetime         |
+-------+-------------------------+
| 0     | 2017-01-31 23:59:53 UTC |
| 0     | 2017-01-31 23:59:43 UTC |
| 0.05  | 2017-01-31 23:59:33 UTC |
| 0     | 2017-01-31 23:59:23 UTC |
| 0.02  | 2017-01-31 23:59:13 UTC |
| 0.02  | 2017-01-31 23:59:03 UTC |
| 0     | 2017-01-31 23:58:53 UTC |
| 0     | 2017-01-31 23:58:43 UTC |
| 0     | 2017-01-31 23:58:33 UTC |
| 0     | 2017-01-31 23:58:23 UTC |
| 0     | 2017-01-31 23:58:13 UTC |
| 0.02  | 2017-01-31 23:58:03 UTC |
| 0.02  | 2017-01-31 23:57:53 UTC |
| 0     | 2017-01-31 23:57:43 UTC |
| 0.02  | 2017-01-31 23:57:33 UTC |
| 0     | 2017-01-31 23:57:23 UTC |
| 0.02  | 2017-01-31 23:57:22 UTC |
| 0.02  | 2017-01-31 23:57:13 UTC |
| 0     | 2017-01-31 23:57:09 UTC |
| 0.02  | 2017-01-31 23:57:08 UTC |
| 0     | 2017-01-31 23:57:03 UTC |
| 0     | 2017-01-31 23:56:53 UTC |
| 0     | 2017-01-31 23:56:51 UTC |
| 0     | 2017-01-31 23:56:43 UTC |
| 0     | 2017-01-31 23:56:34 UTC |
| 0     | 2017-01-31 23:56:33 UTC |
| 0     | 2017-01-31 23:56:23 UTC |
| 0     | 2017-01-31 23:56:18 UTC |
+-------+-------------------------+

Query:

#standardSQL
SELECT
 MIN(datetime), MAX(datetime)
FROM
 (SELECT t.*,
   (SELECT
     COUNT(*)
    FROM
     `dbtest.log_*` t2
    WHERE
     t2.datetime <= t.datetime and t2.speed > 0) grp
 FROM
 `dbtest.log_*` t
 WHERE t.speed = 0) x
 GROUP BY grp

Result:

"LEFT OUTER JOIN cannot be used without a condition that is an
  equality of fields from both sides of the join."

What's wrong with my query?

Id there a better way to achieve that in bigquery?

Body:
Below is for BigQuery Standard SQL

#standardSQL
SELECT
  MIN(datetime) AS min_time,
  MAX(datetime) AS max_time,
  TIMESTAMP_DIFF(MAX(datetime), MIN(datetime), SECOND) AS idle
FROM (
  SELECT *, SUM(speed) OVER(ORDER BY datetime) AS grp
  FROM `dbtest.YourTable`
)
WHERE speed = 0
GROUP BY grp
HAVING COUNT(1) > 1
-- ORDER BY grp DESC

You can play/test with dummy data in example from your question

#standardSQL
WITH yourTable AS (
  SELECT 0 AS speed, TIMESTAMP '2017-01-31 23:59:53 UTC' AS datetime UNION ALL
  SELECT 0, TIMESTAMP '2017-01-31 23:59:43 UTC' UNION ALL
  SELECT 0.05, TIMESTAMP '2017-01-31 23:59:33 UTC' UNION ALL
  SELECT 0, TIMESTAMP '2017-01-31 23:59:23 UTC' UNION ALL
  SELECT 0.02, TIMESTAMP '2017-01-31 23:59:13 UTC' UNION ALL
  SELECT 0.02, TIMESTAMP '2017-01-31 23:59:03 UTC' UNION ALL
  SELECT 0, TIMESTAMP '2017-01-31 23:58:53 UTC' UNION ALL
  SELECT 0, TIMESTAMP '2017-01-31 23:58:43 UTC' UNION ALL
  SELECT 0, TIMESTAMP '2017-01-31 23:58:33 UTC' UNION ALL
  SELECT 0, TIMESTAMP '2017-01-31 23:58:23 UTC' UNION ALL
  SELECT 0, TIMESTAMP '2017-01-31 23:58:13 UTC' UNION ALL
  SELECT 0.02, TIMESTAMP '2017-01-31 23:58:03 UTC' UNION ALL
  SELECT 0.02, TIMESTAMP '2017-01-31 23:57:53 UTC' UNION ALL
  SELECT 0, TIMESTAMP '2017-01-31 23:57:43 UTC' UNION ALL
  SELECT 0.02, TIMESTAMP '2017-01-31 23:57:33 UTC' UNION ALL
  SELECT 0, TIMESTAMP '2017-01-31 23:57:23 UTC' UNION ALL
  SELECT 0.02, TIMESTAMP '2017-01-31 23:57:22 UTC' UNION ALL
  SELECT 0.02, TIMESTAMP '2017-01-31 23:57:13 UTC' UNION ALL
  SELECT 0, TIMESTAMP '2017-01-31 23:57:09 UTC' UNION ALL
  SELECT 0.02, TIMESTAMP '2017-01-31 23:57:08 UTC' UNION ALL
  SELECT 0, TIMESTAMP '2017-01-31 23:57:03 UTC' UNION ALL
  SELECT 0, TIMESTAMP '2017-01-31 23:56:53 UTC' UNION ALL
  SELECT 0, TIMESTAMP '2017-01-31 23:56:51 UTC' UNION ALL
  SELECT 0, TIMESTAMP '2017-01-31 23:56:43 UTC' UNION ALL
  SELECT 0, TIMESTAMP '2017-01-31 23:56:34 UTC' UNION ALL
  SELECT 0, TIMESTAMP '2017-01-31 23:56:33 UTC' UNION ALL
  SELECT 0, TIMESTAMP '2017-01-31 23:56:23 UTC' UNION ALL
  SELECT 0, TIMESTAMP '2017-01-31 23:56:18 UTC'
)
SELECT
  MIN(datetime) AS min_time,
  MAX(datetime) AS max_time,
  TIMESTAMP_DIFF(MAX(datetime), MIN(datetime), SECOND) AS idle
FROM (
  SELECT *, SUM(speed) OVER(ORDER BY datetime) AS grp
  FROM yourTable
)
WHERE speed = 0
GROUP BY grp
HAVING COUNT(1) > 1
-- ORDER BY grp DESC


问:
How to remove consecutive rows with duplicate data in certain fields (in SQLite)?
Let's say for example you have a table like this:

```<code>-------------------------------
Date        Name          Type
2017-01-01  John          1
2017-01-02  John          1
2017-01-03  Mike          2
2017-01-04  John          1
-------------------------------
</code>```

I want to be able to group by the type to get a result like the following

```<code>-------------------------
Name          Type
John          1
Mike          2
John          1
-------------------------
</code>```

As you can see the first two rows was grouped because there is no different type in between them, like the thing you see in mobile phones call logs.

How can I achieve that in SQLite?

答:
You can do this with an ordered temp table and some rowid comparisons:</p>

```<code>sqlite> create table t (date, name, type);
sqlite> insert into t (date, name, type) values ( '2017-01-01', 'John', 1);
sqlite> insert into t (date, name, type) values ( '2017-01-02', 'John', 1);
sqlite> insert into t (date, name, type) values ( '2017-01-03', 'Mike', 2);
sqlite> insert into t (date, name, type) values ( '2017-01-04', 'John', 1);

sqlite> create temp table tp as select date, name, type from t order by date;
sqlite> delete from tp
     where tp.name = (select name from t where t.rowid = tp.rowid - 1)
     and tp.type = (select type from t where t.rowid = tp.rowid - 1);
sqlite> select * from tp;
2017-01-01|John|1
2017-01-03|Mike|2
2017-01-04|John|1
sqlite>
</code>```

Body:
Let's say for example you have a table like this:

-------------------------------
Date        Name          Type
2017-01-01  John          1
2017-01-02  John          1
2017-01-03  Mike          2
2017-01-04  John          1
-------------------------------

I want to be able to group by the type to get a result like the following

-------------------------
Name          Type
John          1
Mike          2
John          1
-------------------------

As you can see the first two rows was grouped because there is no different type in between them, like the thing you see in mobile phones call logs.

How can I achieve that in SQLite?

Body:
You can do this with an ordered temp table and some rowid comparisons:

sqlite> create table t (date, name, type);
sqlite> insert into t (date, name, type) values ( '2017-01-01', 'John', 1);
sqlite> insert into t (date, name, type) values ( '2017-01-02', 'John', 1);
sqlite> insert into t (date, name, type) values ( '2017-01-03', 'Mike', 2);
sqlite> insert into t (date, name, type) values ( '2017-01-04', 'John', 1);

sqlite> create temp table tp as select date, name, type from t order by date;
sqlite> delete from tp
     where tp.name = (select name from t where t.rowid = tp.rowid - 1)
     and tp.type = (select type from t where t.rowid = tp.rowid - 1);
sqlite> select * from tp;
2017-01-01|John|1
2017-01-03|Mike|2
2017-01-04|John|1
sqlite>


问:
MarkLogic- How to use andNot in structuredQueryBuilder
{"uuid": 121222151, "path": "/aaa/bbb/ccc.json", "name": "newDoc1",
"uuid": 121222152, "path": "/aaa/ddd.json", "name": "newDoc1"}

I am using StructuredQueryBuilder to search for results.

```<code>StructuredQueryBuilder queryBuilder = new StructuredQueryBuilder();
StructuredQueryDefinition containPositiveQuery = queryBuilder.containerQuery(queryBuilder.jsonProperty("name"), queryBuilder.term("newDoc1"));
StructuredQueryDefinition containNegativeQuery = queryBuilder.containerQuery(queryBuilder.jsonProperty("path"), queryBuilder.term("*/bbb/*"));
StructuredQueryDefinition containQuery = qb.andNot(containPositiveQuery, containNegativeQuery);
</code>```

I want the result to search for the name "newDoc1" but not in the path which contains "*/bbb/*". The above code is not working. What could be the reason?

答:
Have you turned on wildcard indexes for the path property?  If not, you probably want to create a field on the path property and turn on the wildcard indexes only for that field.

To understand wildcard searches, see:

http://docs.marklogic.com/guide/search-dev/wildcard

Turning on wildcards for a specific field makes sense if you only need wildcards for that JSON property.

Body:
{"uuid": 121222151, "path": "/aaa/bbb/ccc.json", "name": "newDoc1",
"uuid": 121222152, "path": "/aaa/ddd.json", "name": "newDoc1"}

I am using StructuredQueryBuilder to search for results.

StructuredQueryBuilder queryBuilder = new StructuredQueryBuilder();
StructuredQueryDefinition containPositiveQuery = queryBuilder.containerQuery(queryBuilder.jsonProperty("name"), queryBuilder.term("newDoc1"));
StructuredQueryDefinition containNegativeQuery = queryBuilder.containerQuery(queryBuilder.jsonProperty("path"), queryBuilder.term("*/bbb/*"));
StructuredQueryDefinition containQuery = qb.andNot(containPositiveQuery, containNegativeQuery);

I want the result to search for the name "newDoc1" but not in the path which contains "*/bbb/*". The above code is not working. What could be the reason?


问:
Is PrintWriter buffered?
I know that the PrintWriter is really good if we want to write formatted data, and I also know the use of BufferedWriter to improve IO performance.

But I tried something like this,

```<code>PrintWriter pw = new PrintWriter(System.out);
pw.println("Statement 1");
pw.println("Statement 2");
//pw.flush();
</code>```

I observed that when the flush method is commented there is no output, but when I uncomment it, I get the desired output.

This is only possible if the PrintWriter is buffered. If so, then what is the point of wrapping a PrintWriter using a BufferedWriter and then writing it?

Though the javadoc doesn't mention anywhere that the PrintWriter is buffered, but it seems so.

答: I think that since PrintWriter too can read the String at once, it would be using the buffer. </p>

Title: Is PrintWriter buffered?

Body:
I know that the PrintWriter is really good if we want to write formatted data, and I also know the use of BufferedWriter to improve IO performance.

But I tried something like this,

PrintWriter pw = new PrintWriter(System.out);
pw.println("Statement 1");
pw.println("Statement 2");
//pw.flush();

I observed that when the flush method is commented there is no output, but when I uncomment it, I get the desired output.

This is only possible if the PrintWriter is buffered. If so, then what is the point of wrapping a PrintWriter using a BufferedWriter and then writing it?

Though the javadoc doesn't mention anywhere that the PrintWriter is buffered, but it seems so.


问:
Friendship and Interfaces
I'm having a compilation error using Apple's Clang 7.0 with the following friendship code, using C++11 standard. I wonder what's really wrong with it since it seems to be valid for me. I'm describing the setting and the error I'm having:

MyInterface

```<code>namespace namespace1
{

class MyInterface
{
friend class MyClass;
public:
    virtual void some_method(void) = 0;
    ...
private:
    type some_attribute;
    ...
}

}
</code>```

MyClass::MyMethod Implementation

```<code>namespace namespace2
{

void MyClass::MyMethod(MyInterface* MyConcrete)
{
    ...
    // MyConcrete implements MyInterface
    if(MyConcrete->some_attribute == some_value) // Error*
    {
       ...
    }
    ...
}

}
</code>```

Error

```<code>error: 'some_attribute' is a private member of 'namespace1::MyInterface'
</code>```

I really expected that MyClass would have access to some_attribute in MyConcrete (which implemented MyInterface) regardless of the class access modifier. Any clues why this error is happening? Any suggestions?

Thank you!

答:
MyClass is in namespace2. So you need to use:

```<code>friend class namespace2::MyClass;
</code>```

You may also need to use forward decleration of MyClass before you define MyInterface.

Here's an example that compiles:

```<code>// forward decleration
namespace namespace2
{
    class MyClass;
}

namespace namespace1
{
    class MyInterface
    {
        friend class namespace2::MyClass; // added missing namespace
    public:
        virtual void some_method(void) = 0;

    private:
        int some_attribute;
    };
}

namespace namespace2
{
    class MyClass
    {
        void MyMethod(namespace1::MyInterface* MyConcrete)
        {
            if(MyConcrete->some_attribute == 1)
            {
            }
        }
    };
}

int main()
{
}
</code>```

You can run it here.

Title: Friendship and Interfaces

Body:
I'm having a compilation error using Apple's Clang 7.0 with the following friendship code, using C++11 standard. I wonder what's really wrong with it since it seems to be valid for me. I'm describing the setting and the error I'm having:

MyInterface

namespace namespace1
{

class MyInterface
{
friend class MyClass;
public:
    virtual void some_method(void) = 0;
    ...
private:
    type some_attribute;
    ...
}

}

MyClass::MyMethod Implementation

namespace namespace2
{

void MyClass::MyMethod(MyInterface* MyConcrete)
{
    ...
    // MyConcrete implements MyInterface
    if(MyConcrete->some_attribute == some_value) // Error*
    {
       ...
    }
    ...
}

}

Error

error: 'some_attribute' is a private member of 'namespace1::MyInterface'

I really expected that MyClass would have access to some_attribute in MyConcrete (which implemented MyInterface) regardless of the class access modifier. Any clues why this error is happening? Any suggestions?

Thank you!

Body:
MyClass is in namespace2. So you need to use:

friend class namespace2::MyClass;

You may also need to use forward decleration of MyClass before you define MyInterface.

Here's an example that compiles:

// forward decleration
namespace namespace2
{
    class MyClass;
}

namespace namespace1
{
    class MyInterface
    {
        friend class namespace2::MyClass; // added missing namespace
    public:
        virtual void some_method(void) = 0;

    private:
        int some_attribute;
    };
}

namespace namespace2
{
    class MyClass
    {
        void MyMethod(namespace1::MyInterface* MyConcrete)
        {
            if(MyConcrete->some_attribute == 1)
            {
            }
        }
    };
}

int main()
{
}

You can run it here.


问:
Easy way to store and retrieve objects in Java without using a relational DB?
Do you know of an "easy" way to store and retrieve objects in Java without using a relational DB / ORM like Hibernate?

[Note that I am not considering serialization as-is for this purpose, as it won't allow to retrieve arbitrary objects in the middle of an object graph. Neither am I considering DB4O because of its restrictive license. Thanks.]

"Easy" meaning: not having to handle low-level details such as key/value pairs to rebuild an object graph (as with BerkeleyDB or traditional caches). The same applies for rebuilding objects from a document- or column-oriented DB (CouchDB, HBase, ..., even Lucene).

Perhaps there are interesting projects out there that provide a layer of integration between the mentioned storage systems and the object model (like ORM would be for RDBMSs) that I am not aware of.

Anyone successfully using those in production, or experimenting with persistence strategies other than relational DBs? How about RDF stores?

Update: I came across a very interesting article: A list of distributed key-value stores

答:
Hmm... without serialization, and without an ORM solution, I would fall back to some sort of XML based implementation?  You'd still have to design it carefully if you want to pull out only some of the objects from the object graph - perhaps a different file for each object, where object relationships are referenced by a URI to another file?

I would have said that wasn't "easy" because I've always found designing the mapping of XML to objects to be somewhat time consuming, but I was really inspired by a conversation on Apache Betwixt that has me feeling hopeful that I'm just out of date, and easier solutions are now available.

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: bethlakshmi


问:
Align inline ordered DIVs?
How do I align part of child divs inline if I use display: flex; flex-direction: column; for the paternal div?

I tried to use display: inline-block for the child divs, also float:left, but no one of this work.

#container {
  display: flex;
  flex-direction: column;
}
.item
{
  border: 1px dotted;
  width: 100px;
  height: 100px;
}
.item1 {
  order: 2;
}
.item2 {
  order: 1;
}
.item3 {
  order: 3;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">
  <div class="item1 item" >2</div>
  <div class="item2 item" >1</div>
  <div class="item3 item" >3</div>
</div></code>```

答:
#container {
  display: flex;
  flex-wrap: wrap;
}

.item  { display: flex; }
.item1 { flex: 1 0 45%; order: 2; }
.item2 { flex: 1 0 60%; order: 1; }
.item3 { flex: 1 0 45%; order: 3; }

.item > span {
  border: 1px dotted;
  width: 100px;
  height: 100px;
  margin: 5px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.item2 > span { margin: 0 auto;    }
.item1 > span { margin-left: auto; }
.item3 > span { margin-right: auto;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">
  <div class="item1 item"><span>2</span></div>
  <div class="item2 item"><span>1</span></div>
  <div class="item3 item"><span>3</span></div>
</div></code>```

Title: Align inline ordered DIVs?

Body:
How do I align part of child divs inline if I use display: flex; flex-direction: column; for the paternal div?

I tried to use display: inline-block for the child divs, also float:left, but no one of this work.

#container {
  display: flex;
  flex-direction: column;
}
.item
{
  border: 1px dotted;
  width: 100px;
  height: 100px;
}
.item1 {
  order: 2;
}
.item2 {
  order: 1;
}
.item3 {
  order: 3;
}

2

1

3

Body:
#container {
  display: flex;
  flex-wrap: wrap;
}

.item  { display: flex; }
.item1 { flex: 1 0 45%; order: 2; }
.item2 { flex: 1 0 60%; order: 1; }
.item3 { flex: 1 0 45%; order: 3; }

.item > span {
  border: 1px dotted;
  width: 100px;
  height: 100px;
  margin: 5px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.item2 > span { margin: 0 auto;    }
.item1 > span { margin-left: auto; }
.item3 > span { margin-right: auto;}

<div id="container">
  <div class="item1 item"><span>2</span></div>
  <div class="item2 item"><span>1</span></div>
  <div class="item3 item"><span>3</span></div>
</div>


问:
how to suppress ssl on a single controller
I have config.force_ssl = true in my production.rb for a Ruby on Rails 5 app but need to have a single controller NOT force_ssl. Is this possible without configuring each controller? Is there a way to unforce_ssl within a single controller?

答:
according to this page

You can pass any of the following options to affect the before_action
callback

only - The callback should be run only for this action

except - The callback should be run for all actions except this action

if - A symbol naming an instance method or a proc; the callback will be called only when it returns a true value.

unless - A symbol naming an instance method or a proc; the callback will be called only when it returns a false value.

This is using the controller level force_ssl though.

The config level force_ssl, is application wide


问:
Is there a downloadable Scipy file for Python 3.6
I have Python 3.6 and I was wondering if there is a downloadable scipy file for version 3.6. I opened up the command prompt and ran "py -m pip install scipy". And it just gives me an error. I know its not the pip because its already updated. When I did it for nltk and numpy it worked but it doesn't work for scipy. I read somewhere that you have to download and install 3.4 because scipy is not compatible with 3.6. Any answer would be very much appreciated thank you</p>

答:
I had the same problem but i now use anaconda and this has it already installed.. as well as most science data modules..

https://docs.continuum.io/anaconda/pkg-docs


答:
You could create a secure controller:

```<code>class SecureController < ApplicationController
  force_ssl
end
</code>```

Then you can make all controllers inherit SecureController

```<code>class ThingsController < SecureController
  ...
end
</code>```

Except for the one in question. You'll have to make a one-time change to all controllers that you want this to apply to, but the good news is that you'll only have to do it once, and you then have the ability to extend functionality to SecureController. Sounds like your question is asking for a way to :skip, or :except on a before_action, but most Rails developers I know agree that this is the way it should be done.

Title: how to suppress ssl on a single controller

Body: I have config.force_ssl = true in my production.rb for a Ruby on Rails 5 app but need to have a single controller NOT force_ssl. Is this possible without configuring each controller? Is there a way to unforce_ssl within a single controller?

Body:
You could create a secure controller:

class SecureController < ApplicationController
  force_ssl
end

Then you can make all controllers inherit SecureController

class ThingsController < SecureController
  ...
end

Except for the one in question. You'll have to make a one-time change to all controllers that you want this to apply to, but the good news is that you'll only have to do it once, and you then have the ability to extend functionality to SecureController. Sounds like your question is asking for a way to :skip, or :except on a before_action, but most Rails developers I know agree that this is the way it should be done.


问:
Telnet not valid when opening command prompt with Ruby
When I open a command prompt manually and type the following command I get a response from the server I am pinging.

```<code>telnet <server> <port>
</code>```

When I open the command prompt with Ruby, using the following command, and run the same telnet command above, I get ''telnet' is not recognized as an internal or external command, operable program or batch file.'

Ruby command:

```<code>system('start cmd.exe)
</code>```

It opens the prompt fine, but the command itself is not working, and I am not sure to why that is.

答:
cmd.exe is not located at the place from which you have run irb (or whatever is your ruby shell.

You need to pass the full-path to cmd.exe, include escapes for any illegal path characters, e.g. C:\some\folder\path\to\cmd.exe

```<code>system('start C:\some\folder\path\to\cmd.exe')
</code>```

Body:
When I open a command prompt manually and type the following command I get a response from the server I am pinging.

telnet <server> <port>

When I open the command prompt with Ruby, using the following command, and run the same telnet command above, I get ''telnet' is not recognized as an internal or external command, operable program or batch file.'

Ruby command:

system('start cmd.exe)

It opens the prompt fine, but the command itself is not working, and I am not sure to why that is.

Body:
cmd.exe is not located at the place from which you have run irb (or whatever is your ruby shell.

You need to pass the full-path to cmd.exe, include escapes for any illegal path characters, e.g. C:\some\folder\path\to\cmd.exe

system('start C:\some\folder\path\to\cmd.exe')


问:
Is it necessary to include GameObjects whose physics are deterministic in worldUpdate?
In order to reduce data transfer size and the computational time for serializing world objects for each worldUpdate, I was wondering if it is possible to omit syncs for objects whose physics can be entirely, faithfully simulated on the client-side gameEngine (they are not playerObjects so playerInput does not affect them directly, and their physics are entirely deterministic). Interactions with these GameObjects would be entirely handled by GameEvents that are much less frequent. I feel like this should be possible if the client is running the same physics as the server and has access to the same initial conditions.

When I try to omit GameObjects from subsequent worldUpdates, I see that their motion becomes more choppy and they move faster than if they were not omitted; however, when I stop the game server while keeping the client open, their motion is more like what I would expect if I hadn't omitted them. This is all on my local machine with extrapolation synchronization.

答:
The short answer is that the latest version of Lance (1.0.8 at the time of this writing) doesn't support user omission of game objects from world updates, but it does implement a diffing mechanism that omits objects from the update if their netScheme properties haven't changed, saving up on bandwidth.

This means that if you have static objects, like walls, for example, they will only get transmitted once for each player. Not transmitting this at all is an interesting feature to have.

If objects you're referring to are not static, then there is no real way to know their position deterministically. You might have considered using the world step count, but different clients process different world steps at different times due to the web's inherent latency. A client can't know what is the true step being handled by the server at a given point in time, so it cannot deterministically decide on such an object's position. This is why Lance uses the Authoritative server model - to allow one single source of truth, and make sure clients are synched up.

If you still want to manually avoid sending updates for an object, you can edit its netScheme so that it doesn't return anything but its id, for example:

```<code>static get netScheme() {
    return {
        id: { type: Serializer.TYPES.INT32 }
    };
}
</code>```

Though it's not a typical use due to the aforementioned reasons, so if you encounter specific sync issues and this is still a feature you're interested in, it's best if you submit a feature request in the Lance issue tracker. Make sure to include details on your use case to promote a healthy discussion

Body:
The short answer is that the latest version of Lance (1.0.8 at the time of this writing) doesn't support user omission of game objects from world updates, but it does implement a diffing mechanism that omits objects from the update if their netScheme properties haven't changed, saving up on bandwidth.

This means that if you have static objects, like walls, for example, they will only get transmitted once for each player. Not transmitting this at all is an interesting feature to have.

If objects you're referring to are not static, then there is no real way to know their position deterministically. You might have considered using the world step count, but different clients process different world steps at different times due to the web's inherent latency. A client can't know what is the true step being handled by the server at a given point in time, so it cannot deterministically decide on such an object's position. This is why Lance uses the Authoritative server model - to allow one single source of truth, and make sure clients are synched up.

If you still want to manually avoid sending updates for an object, you can edit its netScheme so that it doesn't return anything but its id, for example:

static get netScheme() {
    return {
        id: { type: Serializer.TYPES.INT32 }
    };
}

Though it's not a typical use due to the aforementioned reasons, so if you encounter specific sync issues and this is still a feature you're interested in, it's best if you submit a feature request in the Lance issue tracker. Make sure to include details on your use case to promote a healthy discussion


问:
codeigniter array
How can I grab this data and increment it in Codeigniter?</p>

```<code>$_SESSION['cart'][$_GET[id]]++;
</code>```

答:
because CI destroys the $_GET array, you can do this

$_SESSION['cart'][$this->uri->segment(3)]++;

where 3 is the URL segment of the ID. But I would look in to the shopping cart class as recommended by Malachi.

from the docs ~

```<code>$data = array(
               'rowid' => 'b99ccdf16028f015540f341130b6d8ec',
               'qty'   => 3
            );

$this->cart->update($data);
</code>```

Title: codeigniter array

Body:
How can I grab this data and increment it in Codeigniter?

$_SESSION['cart'][$_GET[id]]++;

Body:
because CI destroys the $_GET array, you can do this

$_SESSION['cart'][$this->uri->segment(3)]++;

where 3 is the URL segment of the ID. But I would look in to the shopping cart class as recommended by Malachi.

from the docs ~

$data = array(
               'rowid' => 'b99ccdf16028f015540f341130b6d8ec',
               'qty'   => 3
            );

$this->cart->update($data);


问:
Trouble with ACCESS VBA INSERT INTO
I am getting an error with this INSERT INTO that I just can not seem to figure out. The code iterates through a Dao recordset to append only certain records to a table.

```<code>    Dim maxDate As Variant

Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim sqlinsert As String

maxDate = DMax("[Eff Date]", "400_CF_BREAK_LOG")
Set db = CurrentDb

Set rs = db.OpenRecordset("860_APPEND_DIFFERENCES")
If Not rs.BOF Then
    'populate the table
    rs.MoveFirst
    Do
        If (rs![Eff Date] > maxDate Or IsNull(maxDate)) Then
            sqlinsert = "INSERT INTO 400_CF_BREAK_LOG (Eff Date, PrimarySecurity ID Number, CUSIP(Aladdin ID), IsrName, Asset Type, Metlife Port Code, Business Unit, Principal Difference, Total PAM Principal, Total Aladdin Principal,Income Difference, Total PAM Interest,Total Aladdin Interest,Total CF Difference,Total PAM CF,PAM Coupon)" & _
            " VALUES ('" & rs("Eff Date") & "', '" & rs("PrimarySecurity ID Number") & "', '" & rs("CUSIP(Aladdin ID)") & "', '" & rs("IsrName") & "', '" & rs("Asset Type") & "', '" & rs("Metlife Port Code") & "', '" & rs("Business Unit") & "', '" & rs("Principal Difference") & "',  '" & rs("Total PAM Principal") & "',  '" & rs("Total Aladdin Principal") & "','" & rs("Income Difference") & "', '" & rs("Total PAM Interest") & "', '" & rs("Total Aladdin Interest") & "', '" & rs("Total CF Difference") & "', '" & rs("Total PAM CF") & "', '" & rs("PAM Coupon") & "') "
            DoCmd.RunSQL (sqlinsert)
        End If
        rs.MoveNext
    Loop Until rs.EOF
End If
</code>```

I keep getting Syntax error in INSERT INTO statement, but I have checked it over a couple times.

EDIT - Explanation. Tags

答:
Names with spaces or punctuation/special characters (only exception is underscore) need to be enclosed in [ ]. Best to avoid these in naming convention. However, references to the recordset fields with quote marks should work without enclosing in [ ]. An alternate syntax that would require [ ] is: rs![Eff Date].

```<code>sqlinsert = "INSERT INTO 400_CF_BREAK_LOG ([Eff Date], [PrimarySecurity ID Number],
[CUSIP(Aladdin ID)], IsrName, [Asset Type], [Metlife Port Code], [Business Unit],
[Principal Difference], [Total PAM Principal], [Total Aladdin Principal],
[Income Difference], [Total PAM Interest], [Total Aladdin Interest], [Total CF Difference],
[Total PAM CF], [PAM Coupon])" & _
" VALUES ('" & rs("Eff Date") & "', '" & rs("PrimarySecurity ID Number") & "', '" &
rs("CUSIP(Aladdin ID)") & "', '" & rs("IsrName") & "', '" & rs("Asset Type") & "', '" &
rs("Metlife Port Code") & "', '" & rs("Business Unit") & "', '" & rs("Principal Difference") & "',  '" &
rs("Total PAM Principal") & "',  '" & rs("Total Aladdin Principal") & "','" &
rs("Income Difference") & "', '" & rs("Total PAM Interest") & "', '" &
rs("Total Aladdin Interest") & "', '" & rs("Total CF Difference") & "', '" & rs("Total PAM CF") & "', '" &
rs("PAM Coupon") & "') "
</code>```

Title: Trouble with ACCESS VBA INSERT INTO

Body:
I am getting an error with this INSERT INTO that I just can not seem to figure out. The code iterates through a Dao recordset to append only certain records to a table.

    Dim maxDate As Variant

Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim sqlinsert As String

maxDate = DMax("[Eff Date]", "400_CF_BREAK_LOG")
Set db = CurrentDb

Set rs = db.OpenRecordset("860_APPEND_DIFFERENCES")
If Not rs.BOF Then
    'populate the table
    rs.MoveFirst
    Do
        If (rs![Eff Date] > maxDate Or IsNull(maxDate)) Then
            sqlinsert = "INSERT INTO 400_CF_BREAK_LOG (Eff Date, PrimarySecurity ID Number, CUSIP(Aladdin ID), IsrName, Asset Type, Metlife Port Code, Business Unit, Principal Difference, Total PAM Principal, Total Aladdin Principal,Income Difference, Total PAM Interest,Total Aladdin Interest,Total CF Difference,Total PAM CF,PAM Coupon)" & _
            " VALUES ('" & rs("Eff Date") & "', '" & rs("PrimarySecurity ID Number") & "', '" & rs("CUSIP(Aladdin ID)") & "', '" & rs("IsrName") & "', '" & rs("Asset Type") & "', '" & rs("Metlife Port Code") & "', '" & rs("Business Unit") & "', '" & rs("Principal Difference") & "',  '" & rs("Total PAM Principal") & "',  '" & rs("Total Aladdin Principal") & "','" & rs("Income Difference") & "', '" & rs("Total PAM Interest") & "', '" & rs("Total Aladdin Interest") & "', '" & rs("Total CF Difference") & "', '" & rs("Total PAM CF") & "', '" & rs("PAM Coupon") & "') "
            DoCmd.RunSQL (sqlinsert)
        End If
        rs.MoveNext
    Loop Until rs.EOF
End If

I keep getting Syntax error in INSERT INTO statement, but I have checked it over a couple times.

EDIT - Explanation. Tags

Body:
Names with spaces or punctuation/special characters (only exception is underscore) need to be enclosed in [ ]. Best to avoid these in naming convention. However, references to the recordset fields with quote marks should work without enclosing in [ ]. An alternate syntax that would require [ ] is: rs![Eff Date].

sqlinsert = "INSERT INTO 400_CF_BREAK_LOG ([Eff Date], [PrimarySecurity ID Number],
[CUSIP(Aladdin ID)], IsrName, [Asset Type], [Metlife Port Code], [Business Unit],
[Principal Difference], [Total PAM Principal], [Total Aladdin Principal],
[Income Difference], [Total PAM Interest], [Total Aladdin Interest], [Total CF Difference],
[Total PAM CF], [PAM Coupon])" & _
" VALUES ('" & rs("Eff Date") & "', '" & rs("PrimarySecurity ID Number") & "', '" &
rs("CUSIP(Aladdin ID)") & "', '" & rs("IsrName") & "', '" & rs("Asset Type") & "', '" &
rs("Metlife Port Code") & "', '" & rs("Business Unit") & "', '" & rs("Principal Difference") & "',  '" &
rs("Total PAM Principal") & "',  '" & rs("Total Aladdin Principal") & "','" &
rs("Income Difference") & "', '" & rs("Total PAM Interest") & "', '" &
rs("Total Aladdin Interest") & "', '" & rs("Total CF Difference") & "', '" & rs("Total PAM CF") & "', '" &
rs("PAM Coupon") & "') "


问:
How to pass onChange to a stateless component
I have been playing around with reactjs, and building some basic forms all works good but then it became complicated when i tried to break into smaller compoments
i have a simple component that has a form in it called XMLParser, and it has 2 smaller components inside called XMLInput and XMLResult.

XMLResult is pretty straight forward it just passes the value to as the props, but couldnt figure out what is the best approact to use XMLInput i couldnt get the binding to work with the child component, thanks for any pointers.

```<code>function EppResult(props) {
    const resultXML = props.xmlData;
 return <div style={styles.child}>
        <textarea style={styles.outputBox} name="resultXML" value={resultXML} readOnly/>
    </div>;

}

class EppInput extends Component{

  render(){
  return <textarea
    style={styles.inputBox}
    placeholder="Enter XML here!"
    name="xmlData"
    value={this.props.value}
    onChange={this.props.handleInputChange}
  />;
}
}

    class XMLParser extends Component {
        constructor(props) {
            super(props);

        this.state = {xmlData : ""};
        this.state = {resultXML : ""};
            this.handleInputChange = this.handleInputChange.bind(this);
            this.handleSubmit = this.handleSubmit.bind(this);
        }

handleSubmit(event) {
    console.log("do submit");
}

        handleInputChange(event) {
            const target = event.target;
            const value = target.type === "checkbox" ? target.checked : target.value;
            const name = target.name;
            this.setState({
                [name]: value
            });
        }

render() {
        return (
            <div style={styles.container}>
                <form onSubmit={this.handleSubmit}>
                    <div style={styles.container}>
                        <div style={styles.child}>
                        <XMLInput value={this.state.xmlData} onChange={this.handleInputChange} />
                        </div>
                        <div style={styles.child}>
                            <div style={styles.formContainer}>

                                <button style={styles.formElement}>Run!</button>
                            </div>
                        </div>
            <XMLResult xmlData={this.state.resultXML}/>
                    </div>
                </form>
            </div>
        );
    }
}
</code>```

答:
I'm seeing a number of problems:

EppInput is the sub-component name, but XMLInput is used in the main component

You pass an    onChange prop, but refer to it as
this.props.handleInputChange --    it should be
this.props.onChange

Just a note--I don't know where the styles object is, but I'm going
to assume it's available to all the components

I haven't tested this, but here's a basic cleanup, with some alterations to see some other ways of doing things:

```<code>// stateless functional component
const XMLResult = ({ xmlData }) => (
  <div style={styles.child}>
    <textarea
      style={styles.outputBox}
      name="resultXML"
      value={xmlData}
      readOnly
    />
  </div>
);

// stateless functional component
// props are passed directly to the child element using the spread operator
const XMLInput = (props) => (
  <textarea
    {...props}
    style={styles.inputBox}
    placeholder="Enter XML here!"
    name="xmlData"
  />
);

class XMLParser extends Component {
  constructor(props) {
    super(props);
    this.state = { xmlData: "", resultXML: "" };
    this.handleInputChange = this.handleInputChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit(event) {
    console.log("do submit");
  }

  handleInputChange(event) {
    const target = event.target;
    const value = target.type === "checkbox" ? target.checked : target.value;
    const name = target.name;
    this.setState({
      [name]: value
    });
  }

  render() {
    return (
      <div style={styles.container}>
        <form onSubmit={this.handleSubmit}>
          <div style={styles.container}>
            <div style={styles.child}>
              <XMLInput
                value={this.state.xmlData}
                onChange={this.handleInputChange}
              />
            </div>
            <div style={styles.child}>
              <div style={styles.formContainer}>
                <button style={styles.formElement}>Run!</button>
              </div>
            </div>
            <XMLResult xmlData={this.state.resultXML} />
          </div>
        </form>
      </div>
    );
  }
}
</code>```

Body:
I have been playing around with reactjs, and building some basic forms all works good but then it became complicated when i tried to break into smaller compoments
i have a simple component that has a form in it called XMLParser, and it has 2 smaller components inside called XMLInput and XMLResult.

XMLResult is pretty straight forward it just passes the value to as the props, but couldnt figure out what is the best approact to use XMLInput i couldnt get the binding to work with the child component, thanks for any pointers.

function EppResult(props) {
    const resultXML = props.xmlData;
 return

        <textarea style={styles.outputBox} name="resultXML" value={resultXML} readOnly/>

;

}

class EppInput extends Component{

  render(){
  return <textarea
    style={styles.inputBox}
    placeholder="Enter XML here!"
    name="xmlData"
    value={this.props.value}
    onChange={this.props.handleInputChange}
  />;
}
}

    class XMLParser extends Component {
        constructor(props) {
            super(props);

        this.state = {xmlData : ""};
        this.state = {resultXML : ""};
            this.handleInputChange = this.handleInputChange.bind(this);
            this.handleSubmit = this.handleSubmit.bind(this);
        }

handleSubmit(event) {
    console.log("do submit");
}

        handleInputChange(event) {
            const target = event.target;
            const value = target.type === "checkbox" ? target.checked : target.value;
            const name = target.name;
            this.setState({
                [name]: value
            });
        }

render() {
        return (

                <form onSubmit={this.handleSubmit}>

                        <XMLInput value={this.state.xmlData} onChange={this.handleInputChange} />

                                <button style={styles.formElement}>Run!</button>

            <XMLResult xmlData={this.state.resultXML}/>

                </form>

        );
    }
}

Body:
I'm seeing a number of problems:

EppInput is the sub-component name, but XMLInput is used in the main component

You pass an    onChange prop, but refer to it as
this.props.handleInputChange --    it should be
this.props.onChange

Just a note--I don't know where the styles object is, but I'm going
to assume it's available to all the components

I haven't tested this, but here's a basic cleanup, with some alterations to see some other ways of doing things:

// stateless functional component
const XMLResult = ({ xmlData }) => (
  <div style={styles.child}>
    <textarea
      style={styles.outputBox}
      name="resultXML"
      value={xmlData}
      readOnly
    />
  </div>
);

// stateless functional component
// props are passed directly to the child element using the spread operator
const XMLInput = (props) => (
  <textarea
    {...props}
    style={styles.inputBox}
    placeholder="Enter XML here!"
    name="xmlData"
  />
);

class XMLParser extends Component {
  constructor(props) {
    super(props);
    this.state = { xmlData: "", resultXML: "" };
    this.handleInputChange = this.handleInputChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit(event) {
    console.log("do submit");
  }

  handleInputChange(event) {
    const target = event.target;
    const value = target.type === "checkbox" ? target.checked : target.value;
    const name = target.name;
    this.setState({
      [name]: value
    });
  }

  render() {
    return (
      <div style={styles.container}>
        <form onSubmit={this.handleSubmit}>
          <div style={styles.container}>
            <div style={styles.child}>
              <XMLInput
                value={this.state.xmlData}
                onChange={this.handleInputChange}
              />
            </div>
            <div style={styles.child}>
              <div style={styles.formContainer}>
                <button style={styles.formElement}>Run!</button>
              </div>
            </div>
            <XMLResult xmlData={this.state.resultXML} />
          </div>
        </form>
      </div>
    );
  }
}


问:
Python sum elements between two numbers
I'm sure this is very simple. I've searched google and here and not found the specific answer

```<code>a = rnd.randn(100)
print np.sum(a)
</code>```

gives sum of elements in a

```<code>np.sum(a[a>0.])
</code>```

gives sum of elements greater than 0

```<code>print np.sum((a < 2.0) & (a > -2.0))
</code>```

ok so this returns the number of elements between 2 and -2.

how do I get the sum of the elements between2 and -2??? I've tried lots of things for example

```<code>np.sum(a[a >0.] & a[a<1.])
</code>```

etc and can't find the correct way to do it :-(

答:
& is a bitwise operator and doesn't give you the proper result, instead you need to use np.logical_and to get a mask array. Then you can pass it as the index to the array in order to get the desire items, then pass it to the sum:

```<code>In [9]: a = np.arange(-10, 10)

In [10]: a[np.logical_and(a>-2,a<2)]
Out[10]: array([-1,  0,  1])

In [11]: a[np.logical_and(a>-2,a<2)].sum()
Out[11]: 0
</code>```

Title: Python sum elements between two numbers

Body:
I'm sure this is very simple. I've searched google and here and not found the specific answer

a = rnd.randn(100)
print np.sum(a)

gives sum of elements in a

np.sum(a[a>0.])

gives sum of elements greater than 0

print np.sum((a < 2.0) & (a > -2.0))

ok so this returns the number of elements between 2 and -2.

how do I get the sum of the elements between2 and -2??? I've tried lots of things for example

np.sum(a[a >0.] & a[a<1.])

etc and can't find the correct way to do it :-(

Body:
& is a bitwise operator and doesn't give you the proper result, instead you need to use np.logical_and to get a mask array. Then you can pass it as the index to the array in order to get the desire items, then pass it to the sum:

In [9]: a = np.arange(-10, 10)

In [10]: a[np.logical_and(a>-2,a<2)]
Out[10]: array([-1,  0,  1])

In [11]: a[np.logical_and(a>-2,a<2)].sum()
Out[11]: 0


问:
AMP PHP Contact Form Don't Redirect (Google AMP)
I have HTML form in AMP, with POST action; PHP file for emails use Sendgrid API. I was try headers response for Json redirect, but, don't works.

For this reason i applied JavaScript redirect (yes, i know, this generate error for AMP validation, but i need redirect to thanks page for track online conversions).

PHP file works fine, all emails are send it's, but whithout JavaScript redirect, only with div success or error for email send, only i see error for send email, but, contradictorily, all emails are send it's without problems LOL through Sendgrid API).

So, i need redirect the HTML contact form with correct PHP header Json response (without JavaScript), for track online conversions and validate correctly my AMP HTML source. In other case, i think to it's very useful make a correct redirect from PHP file after success submission (to i try redirect with header location in PHP, but, don't works...)

Form:

<form method="post"
  class="p2"
  action-xhr="//example.com/path/themex/amp-theme/path/file.php"
  target="_top">

    <input type="text"
      class="block border-none p0 m0"
      name="name"
      placeholder="Nombre"
      required>
    <input type="tel"
      class="block border-none p0 m0"
      name="tel"
      placeholder="Teléfono"
      required>

  <select name="store"
      id="store">
      <option value="San Antonio">San Antonio</option>
      <option value="Santiago Centro">Santiago Centro</option>
      <option value="San Bernardo">San Bernardo</option>
      <option value="Puente Alto">Puente Alto</option>
      <option value="Rancagua">Rancagua</option>
      <option value="Chillán">Chillán</option>
      <option value="Talca">Talca</option>
      <option value="Concepción">Concepción</option>
      <option value="Los Ángeles">Los Ángeles</option>
      <option value="Linares">Linares</option>
      <option value="Valdivia">Valdivia</option>
      <option value="Temuco">Temuco</option>
      <option value="Puerto Montt">Puerto Montt</option>
    </select>
    Selecione una Ciudad
  <input type="submit"
    value="Enviar"
    class="ampstart-btn caps" onclick="redirectThanks()">

    <template type="amp-mustache">
      Success! Thanks {{name}} for trying the
      amp-form demo! Try to insert the word "error" as a name input in the form to see how
      amp-form handles errors.
    </template>

    <template type="amp-mustache">
      Error! Thanks {{name}} for trying the
      amp-form demo with an error response.
    </template>

</form>```
</div>
</div>
</p>

<p>PHP post:</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><?php
/*SendGrid Library*/
require_once ('vendor/autoload.php');

/*Post Data*/
$name = $_POST['name'];
$tel = $_POST['tel'];
$store = $_POST['store'];

/*Content*/
  $from = new SendGrid\Email("Sender", "no-reply@example.com");
$subject = "My Subject {$store}";
$to = new SendGrid\Email("Recipient", "address@example.com");
$content = new SendGrid\Content("text/html", "
 Name: {$name}<br>
 Phone: {$tel}<br>
 Store: {$store}
 ");

/*Send the mail*/
$mail = new SendGrid\Mail($from, $subject, $to, $content);
$apiKey = ('mysendgridapikeyhash');
$sg = new \SendGrid($apiKey);

/*Response*/
$response = $sg->client->mail()->send()->post($mail);

header("Content-type: application/json");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Origin: *.ampproject.org");
header("AMP-Access-Control-Allow-Source-Origin: https://www.example.com/");
header("Access-Control-Expose-Headers: AMP-Access-Control-Allow-Source-Origin");
header ('AMP-Redirect-To: https://www.example.com/thanks-page/amp/');

?></code>```

Any idea, please?

答:
I notice you specify an Access-Control-Expose-Headers header, and only added AMP-Access-Control-Allow-Source-Origin to it. The amp-form docs state that AMP-Redirect-To also needs to be exposed.

Try this:

header("Access-Control-Expose-Headers: AMP-Access-Control-Allow-Source-Origin, AMP-Redirect-To");
```

If that doesn't work, try opening the browser developer tools and adding any console errors to your question. If anything is going wrong, the AMP framework usually writes very helpful error messages in the console that are useful for diagnosing problems.

Body:
I have HTML form in AMP, with POST action; PHP file for emails use Sendgrid API. I was try headers response for Json redirect, but, don't works.

For this reason i applied JavaScript redirect (yes, i know, this generate error for AMP validation, but i need redirect to thanks page for track online conversions).

PHP file works fine, all emails are send it's, but whithout JavaScript redirect, only with div success or error for email send, only i see error for send email, but, contradictorily, all emails are send it's without problems LOL through Sendgrid API).

So, i need redirect the HTML contact form with correct PHP header Json response (without JavaScript), for track online conversions and validate correctly my AMP HTML source. In other case, i think to it's very useful make a correct redirect from PHP file after success submission (to i try redirect with header location in PHP, but, don't works...)

Form:

<form method="post"
  class="p2"
  action-xhr="//example.com/path/themex/amp-theme/path/file.php"
  target="_top">

    <input type="text"
      class="block border-none p0 m0"
      name="name"
      placeholder="Nombre"
      required>
    <input type="tel"
      class="block border-none p0 m0"
      name="tel"
      placeholder="Teléfono"
      required>

  <select name="store"
      id="store">
      <option value="San Antonio">San Antonio</option>
      <option value="Santiago Centro">Santiago Centro</option>
      <option value="San Bernardo">San Bernardo</option>
      <option value="Puente Alto">Puente Alto</option>
      <option value="Rancagua">Rancagua</option>
      <option value="Chillán">Chillán</option>
      <option value="Talca">Talca</option>
      <option value="Concepción">Concepción</option>
      <option value="Los Ángeles">Los Ángeles</option>
      <option value="Linares">Linares</option>
      <option value="Valdivia">Valdivia</option>
      <option value="Temuco">Temuco</option>
      <option value="Puerto Montt">Puerto Montt</option>
    </select>
    Selecione una Ciudad
  <input type="submit"
    value="Enviar"
    class="ampstart-btn caps" onclick="redirectThanks()">

    <template type="amp-mustache">
      Success! Thanks {{name}} for trying the
      amp-form demo! Try to insert the word "error" as a name input in the form to see how
      amp-form handles errors.
    </template>

    <template type="amp-mustache">
      Error! Thanks {{name}} for trying the
      amp-form demo with an error response.
    </template>

</form>

PHP post:

<?php
/*SendGrid Library*/
require_once ('vendor/autoload.php');

/*Post Data*/
$name = $_POST['name'];
$tel = $_POST['tel'];
$store = $_POST['store'];

/*Content*/
  $from = new SendGrid\Email("Sender", "no-reply@example.com");
$subject = "My Subject {$store}";
$to = new SendGrid\Email("Recipient", "address@example.com");
$content = new SendGrid\Content("text/html", "
 Name: {$name}

 Phone: {$tel}

 Store: {$store}
 ");

/*Send the mail*/
$mail = new SendGrid\Mail($from, $subject, $to, $content);
$apiKey = ('mysendgridapikeyhash');
$sg = new \SendGrid($apiKey);

/*Response*/
$response = $sg->client->mail()->send()->post($mail);

header("Content-type: application/json");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Origin: *.ampproject.org");
header("AMP-Access-Control-Allow-Source-Origin: https://www.example.com/");
header("Access-Control-Expose-Headers: AMP-Access-Control-Allow-Source-Origin");
header ('AMP-Redirect-To: https://www.example.com/thanks-page/amp/');

?>

Any idea, please?

Body:
I notice you specify an Access-Control-Expose-Headers header, and only added AMP-Access-Control-Allow-Source-Origin to it. The amp-form docs state that AMP-Redirect-To also needs to be exposed.

Try this:

header("Access-Control-Expose-Headers: AMP-Access-Control-Allow-Source-Origin, AMP-Redirect-To");

If that doesn't work, try opening the browser developer tools and adding any console errors to your question. If anything is going wrong, the AMP framework usually writes very helpful error messages in the console that are useful for diagnosing problems.


问:
Toggle CORS Setting dependent on build
I would like CORS to be enabled if I build a project using the development settings, and disabled if I use the production settings.

So far I have found you can have different config files based on this answer

What I am confused about is how I would apply this for cors

Basically I would want a Web.Debug.Config with cors enabled so something like so

```<code><customHeaders>
   <add name="Access-Control-Allow-Origin" value="*" />
 </customHeaders>
</code>```

And then Would I just not add in these Headers in the web.Release.Config?

答:
I think there is a far easier way of achieving what you want. You could use filters over the classes/methods that you want to enable/disable cors for and then use the #IF DEBUG directives. Example:

```<code>    #if DEBUG
    [EnableCors("","","")]
    #endif
    public class MyController : ApiController
    {
    }
</code>```

For this to work you need 2 things.

Add cors package from nugget

EnableCors in the Register method of your config class. Simply do context.EnableCors();

Title: Toggle CORS Setting dependent on build

Body:
I would like CORS to be enabled if I build a project using the development settings, and disabled if I use the production settings.

So far I have found you can have different config files based on this answer

What I am confused about is how I would apply this for cors

Basically I would want a Web.Debug.Config with cors enabled so something like so

<customHeaders>
   <add name="Access-Control-Allow-Origin" value="*" />
 </customHeaders>

And then Would I just not add in these Headers in the web.Release.Config?

Body:
I think there is a far easier way of achieving what you want. You could use filters over the classes/methods that you want to enable/disable cors for and then use the #IF DEBUG directives. Example:

    #if DEBUG
    [EnableCors("","","")]
    #endif
    public class MyController : ApiController
    {
    }

For this to work you need 2 things.

Add cors package from nugget

EnableCors in the Register method of your config class. Simply do context.EnableCors();


问:
State in Angular2 service not updated by ngrx/store
I'm having this reducer:

heroStore.reducer.ts

```<code>import { Action } from '@ngrx/store';
import {Hero} from '../models/hero';
import {BehaviorSubject} from 'rxjs/BehaviorSubject';

export const UPDATE = '[hero] UPDATE';

export function heroReducer(state: { [heroId: string]: BehaviorSubject<Hero>; } = {}, action: Action):
{ [heroId: string]: BehaviorSubject<Hero>; } {
  switch (action.type) {
    case UPDATE:
      let newState;
      const hero: Hero = action.payload;
      if (state[hero.uid]) { // hero exists
        newState = state[hero.uid].next(hero);
      } else {
        const heroObservable = new BehaviorSubject<Hero>(hero);
        newState = Object.assign({}, state, {[hero.uid]: heroObservable});
      }
      console.log('New State', newState);
      return newState;

    default:
      return state;
  }
}
</code>```

and the following service

hero.service.ts

```<code>getHero(heroId: string): BehaviorSubject<Hero> {
  let state;
  this.store.select('heroStore').subscribe(s => state = s);
  console.log('state returned in service', state);
  return state[heroId];
}
</code>```

And finally the following test:

```<code>  it('should be able to get a hero', inject([HeroService], (service: HeroService) => {
    expect(service).toBeTruthy();

    heroReducer({}, {
      type: '[hero] UPDATE',
      payload: {
        uid: '5',
        name: 'Franz'
      }
    });

    const heroObs = service.getHero('5');
    expect(heroObs.getValue().name).toEqual('Franz');

  }));
</code>```

But somehow the state doesn't get updated. It produces the following logs:

LOG: 'New State', Object{5: BehaviorSubject{_isScalar: false,
  observers: [], closed: false, isStopped: false, hasError: false,
  thrownError: null, _value: Object{uid: ..., name: ...}}}

LOG: 'state returned in service', Object{}

So the reducer actually returns the correct new state. But when subscribed upon in the service, I still get an empty object.

If I understand correctly, a store in ngrx/store is a rxjs BehaviorSubject, which in turn is supposed to return the last value on subscription. From the docs of BehaviorSubject:

Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications

So how is it possible that state is still an empty object?

答:
Your getHero is not coded properly and I think it returns an unassigned value. A better way to write it would be:

```<code>getHero(heroId: string): BehaviorSubject<Hero> {
  let state = new BehaviorSubject<Hero>();
  this.store.select('heroStore').subscribe(s => state.next(s[heroId]));
  return state;
}
</code>```

or even better:

```<code>getHero(heroId: string): Observable<Heor> {
    return this.store.select('heroStore')
        .map(heros => heros[heroId];
}
</code>```

or if you want to really go elegant, this might work:

```<code>getHero(heroId: string): Observable<Heor> {
    return this.store.select('heroStore', heroId);
}
</code>```

Body:
I'm having this reducer:

heroStore.reducer.ts

import { Action } from '@ngrx/store';
import {Hero} from '../models/hero';
import {BehaviorSubject} from 'rxjs/BehaviorSubject';

export const UPDATE = '[hero] UPDATE';

export function heroReducer(state: { [heroId: string]: BehaviorSubject<Hero>; } = {}, action: Action):
{ [heroId: string]: BehaviorSubject<Hero>; } {
  switch (action.type) {
    case UPDATE:
      let newState;
      const hero: Hero = action.payload;
      if (state[hero.uid]) { // hero exists
        newState = state[hero.uid].next(hero);
      } else {
        const heroObservable = new BehaviorSubject<Hero>(hero);
        newState = Object.assign({}, state, {[hero.uid]: heroObservable});
      }
      console.log('New State', newState);
      return newState;

    default:
      return state;
  }
}

and the following service

hero.service.ts

getHero(heroId: string): BehaviorSubject<Hero> {
  let state;
  this.store.select('heroStore').subscribe(s => state = s);
  console.log('state returned in service', state);
  return state[heroId];
}

And finally the following test:

  it('should be able to get a hero', inject([HeroService], (service: HeroService) => {
    expect(service).toBeTruthy();

    heroReducer({}, {
      type: '[hero] UPDATE',
      payload: {
        uid: '5',
        name: 'Franz'
      }
    });

    const heroObs = service.getHero('5');
    expect(heroObs.getValue().name).toEqual('Franz');

  }));

But somehow the state doesn't get updated. It produces the following logs:

LOG: 'New State', Object{5: BehaviorSubject{_isScalar: false,
  observers: [], closed: false, isStopped: false, hasError: false,
  thrownError: null, _value: Object{uid: ..., name: ...}}}

LOG: 'state returned in service', Object{}

So the reducer actually returns the correct new state. But when subscribed upon in the service, I still get an empty object.

If I understand correctly, a store in ngrx/store is a rxjs BehaviorSubject, which in turn is supposed to return the last value on subscription. From the docs of BehaviorSubject:

Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications

So how is it possible that state is still an empty object?

Body:
Your getHero is not coded properly and I think it returns an unassigned value. A better way to write it would be:

getHero(heroId: string): BehaviorSubject<Hero> {
  let state = new BehaviorSubject<Hero>();
  this.store.select('heroStore').subscribe(s => state.next(s[heroId]));
  return state;
}

or even better:

getHero(heroId: string): Observable<Heor> {
    return this.store.select('heroStore')
        .map(heros => heros[heroId];
}

or if you want to really go elegant, this might work:

getHero(heroId: string): Observable<Heor> {
    return this.store.select('heroStore', heroId);
}


问:
How to avoid NPE when no values is specified for Spring JPA criteria
I have a Spring JPA search criteria like below. Where area is an Integer. </p>

```<code>cb.between(root.get(Property_.area), searchConstraint.getAreaMin(), searchConstraint.getAreaMax())
</code>```

<p>The question is, when the user does not specify an upper bound or lower bound in the search, the value is null and this results in NPE. One thing comes to my mind is to make an if check for null values and set the value to Integer.MAX_VAL if it is null as a work around.This way I can avoid NPE, but it is also going to create a lot of if else checks. So I want to know if there is a better way.  </p>

答:
Two cleaner solutions come to my mind:

using Optionals e.g. `Optional.ofNullable(searchConstraint.getAreaMax()).orElse(Integer.MAX_VALUE)

areaMin and areaMax should have sensible default values which are overwritten only if user provided some data ; the data itself should be validated

Body:
I have a Spring JPA search criteria like below. Where area is an Integer.

cb.between(root.get(Property_.area), searchConstraint.getAreaMin(), searchConstraint.getAreaMax())

The question is, when the user does not specify an upper bound or lower bound in the search, the value is null and this results in NPE. One thing comes to my mind is to make an if check for null values and set the value to Integer.MAX_VAL if it is null as a work around.This way I can avoid NPE, but it is also going to create a lot of if else checks. So I want to know if there is a better way.


问:
google Cloud Vision API: node.js and an image URI, how to invoke vision.detectText()?
I'm trying to detect text in a remote image with the google Cloud Vision API, but can't seem to get the vision.detectText() syntax right.

How do I use vision.detectText() when there is no cloud storage bucket?

I'm thinking I can/should ignore the reference to storage.bucket() indicated on https://cloud.google.com/vision/docs/detecting-text

I have:

```<code> vision.detectText('https://drive.google.com/file
   /d/0Bw4DMtLCtPMkWVlIVXE5a2ZpQlU/view?usp=drivesdk')
          .then((results) => {
            const detections = results[0];
            console.log('Text:');
            detections.forEach((text) => console.log(text));
          })
          .catch((err) => {
            console.error('ERROR:', err);
          });
</code>```

the console reports:

```<code>ERROR: { PartialFailureError: A failure occurred during this request.
at /Users/node_modules/@google-cloud/vision/src/index.js:434:15
at /Users/node_modules/@google-cloud/vision/src/index.js:126:5
at _combinedTickCallback (internal/process/next_tick.js:80:11)
at process._tickCallback (internal/process/next_tick.js:104:9)
errors:
[ { image:  'https://drive.google.com/file/d
 /0Bw4DMtLCtPMkNFFselFhU0RMV2c/view?usp=drivesdk',
   errors: [Object] } ],
 response: { responses: [ [Object] ] },
 message: 'A failure occurred during this request.' }
</code>```

I have tried using:

```<code>vision.detectText(storage.bucket().file('https://......
</code>```

but the error is:

```<code>Error: A bucket name is needed to use Cloud Storage.
</code>```

答:
It looks like you're not setting your GOOGLE_APPLICATION_CREDENTIALS environment variable. The following code works as tested:

```<code>const Vision = require('@google-cloud/vision');
const vision = Vision();
const fileName = 'http://example.com/eg.jpg';

vision.detectText(fileName)
  .then((results) => {
    const detections = results[0];

    console.log('Text:');
    detections.forEach((text) => console.log(text));
    })
    .catch((err) => {
      console.error('ERROR:', err);
    });
</code>```

To try it out with our sample, pass a URI (e.g. http URI) to the detect.js sample as:

```<code>node detect.js fulltext http://www.identifont.com/samples/houseindustries/NeutraText.gif
</code>```

Body:
I'm trying to detect text in a remote image with the google Cloud Vision API, but can't seem to get the vision.detectText() syntax right.

How do I use vision.detectText() when there is no cloud storage bucket?

I'm thinking I can/should ignore the reference to storage.bucket() indicated on https://cloud.google.com/vision/docs/detecting-text

I have:

 vision.detectText('https://drive.google.com/file
   /d/0Bw4DMtLCtPMkWVlIVXE5a2ZpQlU/view?usp=drivesdk')
          .then((results) => {
            const detections = results[0];
            console.log('Text:');
            detections.forEach((text) => console.log(text));
          })
          .catch((err) => {
            console.error('ERROR:', err);
          });

the console reports:

ERROR: { PartialFailureError: A failure occurred during this request.
at /Users/node_modules/@google-cloud/vision/src/index.js:434:15
at /Users/node_modules/@google-cloud/vision/src/index.js:126:5
at _combinedTickCallback (internal/process/next_tick.js:80:11)
at process._tickCallback (internal/process/next_tick.js:104:9)
errors:
[ { image:  'https://drive.google.com/file/d
 /0Bw4DMtLCtPMkNFFselFhU0RMV2c/view?usp=drivesdk',
   errors: [Object] } ],
 response: { responses: [ [Object] ] },
 message: 'A failure occurred during this request.' }

I have tried using:

vision.detectText(storage.bucket().file('https://......

but the error is:

Error: A bucket name is needed to use Cloud Storage.

Body:
It looks like you're not setting your GOOGLE_APPLICATION_CREDENTIALS environment variable. The following code works as tested:

const Vision = require('@google-cloud/vision');
const vision = Vision();
const fileName = 'http://example.com/eg.jpg';

vision.detectText(fileName)
  .then((results) => {
    const detections = results[0];

    console.log('Text:');
    detections.forEach((text) => console.log(text));
    })
    .catch((err) => {
      console.error('ERROR:', err);
    });

To try it out with our sample, pass a URI (e.g. http URI) to the detect.js sample as:

node detect.js fulltext http://www.identifont.com/samples/houseindustries/NeutraText.gif


问:
Cannot Run php in windows command line, works OK in linux
The other answers to this question do not seem to work or be relevant.

I have a script (mailPipe.php) which parses a file (mail.raw) into a MySQL database.

In linux, I can run it as follows:

```<code>cat mail.raw | ./mailPipe.php
</code>```

I am trying to run this in Windows

I have verified php.exe is in my PATH

The syntax I am using is

```<code>php.exe "C:\xampp\php\MailPipe.php" -- c:\xampp\php\mail.raw
</code>```

When I run this in the php directory I get multiple error statements saying various .dll files cannot be found, such as:

PHP Warning:  PHP Startup: Unable to load dynamic library 'E:\php\ext\php_pdo_sq
lite.dll' - The specified procedure could not be found.

I do not get this when I put the files into the PEAR directory, but it just does not work

Frustratingly, I noticed from looking at the MySQL table that the insert statement worked correctly twice but I stupidly did not note the correct syntax when it happened, had been trying many permutations of the command.

Looking at comments here and other posts, I have tried using the "-f" switch, "-r", and "-a", all to no avail.

Is there anything obvious I am missing?

答:
May be your script need some php extension, that did not loaded ('PHP Warning: PHP Startup: Unable to load dynamic library').

Try to fix this errors, see PHP Warning: PHP Startup: Unable to load dynamic library
and may be script will  start working.

Body:
The other answers to this question do not seem to work or be relevant.

I have a script (mailPipe.php) which parses a file (mail.raw) into a MySQL database.

In linux, I can run it as follows:

cat mail.raw | ./mailPipe.php

I am trying to run this in Windows

I have verified php.exe is in my PATH

The syntax I am using is

php.exe "C:\xampp\php\MailPipe.php" -- c:\xampp\php\mail.raw

When I run this in the php directory I get multiple error statements saying various .dll files cannot be found, such as:

PHP Warning:  PHP Startup: Unable to load dynamic library 'E:\php\ext\php_pdo_sq
lite.dll' - The specified procedure could not be found.

I do not get this when I put the files into the PEAR directory, but it just does not work

Frustratingly, I noticed from looking at the MySQL table that the insert statement worked correctly twice but I stupidly did not note the correct syntax when it happened, had been trying many permutations of the command.

Looking at comments here and other posts, I have tried using the "-f" switch, "-r", and "-a", all to no avail.

Is there anything obvious I am missing?


问:
Get next year from the current NSDate?
I have a calendar application in which I want to get the next year from the current date (NSDate).

How can I do this?

答:
As VdesmedT mentioned, you can use dateByAddingTimeInterval and add the seconds of one year. But to be more precise, you can do the following:

```<code>NSDate *today = [NSDate date]; // get the current date
NSCalendar* cal = [NSCalendar currentCalendar]; // get current calender
NSDateComponents* dateOnlyToday = [cal components:( NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit ) fromDate:today];
[dateOnlyToday setYear:([dateOnlyToday year] + 1)];
NSDate *nextYear = [cal dateFromComponents:dateOnlyToday];</code>```

Hope this helps.

Title: Get next year from the current NSDate?

Body:
As VdesmedT mentioned, you can use dateByAddingTimeInterval and add the seconds of one year. But to be more precise, you can do the following:

NSDate *today = [NSDate date]; // get the current date
NSCalendar* cal = [NSCalendar currentCalendar]; // get current calender
NSDateComponents* dateOnlyToday = [cal components:( NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit ) fromDate:today];
[dateOnlyToday setYear:([dateOnlyToday year] + 1)];
NSDate *nextYear = [cal dateFromComponents:dateOnlyToday];

Hope this helps.


问:
Unable to make http POST request in java?
```<code>static HttpClient  httpclient = new DefaultHttpClient();
static HttpPost httppost = new HttpPost("http://servername:6405/biprws/logon/long");
public static void main(String[] args) throws ClientProtocolException, IOException {
          ArrayList<NameValuePair> postParameters  = new ArrayList<NameValuePair>();
        postParameters.add(new BasicNameValuePair("userName", "Administrator"));
        postParameters.add(new BasicNameValuePair("password", "test"));
        postParameters.add(new BasicNameValuePair("auth", "secEnterprise"));
       httppost.setEntity(new UrlEncodedFormEntity(postParameters));
        httppost.addHeader("accept", "application/json");
        httppost.addHeader("Content-Type", "application/json");
        HttpResponse response = httpclient.execute(httppost);
        Header s = response.getFirstHeader("logontoken");
        String s1 =  s.getValue();
        System.out.println(s1);// null pointer exception here
    }
</code>```

Running the code above i am not able to add request body to the POST request. How can i achieve this?

Alternative method i followed:

```<code>HttpClient client1 = new DefaultHttpClient();
     HttpPost post = new HttpPost("http://servername:6405/biprws/logon/long");
     String json = "{\"UserName\":\"Administrator\",\"Password\":\"test\",\"Auth\":\"secEnterprise\"}";
     StringEntity entity = new StringEntity(json,"UTF-8");
     entity.setContentType("application/json");
     post.setEntity(entity);
     System.out.println(entity);
     post.setHeader("Accept", "application/json");

     HttpResponse response = client1.execute(post);
     BufferedReader rd1 = new BufferedReader(
             new InputStreamReader(response.getEntity().getContent()));

    String result1 = null;
    String line1 = "";

        result1 =  rd1.readLine();
        System.out.println(result1);
</code>```

Still i am not able to make request.

答:
You are successfully receiving a response which does not contain the "logontoken" header.  Very possibly because the response is not an HTTP 200 OK response.  Why? We don't know, it all depends on the protocol that your server implements on top of HTTP.

That having been said, the use of both httppost.setEntity(new UrlEncodedFromEntity(postParameters)) and httppost.addHeder("Content-Type", "application/json") does not look right to me.  A URL-encoded form entity is not of json content type.  So, either convert your post parameters to json, or lose the content-type header.

Body:
static HttpClient  httpclient = new DefaultHttpClient();
static HttpPost httppost = new HttpPost("http://servername:6405/biprws/logon/long");
public static void main(String[] args) throws ClientProtocolException, IOException {
          ArrayList<NameValuePair> postParameters  = new ArrayList<NameValuePair>();
        postParameters.add(new BasicNameValuePair("userName", "Administrator"));
        postParameters.add(new BasicNameValuePair("password", "test"));
        postParameters.add(new BasicNameValuePair("auth", "secEnterprise"));
       httppost.setEntity(new UrlEncodedFormEntity(postParameters));
        httppost.addHeader("accept", "application/json");
        httppost.addHeader("Content-Type", "application/json");
        HttpResponse response = httpclient.execute(httppost);
        Header s = response.getFirstHeader("logontoken");
        String s1 =  s.getValue();
        System.out.println(s1);// null pointer exception here
    }

Running the code above i am not able to add request body to the POST request. How can i achieve this?

Alternative method i followed:

HttpClient client1 = new DefaultHttpClient();
     HttpPost post = new HttpPost("http://servername:6405/biprws/logon/long");
     String json = "{\"UserName\":\"Administrator\",\"Password\":\"test\",\"Auth\":\"secEnterprise\"}";
     StringEntity entity = new StringEntity(json,"UTF-8");
     entity.setContentType("application/json");
     post.setEntity(entity);
     System.out.println(entity);
     post.setHeader("Accept", "application/json");

     HttpResponse response = client1.execute(post);
     BufferedReader rd1 = new BufferedReader(
             new InputStreamReader(response.getEntity().getContent()));

    String result1 = null;
    String line1 = "";

        result1 =  rd1.readLine();
        System.out.println(result1);

Still i am not able to make request.


答:
For starters, you want your search pattern to be a function of x and y.

```<code>product = grid[y][x] * grid[p[0][1]][p[0][0]] * grid[p[1][1]][p[1][0]] * grid[p[2][1]][p[2][0]]
</code>```

Right now, p[0][1] will always return the same value no matter what x and y are. You should replace the above line with something like:

```<code>product = grid[y][x] * grid[y + p[0][1]][x + p[0][0]] * grid[y + p[1][1]][x + p[1][0]] * grid[y + p[2][1]][x + p[2][0]]
</code>```

Title: Largest product out of 4 in a grid

Body:
I'm doing some project euler problems to practice more. I am at problem 11 and I keep getting the wrong answer.

Here is the list of lists:

problem_11 = [[8, 2, 22, 97, 38, 15, 0, 40, 0, 75, 4, 5, 7, 78, 52, 12, 50, 77, 91, 8],
              [49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 4, 56, 62, 0],
              [81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 3, 49, 13, 36, 65],
              [52, 70, 95, 23, 4, 60, 11, 42, 69, 24, 68, 56, 1, 32, 56, 71, 37, 2, 36, 91],
              [22, 31, 16, 71, 51, 67, 63, 89, 41, 92, 36, 54, 22, 40, 40, 28, 66, 33, 13, 80],
              [24, 47, 32, 60, 99, 3, 45, 2, 44, 75, 33, 53, 78, 36, 84, 20, 35, 17, 12, 50],
              [32, 98, 81, 28, 64, 23, 67, 10, 26, 38, 40, 67, 59, 54, 70, 66, 18, 38, 64, 70],
              [67, 26, 20, 68, 2, 62, 12, 20, 95, 63, 94, 39, 63, 8, 40, 91, 66, 49, 94, 21],
              [24, 55, 58, 5, 66, 73, 99, 26, 97, 17, 78, 78, 96, 83, 14, 88, 34, 89, 63, 72],
              [21, 36, 23, 9, 75, 0, 76, 44, 20, 45, 35, 14, 0, 61, 33, 97, 34, 31, 33, 95],
              [78, 17, 53, 28, 22, 75, 31, 67, 15, 94, 3, 80, 4, 62, 16, 14, 9, 53, 56, 92],
              [16, 39, 5, 42, 96, 35, 31, 47, 55, 58, 88, 24, 0, 17, 54, 24, 36, 29, 85, 57],
              [86, 56, 0, 48, 35, 71, 89, 7, 5, 44, 44, 37, 44, 60, 21, 58, 51, 54, 17, 58],
              [19, 80, 81, 68, 5, 94, 47, 69, 28, 73, 92, 13, 86, 52, 17, 77, 4, 89, 55, 40],
              [4, 52, 8, 83, 97, 35, 99, 16, 7, 97, 57, 32, 16, 26, 26, 79, 33, 27, 98, 66],
              [88, 36, 68, 87, 57, 62, 20, 72, 3, 46, 33, 67, 46, 55, 12, 32, 63, 93, 53, 69],
              [4, 42, 16, 73, 38, 25, 39, 11, 24, 94, 72, 18, 8, 46, 29, 32, 40, 62, 76, 36],
              [20, 69, 36, 41, 72, 30, 23, 88, 34, 62, 99, 69, 82, 67, 59, 85, 74, 4, 36, 16],
              [20, 73, 35, 29, 78, 31, 90, 1, 74, 31, 49, 71, 48, 86, 81, 16, 23, 57, 5, 54],
              [1, 70, 54, 71, 83, 51, 54, 69, 16, 92, 33, 48, 61, 43, 52, 1, 89, 19, 67, 48]
]

Here is the code:

def largest_product_grid(grid):
    greatest = 0
    patterns = [
        [(1, 0), (2, 0), (3, 0)],
        [(1, -1), (2, -2), (3, -3)],
        [(0, -1), (0, -2), (0, -3)],
        [(0, 1), (0, 2), (0, 3)],
        [(-1, -1), (-2, -2), (-3, -3)]]
    for y in range(0, 19):
        for x in range(0, 19):
            for p in patterns:
                product = grid[y][x] * grid[p[0][1]][p[0][0]] * grid[p[1][1]][p[1][0]] * grid[p[2][1]][p[2][0]]
                if greatest < product:
                    greatest = product
    return greatest

I'm pretty sure it's doing more calculations than it needs to, doing the same math several times and going further on both x and y than I probably need to go. Yet I still keep getting the wrong answer. The correct should be: 70600674.

Edit: Question:

"What is the greatest product of four adjacent numbers in the same
  direction (up, down, left, right, or diagonally) in the 20×20 grid?"

I was expecting index out of range errors, yet I oversaw a stupid error.

Body:
For starters, you want your search pattern to be a function of x and y.

product = grid[y][x] * grid[p[0][1]][p[0][0]] * grid[p[1][1]][p[1][0]] * grid[p[2][1]][p[2][0]]

Right now, p[0][1] will always return the same value no matter what x and y are. You should replace the above line with something like:

product = grid[y][x] * grid[y + p[0][1]][x + p[0][0]] * grid[y + p[1][1]][x + p[1][0]] * grid[y + p[2][1]][x + p[2][0]]


问:
How get the current date and the timezone in numbers format
I want to print the current date in this format 2017/06/05 > Year/Month/Day
and next to it, the  current timezone in this format +3

I used this code

```<code>String DateToday  = DateFormat.getDateInstance().format(new Date());
String TZtoday = DateFormat.getTimeInstance().getTimeZone().getDisplayName();
txt.setText(DateToday + " | "+ TZtoday );
</code>```

But, it shows like this:

Jun 5, 2017 | Arabia Standard Time

I want it like this:

2017/06/05 | +3

答:
Just complementing @Ole V.V.'s answer, I've found another way of doing it using ThreeTenABP, but without needing a regex replacement (although I don't think it's much simpler, more on that below).

Using the DateTimeFormatterBuilder you can use a HashMap that maps the values of the offsets to a String. So, for whole offset hours (like +03:00), you can map the respective value to the string +3 and so on.

The only problem is that the ZoneOffset has seconds precision. And the minimum and maximum values are, respectively, UTC-18:00:00 and UTC+18:00:00. So all possible values are UTC-18:00:00, UTC-17:59:59, UTC-17:59:58 and so on. And the formatter requires that all possible values are mapped (otherwise it'll display the offset's seconds value), so the map will have more than 120K entries!

To build this map, I've made 2 loops:

The first loop maps the whole hour offsets (+01:00 to +1, -02:00 to -2 and so on)

The second loop maps all the other values (they remain unchanged):

whole hours >= 10 (like +10:00)

not-whole hours (like +05:30)

The code to create the formatter:

```<code>// builds a hashmap to map all offset values
Map<Long, String> map = new HashMap<>();

// First loop: Map whole hours from 1 to 9 and from -9 to -1
// So a "+01:00" offset is displayed as "+1"
for (int i = 1; i <= 9; i++) {
    long seconds = ZoneOffset.ofHours(i).getTotalSeconds();
    // 1 hour offset maps to "+1" and so on
    map.put(seconds, "+" + i);
    // -1 hour offset maps to "-1" and so on
    map.put(-seconds, "-" + i);
}

// second loop: Need to map all other possible values for not-whole hours
// offsets like "+10:00" and "+01:30" are not changed
int minOffset = ZoneOffset.MIN.getTotalSeconds();
int maxOffset = ZoneOffset.MAX.getTotalSeconds();
for (long i = minOffset; i <= maxOffset; i++) {
    // the map already contains whole hours, don't need to overwrite the values
    if (!map.containsKey(i)) {
        // uses default String representation (like "+05:30")
        map.put(i, ZoneOffset.ofTotalSeconds((int) i).getId());
    }
}

// create the formatter
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                // year/month/day and the "|"
                .appendPattern("uuuu/MM/dd | ")
                // use the map of custom values (offset will use the values in the map)
                .appendText(ChronoField.OFFSET_SECONDS, map)
                // create formatter
                .toFormatter();
</code>```

Some tests:

```<code>LocalDateTime dt = LocalDateTime.of(2017, 5, 1, 10, 0);
ZonedDateTime z = ZonedDateTime.of(dt, ZoneId.of("America/Sao_Paulo")); // UTC-03:00
System.out.println(formatter.format(z)); // 2017/05/01 | -3

// just picking some timezone in Arabia Stardard Time
// (there are more than one timezone in AST: https://en.wikipedia.org/wiki/UTC%2B03:00#Arabia_Standard_Time)
// I don't know in which one you are
z = ZonedDateTime.of(dt, ZoneId.of("Asia/Qatar")); // UTC+03:00
System.out.println(formatter.format(z)); // 2017/05/01 | +3

// 2-digit offset
z = ZonedDateTime.of(dt, ZoneId.of("Asia/Vladivostok")); // UTC+10:00
System.out.println(formatter.format(z)); // 2017/05/01 | +10:00

// not whole hour
z = ZonedDateTime.of(dt, ZoneId.of("Asia/Kathmandu")); // UTC+05:45
System.out.println(formatter.format(z)); // 2017/05/01 | +05:45
</code>```

The output is:

2017/05/01 | -3

  2017/05/01 | +3

  2017/05/01 | +10:00

  2017/05/01 | +05:45

Notes:

I don't know if having a 120K-entries map is better than using regular expressions (it's up to you to decide). This approach creates a big map, but at least doesn't require output post-processing (not sure if that's a reasonable trade-off)

If you want whole-hour offsets >= 10 to be displayed as +10, +11 and so on, just change the first for loop to for (int i = 1; i <= maxOffsetYouWant; i++) - just reminding that the maximum possible value for maxOffsetYouWant is 18.

Body:
I want to print the current date in this format 2017/06/05 > Year/Month/Day
and next to it, the  current timezone in this format +3

I used this code

String DateToday  = DateFormat.getDateInstance().format(new Date());
String TZtoday = DateFormat.getTimeInstance().getTimeZone().getDisplayName();
txt.setText(DateToday + " | "+ TZtoday );

But, it shows like this:

Jun 5, 2017 | Arabia Standard Time

I want it like this:

2017/06/05 | +3

Body:
Just complementing @Ole V.V.'s answer, I've found another way of doing it using ThreeTenABP, but without needing a regex replacement (although I don't think it's much simpler, more on that below).

Using the DateTimeFormatterBuilder you can use a HashMap that maps the values of the offsets to a String. So, for whole offset hours (like +03:00), you can map the respective value to the string +3 and so on.

The only problem is that the ZoneOffset has seconds precision. And the minimum and maximum values are, respectively, UTC-18:00:00 and UTC+18:00:00. So all possible values are UTC-18:00:00, UTC-17:59:59, UTC-17:59:58 and so on. And the formatter requires that all possible values are mapped (otherwise it'll display the offset's seconds value), so the map will have more than 120K entries!

To build this map, I've made 2 loops:

The first loop maps the whole hour offsets (+01:00 to +1, -02:00 to -2 and so on)

The second loop maps all the other values (they remain unchanged):

whole hours >= 10 (like +10:00)

not-whole hours (like +05:30)

The code to create the formatter:

// builds a hashmap to map all offset values
Map<Long, String> map = new HashMap<>();

// First loop: Map whole hours from 1 to 9 and from -9 to -1
// So a "+01:00" offset is displayed as "+1"
for (int i = 1; i <= 9; i++) {
    long seconds = ZoneOffset.ofHours(i).getTotalSeconds();
    // 1 hour offset maps to "+1" and so on
    map.put(seconds, "+" + i);
    // -1 hour offset maps to "-1" and so on
    map.put(-seconds, "-" + i);
}

// second loop: Need to map all other possible values for not-whole hours
// offsets like "+10:00" and "+01:30" are not changed
int minOffset = ZoneOffset.MIN.getTotalSeconds();
int maxOffset = ZoneOffset.MAX.getTotalSeconds();
for (long i = minOffset; i <= maxOffset; i++) {
    // the map already contains whole hours, don't need to overwrite the values
    if (!map.containsKey(i)) {
        // uses default String representation (like "+05:30")
        map.put(i, ZoneOffset.ofTotalSeconds((int) i).getId());
    }
}

// create the formatter
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                // year/month/day and the "|"
                .appendPattern("uuuu/MM/dd | ")
                // use the map of custom values (offset will use the values in the map)
                .appendText(ChronoField.OFFSET_SECONDS, map)
                // create formatter
                .toFormatter();

Some tests:

LocalDateTime dt = LocalDateTime.of(2017, 5, 1, 10, 0);
ZonedDateTime z = ZonedDateTime.of(dt, ZoneId.of("America/Sao_Paulo")); // UTC-03:00
System.out.println(formatter.format(z)); // 2017/05/01 | -3

// just picking some timezone in Arabia Stardard Time
// (there are more than one timezone in AST: https://en.wikipedia.org/wiki/UTC%2B03:00#Arabia_Standard_Time)
// I don't know in which one you are
z = ZonedDateTime.of(dt, ZoneId.of("Asia/Qatar")); // UTC+03:00
System.out.println(formatter.format(z)); // 2017/05/01 | +3

// 2-digit offset
z = ZonedDateTime.of(dt, ZoneId.of("Asia/Vladivostok")); // UTC+10:00
System.out.println(formatter.format(z)); // 2017/05/01 | +10:00

// not whole hour
z = ZonedDateTime.of(dt, ZoneId.of("Asia/Kathmandu")); // UTC+05:45
System.out.println(formatter.format(z)); // 2017/05/01 | +05:45

The output is:

2017/05/01 | -3

  2017/05/01 | +3

  2017/05/01 | +10:00

  2017/05/01 | +05:45

Notes:

I don't know if having a 120K-entries map is better than using regular expressions (it's up to you to decide). This approach creates a big map, but at least doesn't require output post-processing (not sure if that's a reasonable trade-off)

If you want whole-hour offsets >= 10 to be displayed as +10, +11 and so on, just change the first for loop to for (int i = 1; i <= maxOffsetYouWant; i++) - just reminding that the maximum possible value for maxOffsetYouWant is 18.