问:
R: Expand column of dataframes in existing dataframe
I am using jsonlite::fromJSON to get a JSON document to a dataframe. The problem is that it is not getting flattened completely - for reasons not known to me (but someone below has mentioned because they are in the form of a dictionary, they won't get flattened).

```<code>df <- jsonlite::fromJSON(out, flatten = TRUE, simplifyDataFrame = TRUE)
n <- df$hits$total # 1 entry
dat <- df$hits$hits

# dat is a dataframe
dim(dat)
[1]  2 5

# class of each column in the dataframe
lapply(dat, class)

$`_index`
[1] "character"

$`_type`
[1] "character"

$`_id`
[1] "character"

$`_score`
[1] "numeric"

$`_source.samples`
[1] "list"
</code>```

There is a column dat$_source.samples that is actually a list of dataframes:

```<code>> dim(dat$`_source.samples`[[1]])
[1] 21  2
> dim(dat$`_source.samples`[[2]])
[1] 21  2
</code>```

How do I expand the column containing the dataframes such that they form two new columns within the existing dataframe - and duplicate the first four rows as a result of expansion. Here is an example:

Rstudio screenshot of how dat looks:

```<code># the first four columns look like this
> head(dat[,1:4])
  _index _type                _id _score
1   pnoc genes ENSG00000131051.20      1
2   pnoc genes ENSG00000000457.13      1

# the fifth column `_source.samples` that has dataframes looks like this
# just showing the dataframe in the first row of `dat`
> head(dat$`_source.samples`[[1]])
                        sample_id rsem.fpkm
1 C021_0001_20140916_tumor_RNASeq     39.11
2        CPBT_0001_1_tumor_RNASeq    184.56
3        CPBT_0007_1_tumor_RNASeq     41.29
4   C021_0010_001774_tumor_RNASeq     86.31
5   C021_0003_001409_tumor_RNASeq     79.24
6        CPBT_0005_1_tumor_RNASeq     66.20
</code>```

So I would want something like this:

```<code> _index _type                _id _score                       sample_id
1   pnoc genes ENSG00000000457.13      1 C021_0001_20140916_tumor_RNASeq
2   pnoc genes ENSG00000000457.13      1        CPBT_0001_1_tumor_RNASeq
3   pnoc genes ENSG00000000457.13      1        CPBT_0007_1_tumor_RNASeq
4   pnoc genes ENSG00000000457.13      1   C021_0010_001774_tumor_RNASeq
5   pnoc genes ENSG00000000457.13      1   C021_0003_001409_tumor_RNASeq
6   pnoc genes ENSG00000000457.13      1        CPBT_0005_1_tumor_RNASeq
  rsem.fpkm
1      1.39
2      5.58
3      1.93
4      3.64
5      5.20
6      3.69
</code>```

Here is a reproducible dataset:

```<code>> dput(dat)
structure(list(`_index` = c("pnoc", "pnoc"), `_type` = c("genes",
"genes"), `_id` = c("ENSG00000131051.20", "ENSG00000000457.13"
), `_score` = c(1, 1), `_source.samples` = list(structure(list(
    sample_id = c("C021_0001_20140916_tumor_RNASeq", "CPBT_0001_1_tumor_RNASeq",
    "CPBT_0007_1_tumor_RNASeq", "C021_0010_001774_tumor_RNASeq",
    "C021_0003_001409_tumor_RNASeq", "CPBT_0005_1_tumor_RNASeq",
    "CPBT_0008_1_tumor_RNASeq", "C021_0002_001113_tumor_RNASeq",
    "C021_0013_001872_tumor_RNASeq", "C021_0005_001661_tumor_RNASeq",
    "C021_0007_001669_tumor_RNASeq", "C021_0008_001699_tumor_RNASeq",
    "CPBT_0006_1_tumor_RNASeq", "C021_0011_001786_tumor_RNASeq",
    "C021_0009_001766_tumor_RNASeq", "CPBT_0004_1_tumor_RNASeq",
    "CPBT_0003_1_tumor_RNASeq", "CPBT_0009_1_tumor_RNASeq", "C021_0006_001666_tumor_RNASeq",
    "C021_0012_001825_tumor_RNASeq", "C021_0004_001418_tumor_RNASeq"
    ), rsem.fpkm = c(39.11, 184.56, 41.29, 86.31, 79.24, 66.2,
    42.13, 88.78, 78.73, 96.79, 38.5, 105.12, 129.16, 145.13,
    117.96, 86.53, 75.43, 179.01, 0, 61.61, 98.64)), .Names = c("sample_id",
"rsem.fpkm"), class = "data.frame", row.names = c(NA, 21L)),
    structure(list(sample_id = c("C021_0001_20140916_tumor_RNASeq",
    "CPBT_0001_1_tumor_RNASeq", "CPBT_0007_1_tumor_RNASeq", "C021_0010_001774_tumor_RNASeq",
    "C021_0003_001409_tumor_RNASeq", "CPBT_0005_1_tumor_RNASeq",
    "CPBT_0008_1_tumor_RNASeq", "C021_0002_001113_tumor_RNASeq",
    "C021_0013_001872_tumor_RNASeq", "C021_0005_001661_tumor_RNASeq",
    "C021_0007_001669_tumor_RNASeq", "C021_0008_001699_tumor_RNASeq",
    "CPBT_0006_1_tumor_RNASeq", "C021_0011_001786_tumor_RNASeq",
    "C021_0009_001766_tumor_RNASeq", "CPBT_0004_1_tumor_RNASeq",
    "CPBT_0003_1_tumor_RNASeq", "CPBT_0009_1_tumor_RNASeq", "C021_0006_001666_tumor_RNASeq",
    "C021_0012_001825_tumor_RNASeq", "C021_0004_001418_tumor_RNASeq"
    ), rsem.fpkm = c(1.39, 5.58, 1.93, 3.64, 5.2, 3.69, 1.75,
    5.38, 3.46, 4.14, 0.96, 3.93, 4.47, 3.17, 4.38, 2.8, 2.27,
    7.4, 0, 2.76, 5.55)), .Names = c("sample_id", "rsem.fpkm"
    ), class = "data.frame", row.names = c(NA, 21L)))), .Names = c("_index",
"_type", "_id", "_score", "_source.samples"), class = "data.frame", row.names = 1:2)
</code>```

Thanks!

答:
These columns do not get flattened, because they're originally embedded dictionaries within your json file.

Here's what you can do, though it's not totally intuitive:

First, you create a new dataframe with the content of your column _source.samples. You need to make sure you keep the _id column to identify which row each data comes from.

```<code>samples <- mapply(function(x, y) cbind(x, _id = y), dat$`_source.samples, dat$_id, SIMPLIFY = FALSE)
</code>```

Then you merge it with your dat.

```<code>merge(dat, rbind.pages(samples), by= "_id")
</code>```

Body:
I am using jsonlite::fromJSON to get a JSON document to a dataframe. The problem is that it is not getting flattened completely - for reasons not known to me (but someone below has mentioned because they are in the form of a dictionary, they won't get flattened).

df <- jsonlite::fromJSON(out, flatten = TRUE, simplifyDataFrame = TRUE)
n <- df$hits$total # 1 entry
dat <- df$hits$hits

# dat is a dataframe
dim(dat)
[1]  2 5

# class of each column in the dataframe
lapply(dat, class)

$`_index`
[1] "character"

$`_type`
[1] "character"

$`_id`
[1] "character"

$`_score`
[1] "numeric"

$`_source.samples`
[1] "list"

There is a column dat$_source.samples that is actually a list of dataframes:

> dim(dat$`_source.samples`[[1]])
[1] 21  2
> dim(dat$`_source.samples`[[2]])
[1] 21  2

How do I expand the column containing the dataframes such that they form two new columns within the existing dataframe - and duplicate the first four rows as a result of expansion. Here is an example:

Rstudio screenshot of how dat looks:

# the first four columns look like this
> head(dat[,1:4])
  _index _type                _id _score
1   pnoc genes ENSG00000131051.20      1
2   pnoc genes ENSG00000000457.13      1

# the fifth column `_source.samples` that has dataframes looks like this
# just showing the dataframe in the first row of `dat`
> head(dat$`_source.samples`[[1]])
                        sample_id rsem.fpkm
1 C021_0001_20140916_tumor_RNASeq     39.11
2        CPBT_0001_1_tumor_RNASeq    184.56
3        CPBT_0007_1_tumor_RNASeq     41.29
4   C021_0010_001774_tumor_RNASeq     86.31
5   C021_0003_001409_tumor_RNASeq     79.24
6        CPBT_0005_1_tumor_RNASeq     66.20

So I would want something like this:

 _index _type                _id _score                       sample_id
1   pnoc genes ENSG00000000457.13      1 C021_0001_20140916_tumor_RNASeq
2   pnoc genes ENSG00000000457.13      1        CPBT_0001_1_tumor_RNASeq
3   pnoc genes ENSG00000000457.13      1        CPBT_0007_1_tumor_RNASeq
4   pnoc genes ENSG00000000457.13      1   C021_0010_001774_tumor_RNASeq
5   pnoc genes ENSG00000000457.13      1   C021_0003_001409_tumor_RNASeq
6   pnoc genes ENSG00000000457.13      1        CPBT_0005_1_tumor_RNASeq
  rsem.fpkm
1      1.39
2      5.58
3      1.93
4      3.64
5      5.20
6      3.69

Here is a reproducible dataset:

> dput(dat)
structure(list(`_index` = c("pnoc", "pnoc"), `_type` = c("genes",
"genes"), `_id` = c("ENSG00000131051.20", "ENSG00000000457.13"
), `_score` = c(1, 1), `_source.samples` = list(structure(list(
    sample_id = c("C021_0001_20140916_tumor_RNASeq", "CPBT_0001_1_tumor_RNASeq",
    "CPBT_0007_1_tumor_RNASeq", "C021_0010_001774_tumor_RNASeq",
    "C021_0003_001409_tumor_RNASeq", "CPBT_0005_1_tumor_RNASeq",
    "CPBT_0008_1_tumor_RNASeq", "C021_0002_001113_tumor_RNASeq",
    "C021_0013_001872_tumor_RNASeq", "C021_0005_001661_tumor_RNASeq",
    "C021_0007_001669_tumor_RNASeq", "C021_0008_001699_tumor_RNASeq",
    "CPBT_0006_1_tumor_RNASeq", "C021_0011_001786_tumor_RNASeq",
    "C021_0009_001766_tumor_RNASeq", "CPBT_0004_1_tumor_RNASeq",
    "CPBT_0003_1_tumor_RNASeq", "CPBT_0009_1_tumor_RNASeq", "C021_0006_001666_tumor_RNASeq",
    "C021_0012_001825_tumor_RNASeq", "C021_0004_001418_tumor_RNASeq"
    ), rsem.fpkm = c(39.11, 184.56, 41.29, 86.31, 79.24, 66.2,
    42.13, 88.78, 78.73, 96.79, 38.5, 105.12, 129.16, 145.13,
    117.96, 86.53, 75.43, 179.01, 0, 61.61, 98.64)), .Names = c("sample_id",
"rsem.fpkm"), class = "data.frame", row.names = c(NA, 21L)),
    structure(list(sample_id = c("C021_0001_20140916_tumor_RNASeq",
    "CPBT_0001_1_tumor_RNASeq", "CPBT_0007_1_tumor_RNASeq", "C021_0010_001774_tumor_RNASeq",
    "C021_0003_001409_tumor_RNASeq", "CPBT_0005_1_tumor_RNASeq",
    "CPBT_0008_1_tumor_RNASeq", "C021_0002_001113_tumor_RNASeq",
    "C021_0013_001872_tumor_RNASeq", "C021_0005_001661_tumor_RNASeq",
    "C021_0007_001669_tumor_RNASeq", "C021_0008_001699_tumor_RNASeq",
    "CPBT_0006_1_tumor_RNASeq", "C021_0011_001786_tumor_RNASeq",
    "C021_0009_001766_tumor_RNASeq", "CPBT_0004_1_tumor_RNASeq",
    "CPBT_0003_1_tumor_RNASeq", "CPBT_0009_1_tumor_RNASeq", "C021_0006_001666_tumor_RNASeq",
    "C021_0012_001825_tumor_RNASeq", "C021_0004_001418_tumor_RNASeq"
    ), rsem.fpkm = c(1.39, 5.58, 1.93, 3.64, 5.2, 3.69, 1.75,
    5.38, 3.46, 4.14, 0.96, 3.93, 4.47, 3.17, 4.38, 2.8, 2.27,
    7.4, 0, 2.76, 5.55)), .Names = c("sample_id", "rsem.fpkm"
    ), class = "data.frame", row.names = c(NA, 21L)))), .Names = c("_index",
"_type", "_id", "_score", "_source.samples"), class = "data.frame", row.names = 1:2)

Thanks!

Body:
These columns do not get flattened, because they're originally embedded dictionaries within your json file.

Here's what you can do, though it's not totally intuitive:

First, you create a new dataframe with the content of your column _source.samples. You need to make sure you keep the _id column to identify which row each data comes from.

samples <- mapply(function(x, y) cbind(x, _id = y), dat$`_source.samples, dat$_id, SIMPLIFY = FALSE)

Then you merge it with your dat.

merge(dat, rbind.pages(samples), by= "_id")


来源: stackexchange

问:
How to match a class with annotation inside?
I have an annotation named Metric

```<code>@Target({ElementType.FIELD, ElementType.METHOD})
public @interface Metric {
    String name() default "";
}
</code>```

I want to weave some logic when some methods with the @Metric annotation, like:

```<code>public class MethodWithMetricDemo{

    @Metric
    public void targetMethod(){
        // do some thing
    }
}
</code>```

But how to match the class MethodWithMetricDemo in new AgentBuilder.Default().type(xxxxxxxxxxxxxxxx) ?

答: You would need to match your type based on the method annotatation. As methods are inherited virtually, you would however need to travers the entire class hierarchy by hasSuperType(declaresMethod(isAnnotatedWith(...))). This is possible but rather expensive. If you choose to use such a matcher, you should probably restrict your matching to a given namespace.

ContentLicense: CC BY-SA 3.0

Body:
I have an annotation named Metric

@Target({ElementType.FIELD, ElementType.METHOD})
public @interface Metric {
    String name() default "";
}

I want to weave some logic when some methods with the @Metric annotation, like:

public class MethodWithMetricDemo{

    @Metric
    public void targetMethod(){
        // do some thing
    }
}

But how to match the class MethodWithMetricDemo in new AgentBuilder.Default().type(xxxxxxxxxxxxxxxx) ?


问:
Index was outside the bounds of the array
At the line `If aryTemp(1) < aryTemp2(1) Then the

Index was outside the bounds of the
  array.

error appears. Can't identify why would it be outside array's bounds.
Basically trying to compare Last Names to sort the records and place em back into list box.

A student record looks like this:
FirstName[space]LastName[space]Major[space]Telephone[space]Email[space]GPA

Example: Johny Cake E201 6666666666 me@me.com 1.0

```<code> Private Sub btnAscending_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAscending.Click
        ''#load all students into array
        Dim arySort(numberOfRecords) As String
        Dim aryTemp(6) As String
        Dim aryTemp2(6) As String
        For i = 0 To numberOfRecords - 1
            arySort(i) = lstListBox.Items(i)
        Next
        Dim temp As String ''#holds temporary record
        Dim k As Integer
        For i = 0 To arySort.Length - 2
            aryTemp = Split(arySort(i), " ")
            For k = i + 1 To arySort.Length - 1
                aryTemp2 = Split(arySort(k), " ")
                If aryTemp(1) < aryTemp2(1) Then ''# index of 1 refers to last name of a split string
                    temp = arySort(k)
                    arySort(k) = arySort(i)
                    arySort(i) = temp
                End If
            Next
        Next
        lstListBox.Items.Clear()
        numberOfRecords = 0
        isLoaded = False
        For i = 0 To arySort.Length - 1
            lstListBox.Items.Add(arySort(i))
            numberOfRecords += 1
        Next
        currentRecord = 0
        isLoaded = True
    End Sub
</code>```

答: This is because you're comparing against the second item in aryTemp2 (the item at index 1), however aryTemp2 contains either 1 or 0 elements. Looks like you're expecting Split(arySort(k), " ") to return an array containing more elements than it actually is. You should check the dimensions of the array before comparing into it, or verify that arySort(k) contains at least one space (to ensure that arySort2 will have at least two elements in it).

ContentLicense: CC BY-SA 2.5

Body:
At the line `If aryTemp(1) < aryTemp2(1) Then the

Index was outside the bounds of the
  array.

error appears. Can't identify why would it be outside array's bounds.
Basically trying to compare Last Names to sort the records and place em back into list box.

A student record looks like this:
FirstName[space]LastName[space]Major[space]Telephone[space]Email[space]GPA

Example: Johny Cake E201 6666666666 me@me.com 1.0

 Private Sub btnAscending_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAscending.Click
        ''#load all students into array
        Dim arySort(numberOfRecords) As String
        Dim aryTemp(6) As String
        Dim aryTemp2(6) As String
        For i = 0 To numberOfRecords - 1
            arySort(i) = lstListBox.Items(i)
        Next
        Dim temp As String ''#holds temporary record
        Dim k As Integer
        For i = 0 To arySort.Length - 2
            aryTemp = Split(arySort(i), " ")
            For k = i + 1 To arySort.Length - 1
                aryTemp2 = Split(arySort(k), " ")
                If aryTemp(1) < aryTemp2(1) Then ''# index of 1 refers to last name of a split string
                    temp = arySort(k)
                    arySort(k) = arySort(i)
                    arySort(i) = temp
                End If
            Next
        Next
        lstListBox.Items.Clear()
        numberOfRecords = 0
        isLoaded = False
        For i = 0 To arySort.Length - 1
            lstListBox.Items.Add(arySort(i))
            numberOfRecords += 1
        Next
        currentRecord = 0
        isLoaded = True
    End Sub


问:
permission denied for composer in /usr/local/bin/
I followed the documentation on https://getcomposer.org/doc/00-intro.md#globally to install composer globally on arch linux. When I do composer self-update, I get this message:

```<code>  [ErrorException]
  rename(/home/hannes/.composer/cache/composer-temp.phar,/usr/local/bin/composer): Permission denied
</code>```

The permissions in /usr/local/bin/ (I changed them to 777, but it did not help):

```<code>-rwxrwxrwx  1 hannes users 1104202 30. Mai 18:07 composer
</code>```

In my home directory I did this:

```<code>sudo chmod -R 777 .composer/
</code>```

In /etc/php/php.ini, the open_basedir looks so:

```<code>open_basedir = /srv/http/:/home/:/tmp/:/usr/share/pear/:/usr/share/webapps/:/usr/local/bin/
</code>```

I also tried sudo composer self-update but it did not work as well and is possibly not the right way. (?). What else could I try to make this work?

答: Even after moving the file via sudo mv composer.phar /usr/local/bin/composer I was getting a permission error when trying to run the composer command. sudo chmod 755 /usr/local/bin/composer fixed things for me.

Body:
I followed the documentation on https://getcomposer.org/doc/00-intro.md#globally to install composer globally on arch linux. When I do composer self-update, I get this message:

  [ErrorException]
  rename(/home/hannes/.composer/cache/composer-temp.phar,/usr/local/bin/composer): Permission denied

The permissions in /usr/local/bin/ (I changed them to 777, but it did not help):

-rwxrwxrwx  1 hannes users 1104202 30. Mai 18:07 composer

In my home directory I did this:

sudo chmod -R 777 .composer/

In /etc/php/php.ini, the open_basedir looks so:

open_basedir = /srv/http/:/home/:/tmp/:/usr/share/pear/:/usr/share/webapps/:/usr/local/bin/

I also tried sudo composer self-update but it did not work as well and is possibly not the right way. (?). What else could I try to make this work?


问:
phpMyAdmin replication error: ./libraries/dbi/DBIMysqli.class.php#298
Just set up binary log replication between a mysql 5.7 master running in ubuntu 16.04 and a MariaDB 10.0.28 slave running on my Asustor NAS AS204-TE.

After a few attempts replication is working without issue however my only worry are two error messages phpmyadmin shows when I click into the 'Replication' view from the main page...

Error 1:

```<code>Warning in ./libraries/dbi/DBIMysqli.class.php#298
 mysqli_fetch_array(): Malformed server packet. Field length pointing 0 bytes after end of packet

Backtrace

./libraries/dbi/DBIMysqli.class.php#298: mysqli_fetch_array(
object,
integer 1,
)
./libraries/DatabaseInterface.class.php#2760: PMA_DBI_Mysqli->fetchAssoc(object)
./libraries/DatabaseInterface.class.php#2069: PMA_DatabaseInterface->fetchAssoc(object)
./libraries/replication_gui.lib.php#612: PMA_DatabaseInterface->fetchResult(
string 'SHOW SLAVE HOSTS',
NULL,
NULL,
)
./libraries/replication_gui.lib.php#56: PMA_getHtmlForReplicationSlavesTable(boolean true)
./server_replication.php#56: PMA_getHtmlForMasterReplication()
</code>```

Error 2:

```<code>Warning in ./libraries/dbi/DBIMysqli.class.php#298
 mysqli_fetch_array(): Error while reading a row

Backtrace

./libraries/dbi/DBIMysqli.class.php#298: mysqli_fetch_array(
object,
integer 1,
)
./libraries/DatabaseInterface.class.php#2760: PMA_DBI_Mysqli->fetchAssoc(object)
./libraries/DatabaseInterface.class.php#2069: PMA_DatabaseInterface->fetchAssoc(object)
./libraries/replication_gui.lib.php#612: PMA_DatabaseInterface->fetchResult(
string 'SHOW SLAVE HOSTS',
NULL,
NULL,
)
./libraries/replication_gui.lib.php#56: PMA_getHtmlForReplicationSlavesTable(boolean true)
./server_replication.php#56: PMA_getHtmlForMasterReplication()
</code>```

So following a little logic the error message seems to revolve around listing the slaves connecting to the master.  So I click 'Ignore All' on the error and click the 'Show connected slaves' link which shows me nothing other than a tip to ensure "--report-host=xxx" is set on the slave.  I've confirmed the mysql (MariaDB) instance is starting on the slave with the needed parameter and going into mysql via the commandline on the master and issuing a SHOW SLAVE HOSTS; gives me the following output...

```<code>mysql> show slave hosts;
+-----------+----------+------+-----------+------------+
| Server_id | Host     | Port | Master_id | Slave_UUID |
+-----------+----------+------+-----------+------------+
|         2 | blacknas | 3306 |         1 |            |
+-----------+----------+------+-----------+------------+
1 row in set (0.00 sec)
</code>```

I'm not clear on what my next steps should be to further debug this so would appreciate any pointers?

答:
Okay so answering this myself as I get the impression the bug submission with PHP will take an age.

This is not a fault with phpMyAdmin but instead the error is being generated by the mysqli extension in PHP and can be reproduced using the below code (credit for the code snippet goes to nijel who picked up my issue on github)...

```<code><?php
error_reporting(E_ALL);

$link = mysqli_connect("localhost", "my_user", "my_password");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SHOW SLAVE HOSTS";
$result = mysqli_query($link, $query);

/* get associative array */
while (($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) !== null) {
    print_r($row);
}

/* free result set */
mysqli_free_result($result);

/* close connection */
mysqli_close($link);
?>
</code>```

I believe the reason the the mysqli extension is complaining is because the command being issued should return 4 values but in my use case it only returns 3.  This is because the MariaDB slave does not implement the server_uuid feature whereas its MySQL counterpart does.  As a result the returned values from slave to guest are incomplete which is somewhat aligned to what the error messages are saying.  The bug I've filed with PHP will hopefully clarify if the mysqli extension should tolerate these nuances better.  As my replication use case is documented by the developers I would have thought it should but.

Anyways to somewhat prove my theory I created a test container, deployed the ubuntu lamp packages and phpmyadmin and recreated the scenario but using mysql for both master and slave.  As server_uuid is implemented the 'SHOW SLAVE HOSTS;' command returns all 4 values and both the test script above as well as phpMyAdmin no longer whinge.

Replication is certainly working so this is more an annoyance which I'll live with.

Body:
Just set up binary log replication between a mysql 5.7 master running in ubuntu 16.04 and a MariaDB 10.0.28 slave running on my Asustor NAS AS204-TE.

After a few attempts replication is working without issue however my only worry are two error messages phpmyadmin shows when I click into the 'Replication' view from the main page...

Error 1:

Warning in ./libraries/dbi/DBIMysqli.class.php#298
 mysqli_fetch_array(): Malformed server packet. Field length pointing 0 bytes after end of packet

Backtrace

./libraries/dbi/DBIMysqli.class.php#298: mysqli_fetch_array(
object,
integer 1,
)
./libraries/DatabaseInterface.class.php#2760: PMA_DBI_Mysqli->fetchAssoc(object)
./libraries/DatabaseInterface.class.php#2069: PMA_DatabaseInterface->fetchAssoc(object)
./libraries/replication_gui.lib.php#612: PMA_DatabaseInterface->fetchResult(
string 'SHOW SLAVE HOSTS',
NULL,
NULL,
)
./libraries/replication_gui.lib.php#56: PMA_getHtmlForReplicationSlavesTable(boolean true)
./server_replication.php#56: PMA_getHtmlForMasterReplication()

Error 2:

Warning in ./libraries/dbi/DBIMysqli.class.php#298
 mysqli_fetch_array(): Error while reading a row

Backtrace

./libraries/dbi/DBIMysqli.class.php#298: mysqli_fetch_array(
object,
integer 1,
)
./libraries/DatabaseInterface.class.php#2760: PMA_DBI_Mysqli->fetchAssoc(object)
./libraries/DatabaseInterface.class.php#2069: PMA_DatabaseInterface->fetchAssoc(object)
./libraries/replication_gui.lib.php#612: PMA_DatabaseInterface->fetchResult(
string 'SHOW SLAVE HOSTS',
NULL,
NULL,
)
./libraries/replication_gui.lib.php#56: PMA_getHtmlForReplicationSlavesTable(boolean true)
./server_replication.php#56: PMA_getHtmlForMasterReplication()

So following a little logic the error message seems to revolve around listing the slaves connecting to the master.  So I click 'Ignore All' on the error and click the 'Show connected slaves' link which shows me nothing other than a tip to ensure "--report-host=xxx" is set on the slave.  I've confirmed the mysql (MariaDB) instance is starting on the slave with the needed parameter and going into mysql via the commandline on the master and issuing a SHOW SLAVE HOSTS; gives me the following output...

mysql> show slave hosts;
+-----------+----------+------+-----------+------------+
| Server_id | Host     | Port | Master_id | Slave_UUID |
+-----------+----------+------+-----------+------------+
|         2 | blacknas | 3306 |         1 |            |
+-----------+----------+------+-----------+------------+
1 row in set (0.00 sec)

I'm not clear on what my next steps should be to further debug this so would appreciate any pointers?

Body:
Okay so answering this myself as I get the impression the bug submission with PHP will take an age.

This is not a fault with phpMyAdmin but instead the error is being generated by the mysqli extension in PHP and can be reproduced using the below code (credit for the code snippet goes to nijel who picked up my issue on github)...

<?php
error_reporting(E_ALL);

$link = mysqli_connect("localhost", "my_user", "my_password");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SHOW SLAVE HOSTS";
$result = mysqli_query($link, $query);

/* get associative array */
while (($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) !== null) {
    print_r($row);
}

/* free result set */
mysqli_free_result($result);

/* close connection */
mysqli_close($link);
?>

I believe the reason the the mysqli extension is complaining is because the command being issued should return 4 values but in my use case it only returns 3.  This is because the MariaDB slave does not implement the server_uuid feature whereas its MySQL counterpart does.  As a result the returned values from slave to guest are incomplete which is somewhat aligned to what the error messages are saying.  The bug I've filed with PHP will hopefully clarify if the mysqli extension should tolerate these nuances better.  As my replication use case is documented by the developers I would have thought it should but.

Anyways to somewhat prove my theory I created a test container, deployed the ubuntu lamp packages and phpmyadmin and recreated the scenario but using mysql for both master and slave.  As server_uuid is implemented the 'SHOW SLAVE HOSTS;' command returns all 4 values and both the test script above as well as phpMyAdmin no longer whinge.

Replication is certainly working so this is more an annoyance which I'll live with.


问:
Docker only outputs one file
Quick question that I cannot answer via standard googling. In a very simple docker image, I am trying to output text to two separate files. I've removed all other code from my example for simplicity:

```<code>test # cat Dockerfile
FROM centos:latest
    CMD echo "blah" > /docker_path/blah
    CMD echo "blah2" > /docker_path/blah2
test # docker build -t test .
Sending build context to Docker daemon 3.072 kB
Sending build context to Docker daemon
Step 0 : FROM centos:latest
 ---> bac949ce964b
Step 1 : CMD echo "blah" > /docker_path/blah
 ---> Using cache
 ---> bf1fb35bdaca
Step 2 : CMD echo "blah2" > /docker_path/blah2
 ---> Using cache
 ---> f36005c7aba9
Successfully built f36005c7aba9
test #  docker run -v /usr/local/docker/test:/docker_path:Z test
test # ls
blah2  Dockerfile
</code>```

Why does only one file get written? I've realized it is always the second CMD that is written and if I join the writes into one command (ala: CMD echo "blah" > /docker_path/blah && echo "blah2" > /docker_path/blah2), it will output both files.

Can you please help me understand this behavior?

Thanks!

答:
CMD determines which command is run by default when a container is started from the image. Only the last statement has any effect, as it overwrites whatever has been set by previous ones. If you want more complex behaviour, consider including a shell script in your image and calling that using CMD.

If you want to execute commands while the image is built, use RUN statements. Those are executed sequentially like you would expect. Check the Dockerfile reference for details.

Title: Docker only outputs one file

Body:
Quick question that I cannot answer via standard googling. In a very simple docker image, I am trying to output text to two separate files. I've removed all other code from my example for simplicity:

test # cat Dockerfile
FROM centos:latest
    CMD echo "blah" > /docker_path/blah
    CMD echo "blah2" > /docker_path/blah2
test # docker build -t test .
Sending build context to Docker daemon 3.072 kB
Sending build context to Docker daemon
Step 0 : FROM centos:latest
 ---> bac949ce964b
Step 1 : CMD echo "blah" > /docker_path/blah
 ---> Using cache
 ---> bf1fb35bdaca
Step 2 : CMD echo "blah2" > /docker_path/blah2
 ---> Using cache
 ---> f36005c7aba9
Successfully built f36005c7aba9
test #  docker run -v /usr/local/docker/test:/docker_path:Z test
test # ls
blah2  Dockerfile

Why does only one file get written? I've realized it is always the second CMD that is written and if I join the writes into one command (ala: CMD echo "blah" > /docker_path/blah && echo "blah2" > /docker_path/blah2), it will output both files.

Can you please help me understand this behavior?

Thanks!


问:
Java large inputs and outputs
I have been working on a java algorithm and I want to improve it by allowing it to accept and process very large String values.

Could you suggest me any good ways of storing the input/output results. I've been thinking of writing it on a file with the readLine(), writeLine() methods? Is this a good technique ???

答:
I recommend you to store all your string in a text file (if possible) and use BufferedReader utilities ...
here is the a link to how its done :

https://www.tutorialspoint.com/java/io/bufferedreader_readline.htm

Title: Java large inputs and outputs


问:
Token authentication with PHP REST client
I'm trying to figure out a way to make a request to a REST api using some PHP client.

```<code>Authorization: Token token="CREDENTIALS"
</code>```

I can successfully curl it by using

```<code>$ curl -H 'Authorization: Token token="CREDENTIALS" https://uriexample.com
</code>```

But I can't figure out a way to set this header in any PHP client I tried (Guzzle and Httpful).

Would anyone know how can I do this with ANY PHP client? I just don't wanna code this client from scratch :(

答:
The Guzzle docs have loads of examples if you dig into them a little.
http://docs.guzzlephp.org/en/latest/quickstart.html#making-a-request
http://docs.guzzlephp.org/en/latest/request-options.html#headers</p>

```<code><?php

// Create HTTP client with headers for all requests
$client = new GuzzleHttp\Client([
    'base_uri' => 'https://uriexample.com',
    'headers' => [
        'Authorization' => 'Token token="CREDENTIALS"',
    ],
]);

// Dispatch GET request
$client->request('GET', '/');

// OR

// Create HTTP client
$client = new GuzzleHttp\Client([
    'base_uri' => 'https://uriexample.com',
]);

// Dispatch GET request with specific headers
$client->request('GET', '/', [
    'headers' => [
        'Authorization' => 'Token token="CREDENTIALS"',
    ],
]);
</code>```

Body:
I'm trying to figure out a way to make a request to a REST api using some PHP client.

Authorization: Token token="CREDENTIALS"

I can successfully curl it by using

$ curl -H 'Authorization: Token token="CREDENTIALS" https://uriexample.com

But I can't figure out a way to set this header in any PHP client I tried (Guzzle and Httpful).

Would anyone know how can I do this with ANY PHP client? I just don't wanna code this client from scratch :(

Body:
The Guzzle docs have loads of examples if you dig into them a little.
http://docs.guzzlephp.org/en/latest/quickstart.html#making-a-request
http://docs.guzzlephp.org/en/latest/request-options.html#headers

<?php

// Create HTTP client with headers for all requests
$client = new GuzzleHttp\Client([
    'base_uri' => 'https://uriexample.com',
    'headers' => [
        'Authorization' => 'Token token="CREDENTIALS"',
    ],
]);

// Dispatch GET request
$client->request('GET', '/');

// OR

// Create HTTP client
$client = new GuzzleHttp\Client([
    'base_uri' => 'https://uriexample.com',
]);

// Dispatch GET request with specific headers
$client->request('GET', '/', [
    'headers' => [
        'Authorization' => 'Token token="CREDENTIALS"',
    ],
]);


问:
aurelia-redux-immutable - recommended way to subscribe?
I am employing the aurelia-redux-immutable package in my project. It's great, the only thing is that everything you need is hooked up to the view model - EXCEPT subscribe. What is the recommended way of subscribing with this tool?

Thank you for any input.

答: It looks like you are dependent on the state property change notification events in the local class to know if/what changed.</p>


问:
EF query with conditions from multiple tables
I have a table named "Employees". The employeeId from this table MAY be in another table (a many-to-many join tbale) named "Tasks". The other field in the "Tasks" table is a taskId linked to the "TaskDetails" table. This table includes details such as budgetHours.

Using EF4, how do I write the WHERE statement such that the return is employees assigned to tasks where the budgetHours is > 120 hours?

THe WHERE statement in the following limits rows in the Employees table but now I need to add the conditions on the TaskDetails table.

```<code>var assocOrg = Employees.Where(x => x.EmployeeTypeID == 2 && x.DepartmentName == "ABC").Select (x => x.EmployeeID);
</code>```

Thanks!

答:
Assuming you have a Tasks navigation property on the Employee entity, this should be straightforward:

```<code>var assocOrg = Employees.Where(x => x.Tasks.Any(t => t.BudgetHours > 120) && x.DepartmentName == "ABC").Select (x => x.EmployeeID);
</code>```

Of course, this requires the Tasks property to be resolved at this point, either explicitly, via lazy-loading, or with .Include().

(kudos to @adrift for getting Tasks.Any() right... oops.)

Body:
I have a table named "Employees". The employeeId from this table MAY be in another table (a many-to-many join tbale) named "Tasks". The other field in the "Tasks" table is a taskId linked to the "TaskDetails" table. This table includes details such as budgetHours.

Using EF4, how do I write the WHERE statement such that the return is employees assigned to tasks where the budgetHours is > 120 hours?

THe WHERE statement in the following limits rows in the Employees table but now I need to add the conditions on the TaskDetails table.

var assocOrg = Employees.Where(x => x.EmployeeTypeID == 2 && x.DepartmentName == "ABC").Select (x => x.EmployeeID);

Thanks!

Body:
Assuming you have a Tasks navigation property on the Employee entity, this should be straightforward:

var assocOrg = Employees.Where(x => x.Tasks.Any(t => t.BudgetHours > 120) && x.DepartmentName == "ABC").Select (x => x.EmployeeID);

Of course, this requires the Tasks property to be resolved at this point, either explicitly, via lazy-loading, or with .Include().

(kudos to @adrift for getting Tasks.Any() right... oops.)


问:
Migration to webpack 2 for ExtractTextPlugin
I am trying to migrate from webpack 1 to 2 based on this guide. I have made most of the changes but struggling with ExtractTextPlugin. This is how it currently looks with webpack 1:

```<code> module: {
    loaders: [
      {
        test: /\.jsx?$/,
        exclude: /(node_modules|vendor)/,
        loader: 'babel',
        query: {
          presets: ['es2015', 'stage-0', 'react']
        }
      },
      {
        test: /\.css$/,
        loader: ExtractTextPlugin.extract('style-loader', 'css-loader', 'autoprefixer-loader')
      },
      {
        test: /\.styl$/,
        loader: ExtractTextPlugin.extract('style-loader', 'css-loader!autoprefixer-loader!stylus-loader')
      },
      {
        test: /\.(woff|woff2|ttf|eot)($|\?)/,
        loader: 'file-loader?name=[path][name].[ext]'
      },
      {
        test: /\.svg\?/,
        loader: 'url-loader?limit=100000&name=[path][name].[ext]'
      },
      {
        test: /\.(png|gif|jpg|svg)$/,
        loader: 'file-loader?name=[path][name].[ext]'
      },
    ]
  }
</code>```

changes i have made with webpack2:

```<code>module: {
    rules: [
      {
        test: /\.jsx?$/,
        exclude: /(node_modules|vendor)/,
        use:[{
            loader: 'babel-loader',
            query: { //
              presets: ['es2015', 'stage-0', 'react']
            }
          }
        ]
      },

      {
    test: /\.css$/,
    use: ExtractTextPlugin.extract({
      fallback:'style-loader',
      use: ['css-loader', 'postcss-loader','stylus-loader']
    })
  },
  {
    test: /\.styl$/,
    use: ExtractTextPlugin.extract({
      fallback:'style-loader',
        use: ['css-loader', 'postcss-loader','stylus-loader']
    })
  },

      {
        test: /\.(woff|woff2|ttf|eot)($|\?)/,
        use: 'file-loader?name=[path][name].[ext]'
      },
      {
        test: /\.svg\?/,
        use: 'url-loader?limit=100000&name=[path][name].[ext]'
      },
      {
        test: /\.(png|gif|jpg|svg)$/,
        use: 'file-loader?name=[path][name].[ext]'
      },
    ]
  }
</code>```

But this is resulting in error. Where can I find help on migrating this section of webpack config.

Some of the errors i am seeing:

```<code>ERROR in ./~/css-loader!./~/postcss-loader!./~/stylus-loader!./~/bootstrap/dist/css/bootstrap.css
Module build failed: ParseError: C:\temp\node_modules\bootstrap\dist\css\bootstrap.css:3586:71
   3582|   text-decoration: none;
   3583|   cursor: not-allowed;
   3584|   background-color: transparent;
   3585|   background-image: none;
   3586|   filter: progid:DXImageTransform.Microsoft.gradient(enabled = false);
-------------------------------------------------------------------------------^
   3587| }
   3588| .open > .dropdown-menu {
   3589|   display: block;

expected "indent", got ";"

ERROR in ./~/css-loader!./~/postcss-loader!./~/stylus-loader!./vendor/kendo-ui/styles/web/kendo.default.css
Module build failed: TypeError: C:\temp\kendo-ui\styles\web\kendo.default.css:862:27
   858| .k-state-disabled {
   859|   opacity: .7;
   860| }
   861| .k-ie8 .k-state-disabled {
   862|   filter: alpha(opacity=70);
----------------------------------^
   863| }
   864| .k-tile-empty.k-state-selected,
   865| .k-loading-mask.k-state-selected {

Cannot read property 'a' of undefined
    at ".k-ie8 .k-state-disabled " (C:\temp\kendo-ui\styles\web\kendo.default.css:861:2)
</code>```

答:
You're using stylus-loader for your .css as well. But not all CSS is valid stylus. You need to remove stylus-loader from the .css rule:

```<code>{
  test: /\.css$/,
  use: ExtractTextPlugin.extract({
    fallback: 'style-loader',
    use: ['css-loader', 'postcss-loader']
  })
},
</code>```

Body:
I am trying to migrate from webpack 1 to 2 based on this guide. I have made most of the changes but struggling with ExtractTextPlugin. This is how it currently looks with webpack 1:

 module: {
    loaders: [
      {
        test: /\.jsx?$/,
        exclude: /(node_modules|vendor)/,
        loader: 'babel',
        query: {
          presets: ['es2015', 'stage-0', 'react']
        }
      },
      {
        test: /\.css$/,
        loader: ExtractTextPlugin.extract('style-loader', 'css-loader', 'autoprefixer-loader')
      },
      {
        test: /\.styl$/,
        loader: ExtractTextPlugin.extract('style-loader', 'css-loader!autoprefixer-loader!stylus-loader')
      },
      {
        test: /\.(woff|woff2|ttf|eot)($|\?)/,
        loader: 'file-loader?name=[path][name].[ext]'
      },
      {
        test: /\.svg\?/,
        loader: 'url-loader?limit=100000&name=[path][name].[ext]'
      },
      {
        test: /\.(png|gif|jpg|svg)$/,
        loader: 'file-loader?name=[path][name].[ext]'
      },
    ]
  }

changes i have made with webpack2:

module: {
    rules: [
      {
        test: /\.jsx?$/,
        exclude: /(node_modules|vendor)/,
        use:[{
            loader: 'babel-loader',
            query: { //
              presets: ['es2015', 'stage-0', 'react']
            }
          }
        ]
      },

      {
    test: /\.css$/,
    use: ExtractTextPlugin.extract({
      fallback:'style-loader',
      use: ['css-loader', 'postcss-loader','stylus-loader']
    })
  },
  {
    test: /\.styl$/,
    use: ExtractTextPlugin.extract({
      fallback:'style-loader',
        use: ['css-loader', 'postcss-loader','stylus-loader']
    })
  },

      {
        test: /\.(woff|woff2|ttf|eot)($|\?)/,
        use: 'file-loader?name=[path][name].[ext]'
      },
      {
        test: /\.svg\?/,
        use: 'url-loader?limit=100000&name=[path][name].[ext]'
      },
      {
        test: /\.(png|gif|jpg|svg)$/,
        use: 'file-loader?name=[path][name].[ext]'
      },
    ]
  }

But this is resulting in error. Where can I find help on migrating this section of webpack config.

Some of the errors i am seeing:

ERROR in ./~/css-loader!./~/postcss-loader!./~/stylus-loader!./~/bootstrap/dist/css/bootstrap.css
Module build failed: ParseError: C:\temp\node_modules\bootstrap\dist\css\bootstrap.css:3586:71
   3582|   text-decoration: none;
   3583|   cursor: not-allowed;
   3584|   background-color: transparent;
   3585|   background-image: none;
   3586|   filter: progid:DXImageTransform.Microsoft.gradient(enabled = false);
-------------------------------------------------------------------------------^
   3587| }
   3588| .open > .dropdown-menu {
   3589|   display: block;

expected "indent", got ";"

ERROR in ./~/css-loader!./~/postcss-loader!./~/stylus-loader!./vendor/kendo-ui/styles/web/kendo.default.css
Module build failed: TypeError: C:\temp\kendo-ui\styles\web\kendo.default.css:862:27
   858| .k-state-disabled {
   859|   opacity: .7;
   860| }
   861| .k-ie8 .k-state-disabled {
   862|   filter: alpha(opacity=70);
----------------------------------^
   863| }
   864| .k-tile-empty.k-state-selected,
   865| .k-loading-mask.k-state-selected {

Cannot read property 'a' of undefined
    at ".k-ie8 .k-state-disabled " (C:\temp\kendo-ui\styles\web\kendo.default.css:861:2)

Body:
You're using stylus-loader for your .css as well. But not all CSS is valid stylus. You need to remove stylus-loader from the .css rule:

{
  test: /\.css$/,
  use: ExtractTextPlugin.extract({
    fallback: 'style-loader',
    use: ['css-loader', 'postcss-loader']
  })
},


问:
Excel - Finding max value with previous row and various range size
I need to find the maximum relative humidity value during precipitation events. I have calculated the duration of each event and was able to get excel to “scan” the event going backward. The issue where I am stuck at is that some events start on the previous day and I don’t know how to get excel to scan the previous row.

Here is an example…

code:

```<code>=IF(AND(Duration!BP3>0), MAX(INDIRECT(ADDRESS(3, COLUMN(C3)-Duration!BP3)):C3),0)
</code>```

Example: First event in the above table was only an hour long (L2) so the max value is automatically 90.

The next event has a duration of 11 hours. I am trying to get excel to find the max value from 21z to 02z. So BP3 = 6. Since BP3 is greater than 0, I try to find the max relative humidity by subtracting the duration to get a range of the event (COLUMN(C3)-Duration!BP3). For this event, the max value would be 100.

Problem: I get "#VALUE!" because there is no cell with =(C3-6). Is there a way to get it to scan the previous row as well? Would a VBA or python code work better? I am fairly new to VBA and python so I'm not sure how to go about this.

答:
```<code>=IF(BP3<COLUMN(C3),MAX(OFFSET(C3,0,-(BP3-1),1,BP3)),MAX(MAX(A3:C3),MAX(OFFSET(X3,-1,-BP3+COLUMN(C3)+1,1,BP3-COLUMN(C3)))))
</code>```

If BP3 isn't too big, take the max of C3 offset backward. If it is too big, take the max of two ranges: The first range is A3:C3. The second range is X3, offset up 1 row and back a number of columns (bp3-column(c3)).

If the event spans more than two rows, this won't work.

Body:
I need to find the maximum relative humidity value during precipitation events. I have calculated the duration of each event and was able to get excel to “scan” the event going backward. The issue where I am stuck at is that some events start on the previous day and I don’t know how to get excel to scan the previous row.

Here is an example…

code:

=IF(AND(Duration!BP3>0), MAX(INDIRECT(ADDRESS(3, COLUMN(C3)-Duration!BP3)):C3),0)

Example: First event in the above table was only an hour long (L2) so the max value is automatically 90.

The next event has a duration of 11 hours. I am trying to get excel to find the max value from 21z to 02z. So BP3 = 6. Since BP3 is greater than 0, I try to find the max relative humidity by subtracting the duration to get a range of the event (COLUMN(C3)-Duration!BP3). For this event, the max value would be 100.

Problem: I get "#VALUE!" because there is no cell with =(C3-6). Is there a way to get it to scan the previous row as well? Would a VBA or python code work better? I am fairly new to VBA and python so I'm not sure how to go about this.

Body:
=IF(BP3<COLUMN(C3),MAX(OFFSET(C3,0,-(BP3-1),1,BP3)),MAX(MAX(A3:C3),MAX(OFFSET(X3,-1,-BP3+COLUMN(C3)+1,1,BP3-COLUMN(C3)))))

If BP3 isn't too big, take the max of C3 offset backward. If it is too big, take the max of two ranges: The first range is A3:C3. The second range is X3, offset up 1 row and back a number of columns (bp3-column(c3)).

If the event spans more than two rows, this won't work.


问:
How to Search Items with Attachment and keyword in Subject using Filter
I am working on a code which attachment will be download to folder location in context to subject by using a subject filter.

After a long search on the internet, my code is working but the problem here is that I want to put the keyword in the subject filter so that it will download the attachment as the subject keep changing every day

e.g. Sub: training_24357 on one day and training_24359 on the next day.

Also, I want to run my code after every 5 minutes automatically, any help will be much appreciated,

below is my code.

```<code>Sub Attachment()

    Dim OutOpened As Boolean
    Dim App As Outlook.Application
    Dim Ns As Outlook.NameSpace
    Dim Folder As Outlook.MAPIFolder
    Dim Attach As Outlook.Attachment
    Dim Item As Object
    Dim MailItem As Outlook.MailItem
    Dim subject As String
    Dim saveFolder As String
    Dim dateFormat As String

    saveFolder = "D:\Outlook\POS Visit Report"
    If Right(saveFolder, 1) <> "\" Then saveFolder = saveFolder & "\"

        subject = """*POS Visit*"""

        OutOpened = False
        On Error Resume Next
        Set App = GetObject(, "Outlook.Application")
        If Err.Number <> 0 Then
            Set App = New Outlook.Application
            OutOpened = True
        End If
   On Error GoTo 0
        If App Is Nothing Then
            MsgBox "Cannot Start Outlook Mail", vbExclamation
            Exit Sub
        End If
    Set Ns = App.GetNamespace("MAPI")
    Set Folder = Ns.GetDefaultFolder(olFolderInbox)

        If Not olFolder Is Nothing Then
            For Each Item In olFolder.Items
                If Item.Class = Outlook.ObjectClass.olMail Then
                    Set MailItem = Item
                    If MailItem.subject = subject Then
                        Debug.Print MailItem.subject
                        For Each Attach In MailItem.Attachments
                        dateFormat = Format(Now(), "yyyy-mm-dd H-mm")
                        Attach.SaveAsFile saveFolder & "(" & dateFormat & ")" & " " & Attach
                        Next
                    End If
                End If
            Next
        End If

    If OutOpened Then App.Quit
    Set App = Nothing

End Sub
</code>```

答:
To Search for Items with Attachment and by Subject line you can use Items.Restrict Method to filter Items collection containing all the match from the filter

Filter Example: [Attachment & Subject Like '%training%']

```<code>Filter = "@SQL=" & Chr(34) & "urn:schemas:httpmail:subject" & _
                   Chr(34) & " Like '%training%' AND " & _
                   Chr(34) & "urn:schemas:httpmail:hasattachment" & _
                   Chr(34) & "=1"
</code>```

VBA Example https://stackoverflow.com/a/42547062/4539709 Or https://stackoverflow.com/a/42777485/4539709

Now if your running the code from Outlook then you do not need to GetObject, or Set App = New Outlook.Application Just simply  Set Ns = Application.GetNamespace("MAPI")

To run your code when Items are added to you Inbox - Try working with Application.Startup Event (Outlook) And Items_ItemAdd Event (Outlook)

Items.ItemAdd Event Occurs when one or more Items are added to the specified collection. This event does not run when a large number of items are added to the folder at once.

Code Example:

```<code>Private WithEvents Items As Outlook.Items
Private Sub Application_Startup()
    Dim olNs As Outlook.NameSpace
    Dim Inbox  As Outlook.MAPIFolder

    Set olNs = Application.GetNamespace("MAPI")
    Set Inbox = olNs.GetDefaultFolder(olFolderInbox)
    Set Items = Inbox.Items
End Sub

Private Sub Items_ItemAdd(ByVal Item As Object)
    If TypeOf Item Is Outlook.MailItem Then
        '// call sub here
    End If
End Sub
</code>```

Body:
I am working on a code which attachment will be download to folder location in context to subject by using a subject filter.

After a long search on the internet, my code is working but the problem here is that I want to put the keyword in the subject filter so that it will download the attachment as the subject keep changing every day

e.g. Sub: training_24357 on one day and training_24359 on the next day.

Also, I want to run my code after every 5 minutes automatically, any help will be much appreciated,

below is my code.

Sub Attachment()

    Dim OutOpened As Boolean
    Dim App As Outlook.Application
    Dim Ns As Outlook.NameSpace
    Dim Folder As Outlook.MAPIFolder
    Dim Attach As Outlook.Attachment
    Dim Item As Object
    Dim MailItem As Outlook.MailItem
    Dim subject As String
    Dim saveFolder As String
    Dim dateFormat As String

    saveFolder = "D:\Outlook\POS Visit Report"
    If Right(saveFolder, 1) <> "\" Then saveFolder = saveFolder & "\"

        subject = """*POS Visit*"""

        OutOpened = False
        On Error Resume Next
        Set App = GetObject(, "Outlook.Application")
        If Err.Number <> 0 Then
            Set App = New Outlook.Application
            OutOpened = True
        End If
   On Error GoTo 0
        If App Is Nothing Then
            MsgBox "Cannot Start Outlook Mail", vbExclamation
            Exit Sub
        End If
    Set Ns = App.GetNamespace("MAPI")
    Set Folder = Ns.GetDefaultFolder(olFolderInbox)

        If Not olFolder Is Nothing Then
            For Each Item In olFolder.Items
                If Item.Class = Outlook.ObjectClass.olMail Then
                    Set MailItem = Item
                    If MailItem.subject = subject Then
                        Debug.Print MailItem.subject
                        For Each Attach In MailItem.Attachments
                        dateFormat = Format(Now(), "yyyy-mm-dd H-mm")
                        Attach.SaveAsFile saveFolder & "(" & dateFormat & ")" & " " & Attach
                        Next
                    End If
                End If
            Next
        End If

    If OutOpened Then App.Quit
    Set App = Nothing

End Sub

Body:
To Search for Items with Attachment and by Subject line you can use Items.Restrict Method to filter Items collection containing all the match from the filter

Filter Example: [Attachment & Subject Like '%training%']

Filter = "@SQL=" & Chr(34) & "urn:schemas:httpmail:subject" & _
                   Chr(34) & " Like '%training%' AND " & _
                   Chr(34) & "urn:schemas:httpmail:hasattachment" & _
                   Chr(34) & "=1"

VBA Example https://stackoverflow.com/a/42547062/4539709 Or https://stackoverflow.com/a/42777485/4539709

Now if your running the code from Outlook then you do not need to GetObject, or Set App = New Outlook.Application Just simply  Set Ns = Application.GetNamespace("MAPI")

To run your code when Items are added to you Inbox - Try working with Application.Startup Event (Outlook) And Items_ItemAdd Event (Outlook)

Items.ItemAdd Event Occurs when one or more Items are added to the specified collection. This event does not run when a large number of items are added to the folder at once.

Code Example:

Private WithEvents Items As Outlook.Items
Private Sub Application_Startup()
    Dim olNs As Outlook.NameSpace
    Dim Inbox  As Outlook.MAPIFolder

    Set olNs = Application.GetNamespace("MAPI")
    Set Inbox = olNs.GetDefaultFolder(olFolderInbox)
    Set Items = Inbox.Items
End Sub

Private Sub Items_ItemAdd(ByVal Item As Object)
    If TypeOf Item Is Outlook.MailItem Then
        '// call sub here
    End If
End Sub


问:
iTerm2 open file
iTerm2 has a nice ⌘-click to open a file in your IDE.

The problem is I'm running a web server via Vagrant, so /home/vagrant isn't really a physical directory that iTerm2 can access.

Is there a way I can either:

A.) Map /home/vagrant/ to /Sites in my .bash_profile

B.) Run it through a Find/Replace script that returns the modified path?

Any suggestions? Thanks

答:
Thanks Udlei. You definitely pointed me in the right direction. The problem with "Run Command" is that iTerm2 (currently 3.0.15) doesn't respond to clicks if it doesn't recognize the directory in the filesystem. I changed it to "Always Run Command" and was able to use your code to come up with this. I really appreciate your help.</p>

```<code>#!/bin/bash

# iTerm2 > Profiles > Adv -> Semantic History > Always Run Command:
# sh ~/click-handler.sh \1 /home/vagrant /Sites \5

original_filepath=$1
vagrant_basepath=$2
local_basepath=$3
current_pwd=$4

# remove quotes from var_dump if present
original_filepath_temp="${original_filepath%\"}"
original_filepath="${original_filepath_temp#\"}"

# look for /home/vagrant in the $original_filepath
if [[ $original_filepath =~ ^(\/home\/vagrant) ]];
    then
    new_filepath="${original_filepath/$vagrant_basepath/$local_basepath}"
    # echo $new_filepath > ~/Library/Logs/iterm.log
    /usr/local/bin/subl $new_filepath
# default local handling
    else
    original_filepath="$current_pwd/$original_filepath"
    # echo $original_filepath > ~/Library/Logs/iterm.log
    /usr/local/bin/subl $original_filepath
fi
</code>```

Title: iTerm2 open file

Body:
Thanks Udlei. You definitely pointed me in the right direction. The problem with "Run Command" is that iTerm2 (currently 3.0.15) doesn't respond to clicks if it doesn't recognize the directory in the filesystem. I changed it to "Always Run Command" and was able to use your code to come up with this. I really appreciate your help.

#!/bin/bash

# iTerm2 > Profiles > Adv -> Semantic History > Always Run Command:
# sh ~/click-handler.sh \1 /home/vagrant /Sites \5

original_filepath=$1
vagrant_basepath=$2
local_basepath=$3
current_pwd=$4

# remove quotes from var_dump if present
original_filepath_temp="${original_filepath%\"}"
original_filepath="${original_filepath_temp#\"}"

# look for /home/vagrant in the $original_filepath
if [[ $original_filepath =~ ^(\/home\/vagrant) ]];
    then
    new_filepath="${original_filepath/$vagrant_basepath/$local_basepath}"
    # echo $new_filepath > ~/Library/Logs/iterm.log
    /usr/local/bin/subl $new_filepath
# default local handling
    else
    original_filepath="$current_pwd/$original_filepath"
    # echo $original_filepath > ~/Library/Logs/iterm.log
    /usr/local/bin/subl $original_filepath
fi


问:
Is there any shortcut for array size / length in C?
Is there any way to speed up getting an array size in C?

Typing out sizeof(array)/sizeof(int) every time gets old.  Do any C libraries have something like .length or is there some way I can define sizeof(array)/sizeof(int) as a shorter constant of some sort (possible also using dot notation)?

答:
The short answer is "no"; in C, there is no way to get the number of elements in an array based on the array expression alone.  The sizeof trick is about as good as it gets, and its use is limited to expressions of array type.  So the following won't work:

```<code>char *foo = malloc(1024);
size_t count = sizeof foo;
</code>```

count receives the number of bytes for the pointer type (4 on a typical desktop architecture), not in the allocated block.

```<code>char arr[100];
char *p = arr;
size_t count = sizeof p;
</code>```

Same as above.

```<code>void foo(char *arr)
{
  size_t count = sizeof arr; // same as above
  ...
}

void bar(void)
{
  char array[100];
  foo(array);
  ...
}
</code>```

Same as above.

If you need to know how many elements are in an array, you need to track that information separately.

C's treatment of arrays is the source of a lot of heartburn.

Body:
The short answer is "no"; in C, there is no way to get the number of elements in an array based on the array expression alone.  The sizeof trick is about as good as it gets, and its use is limited to expressions of array type.  So the following won't work:

char *foo = malloc(1024);
size_t count = sizeof foo;

count receives the number of bytes for the pointer type (4 on a typical desktop architecture), not in the allocated block.

char arr[100];
char *p = arr;
size_t count = sizeof p;

Same as above.

void foo(char *arr)
{
  size_t count = sizeof arr; // same as above
  ...
}

void bar(void)
{
  char array[100];
  foo(array);
  ...
}

Same as above.

If you need to know how many elements are in an array, you need to track that information separately.

C's treatment of arrays is the source of a lot of heartburn.


问:
Static Nested Type
So i have nested type classes that go something like this:

```<code>namespace MyNamespace
{
    public class User
    {
        private int id = 0;
        private string userId = "";
        private string userPassword = "";

        public int Id
        {
            get { return id; }
            set { id = value; }
        }

        public string UserId
        {
            get { return userId; }
            set { userId = value; }
        }

        public string UserPassword
        {
            get { return userPassword; }
            set { userPassword = value; }
        }

        public User()
        {
            id = 0;
            userId = "";
            userPassword = "";
        }

        public static class SignonInfo
        {
            private static string sesstoken = "";
            private static DateTime sessstart = new DateTime();

            public static string SessToken
            {
                get { return sesstoken; }
                set { sesstoken = value; }
            }

            public static DateTime SessStart
            {
                get { return sessstart; }
                set { sessstart = value; }
            }
        }
    }
}
</code>```

My end goal here was to be able to access the nested static class like this:

```<code>User user = new User();
string token = user.SignonInfo.SessToken;
</code>```

I'm trying to avoid instantiating the class like this:

```<code>User.SignonInfo user = new User.SignonInfo()
</code>```

I need to be able to access properties of both User and SignonInfo classes.

Could someone help me to get on track or slap me about and tell me i'm doing it all wrong?

TIA

答:
The problem is that it's a static class, so an "instance" doesn't have access to it.  This is a good thing, as it prevents global state from masquerading as a well-encapsulated object.

I'd suggest making the nested class non-static, and having theUser class create an instance as needed by the caller (maybe add a public SignonInfo GetSignonInfo() method.)

Title: Static Nested Type

Body:
So i have nested type classes that go something like this:

namespace MyNamespace
{
    public class User
    {
        private int id = 0;
        private string userId = "";
        private string userPassword = "";

        public int Id
        {
            get { return id; }
            set { id = value; }
        }

        public string UserId
        {
            get { return userId; }
            set { userId = value; }
        }

        public string UserPassword
        {
            get { return userPassword; }
            set { userPassword = value; }
        }

        public User()
        {
            id = 0;
            userId = "";
            userPassword = "";
        }

        public static class SignonInfo
        {
            private static string sesstoken = "";
            private static DateTime sessstart = new DateTime();

            public static string SessToken
            {
                get { return sesstoken; }
                set { sesstoken = value; }
            }

            public static DateTime SessStart
            {
                get { return sessstart; }
                set { sessstart = value; }
            }
        }
    }
}

My end goal here was to be able to access the nested static class like this:

User user = new User();
string token = user.SignonInfo.SessToken;

I'm trying to avoid instantiating the class like this:

User.SignonInfo user = new User.SignonInfo()

I need to be able to access properties of both User and SignonInfo classes.

Could someone help me to get on track or slap me about and tell me i'm doing it all wrong?

TIA


问:
How to use group_by variable as an exclusion value with dplyr?
Let's say I have the following data frame:

```<code>(dat  = data_frame(v1 = c(rep("a", 3), rep("b", 3), rep("c", 4)), v2 = 1:10))
# A tibble: 10 × 2
#       v1    v2
#    <chr> <int>
# 1      a     1
# 2      a     2
# 3      a     3
# 4      b     4
# 5      b     5
# 6      b     6
# 7      c     7
# 8      c     8
# 9      c     9
# 10     c    10
</code>```

What I want to be able to do is compute a sum for each group (i.e. "a", "b", and "c") that is equal to the sum of v2 where v1 is not equal to the grouping value. So it should look like this:

```<code># A tibble: 3 × 2
#      v1   sum
#   <chr> <int>
# 1     a    49
# 2     b    40
# 3     c    21
</code>```

Based on what I've been seeing online, this looks like a job for do, but I can't wrap my head around how to achieve this. I thought it would look something like this:

```<code>x %>%
  group_by(v1) %>%
  do(data.frame(sum=sum(.$v2[x$v1 != unique(.$v1)])))
</code>```

But this just gives me a dataframe with sum equal to NA for all three groups. How would I go about doing this?

答:
Maybe using an intermediate column it is easier:</p>

```<code>dat %>% mutate(total = sum(v2)) %>% group_by(v1) %>% summarize(sum = max(total) - sum(v2))
</code>```

Body:
Let's say I have the following data frame:

(dat  = data_frame(v1 = c(rep("a", 3), rep("b", 3), rep("c", 4)), v2 = 1:10))
# A tibble: 10 × 2
#       v1    v2
#    <chr> <int>
# 1      a     1
# 2      a     2
# 3      a     3
# 4      b     4
# 5      b     5
# 6      b     6
# 7      c     7
# 8      c     8
# 9      c     9
# 10     c    10

What I want to be able to do is compute a sum for each group (i.e. "a", "b", and "c") that is equal to the sum of v2 where v1 is not equal to the grouping value. So it should look like this:

# A tibble: 3 × 2
#      v1   sum
#   <chr> <int>
# 1     a    49
# 2     b    40
# 3     c    21

Based on what I've been seeing online, this looks like a job for do, but I can't wrap my head around how to achieve this. I thought it would look something like this:

x %>%
  group_by(v1) %>%
  do(data.frame(sum=sum(.$v2[x$v1 != unique(.$v1)])))

But this just gives me a dataframe with sum equal to NA for all three groups. How would I go about doing this?

Body:
Maybe using an intermediate column it is easier:

dat %>% mutate(total = sum(v2)) %>% group_by(v1) %>% summarize(sum = max(total) - sum(v2))


问:
Rails app - extra record displaying
I have an app that allows users to add albums they like to a database. Anyone can then come along and write a review for that album. Pretty simple.

I am running into a problem where an extra record appears to be created for the reviews on each album's show page. Every album, even if it has not ever been reviewed, has an additional, seemingly empty review being displayed when I use .each to display each review in the album show page. I want to get rid of that.

Here is an image of the problem. I have used CSS to highlight reviews in red. As you can see, there is an empty review at the bottom. When I inspect the review in question, it's raty title is "Not reviewed yet!"

Here is my albums_controller:

```<code>class AlbumsController < ApplicationController
  before_action :set_album, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_user!, only: [:edit, :new, :update, :destroy]

  def index
    @albums = Album.all
    if params[:search].nil?
      @albums = Album.all.order(year: :desc).order(title: :asc).paginate(:page => params[:page], :per_page => 24)
    else
      @albums = @albums.where("albums.title || albums.year || albums.artist LIKE ?", "%#{params[:search]}%").order(year: :desc).order(title: :asc).paginate(:page => params[:page], :per_page => 24)
    end
  end

  def show
     if @album.reviews.blank?
      @average_review = 0
     else
      @average_review = @album.reviews.average(:rating).round(2)
     end
     @review = @album.reviews.build
   end

   def new
     @album = Album.new
   end

   def edit

   end

   def create
     @album = current_user.albums.build(album_params)

     respond_to do |format|
      if @album.save
         format.html { redirect_to @album, notice: 'Album was successfully created.' }
        format.json { render :show, status: :created, location: @album }
      else
        format.html { render :new }
        format.json { render json: @album.errors, status: :unprocessable_entity }
      end
    end
  end

  def update
     respond_to do |format|
      if @album.update(album_params)
        format.html { redirect_to @album, notice: 'Album was successfully updated.' }
        format.json { render :show, status: :ok, location: @album }
      else
        format.html { render :edit }
        format.json { render json: @album.errors, status: :unprocessable_entity }
      end
    end
  end

  def destroy
    @album.destroy
    respond_to do |format|
      format.html { redirect_to albums_url, notice: 'Album was successfully    destroyed.' }
      format.json { head :no_content }
    end
  end

private
# Use callbacks to share common setup or constraints between actions.

def set_album
  @album = Album.find(params[:id])
end

def album_params
  params.require(:album).permit(:title, :artist, :year, :cover)
end
end
</code>```

Here is the album show page, which is where the extra review is being displayed:

```<code><div class="row">
<div class="col-xs-10 col-md-6 col-md-push-3 col-xs-push-1 top bottom">
    <%= image_tag @album.cover, class: 'show_image' %>
    <h2><%= @album.title %></h2>
    <h4><%= @album.artist %></h4>
    <h5><%= @album.year %></h5>
    <p class="white">Average Review<div class="average-review-rating" data-score=<%= @average_review %>></div></p>
    <% if user_signed_in? %>
        <% if @album.user_id == current_user.id %>
            <%= link_to 'Edit', edit_album_path(@album), class: 'grey' %>
            | <%= link_to 'Delete', album_path, method: :delete, data: {confirm: "Are you sure?"}, class: 'grey' %>
        <% end %>
    <% end %>
    <br /><br />
    <h4>Reviews</h4>
    <% if user_signed_in? %>
        <p class="grey">Write a review</p>

        <%= form_for [@album, @review] do |r| %>
            <div class="form-group">
                <div id="rating-form">
                    <label>Rating</label>
                </div>
            </div>
            <div class="form-group">
                <%= r.text_area :comment, class: 'form-control', placeholder: "Write a comment" %>
            </div>
            <div class="form-group">
                <%= r.submit "Create", class: 'btn btn-success' %>
            </div>
        <% end %>
    <% end %>

    <br />
    <% @album.reviews.each do |r| %>
        <div class="red">
            <div class="review-rating" data-number="<%= r.rating %>">
            </div>
            <p class="white"><%= r.comment %></p>
            <% if user_signed_in? %>
                <% if current_user.id == r.user_id %>
                    <%= link_to 'Edit', edit_album_review_path(@album, r.id), class: 'grey' %> |
                    <%= link_to 'Delete', album_review_path(@album, r.id), method: :delete, data: {confirm: "Are you sure?"}, class: 'grey' %>
                <% end %>
            <% end %>
            <br /><br />
        </div>
    <% end %>
</div>
</div>

<script>
$('.review-rating').raty({
readOnly: true,
score: function() {
    return $(this).attr('data-number');
},
path: '/assets/'
});

$('#rating-form').raty({
path: '/assets/',
scoreName: 'review[rating]'
});

$('.average-review-rating').raty({
readOnly: true,
path: '/assets/',
score: function() {
    return $(this).attr('data-score')
}
});
</script>
</code>```

Any help would be very appreciated!

答:
I think it could be because of last line in show.

```<code>@review = @album.reviews.build
</code>```

It builds an empty review.

Title: Rails app - extra record displaying

Body:
I have an app that allows users to add albums they like to a database. Anyone can then come along and write a review for that album. Pretty simple.

I am running into a problem where an extra record appears to be created for the reviews on each album's show page. Every album, even if it has not ever been reviewed, has an additional, seemingly empty review being displayed when I use .each to display each review in the album show page. I want to get rid of that.

Here is an image of the problem. I have used CSS to highlight reviews in red. As you can see, there is an empty review at the bottom. When I inspect the review in question, it's raty title is "Not reviewed yet!"

Here is my albums_controller:

class AlbumsController < ApplicationController
  before_action :set_album, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_user!, only: [:edit, :new, :update, :destroy]

  def index
    @albums = Album.all
    if params[:search].nil?
      @albums = Album.all.order(year: :desc).order(title: :asc).paginate(:page => params[:page], :per_page => 24)
    else
      @albums = @albums.where("albums.title || albums.year || albums.artist LIKE ?", "%#{params[:search]}%").order(year: :desc).order(title: :asc).paginate(:page => params[:page], :per_page => 24)
    end
  end

  def show
     if @album.reviews.blank?
      @average_review = 0
     else
      @average_review = @album.reviews.average(:rating).round(2)
     end
     @review = @album.reviews.build
   end

   def new
     @album = Album.new
   end

   def edit

   end

   def create
     @album = current_user.albums.build(album_params)

     respond_to do |format|
      if @album.save
         format.html { redirect_to @album, notice: 'Album was successfully created.' }
        format.json { render :show, status: :created, location: @album }
      else
        format.html { render :new }
        format.json { render json: @album.errors, status: :unprocessable_entity }
      end
    end
  end

  def update
     respond_to do |format|
      if @album.update(album_params)
        format.html { redirect_to @album, notice: 'Album was successfully updated.' }
        format.json { render :show, status: :ok, location: @album }
      else
        format.html { render :edit }
        format.json { render json: @album.errors, status: :unprocessable_entity }
      end
    end
  end

  def destroy
    @album.destroy
    respond_to do |format|
      format.html { redirect_to albums_url, notice: 'Album was successfully    destroyed.' }
      format.json { head :no_content }
    end
  end

private
# Use callbacks to share common setup or constraints between actions.

def set_album
  @album = Album.find(params[:id])
end

def album_params
  params.require(:album).permit(:title, :artist, :year, :cover)
end
end

Here is the album show page, which is where the extra review is being displayed:

    <%= image_tag @album.cover, class: 'show_image' %>

<%= @album.title %>

<%= @album.artist %>

<%= @album.year %>

Average Review<div class="average-review-rating" data-score=<%= @average_review %>>

    <% if user_signed_in? %>
        <% if @album.user_id == current_user.id %>
            <%= link_to 'Edit', edit_album_path(@album), class: 'grey' %>
            | <%= link_to 'Delete', album_path, method: :delete, data: {confirm: "Are you sure?"}, class: 'grey' %>
        <% end %>
    <% end %>

Reviews

    <% if user_signed_in? %>

Write a review

        <%= form_for [@album, @review] do |r| %>

                    Rating

                <%= r.text_area :comment, class: 'form-control', placeholder: "Write a comment" %>

                <%= r.submit "Create", class: 'btn btn-success' %>

        <% end %>
    <% end %>

    <% @album.reviews.each do |r| %>

            <div class="review-rating" data-number="<%= r.rating %>">

<%= r.comment %>

            <% if user_signed_in? %>
                <% if current_user.id == r.user_id %>
                    <%= link_to 'Edit', edit_album_review_path(@album, r.id), class: 'grey' %> |
                    <%= link_to 'Delete', album_review_path(@album, r.id), method: :delete, data: {confirm: "Are you sure?"}, class: 'grey' %>
                <% end %>
            <% end %>

    <% end %>

Any help would be very appreciated!

Body:
I think it could be because of last line in show.

@review = @album.reviews.build

It builds an empty review.


问:
FilterExpression Syntax error using boto3 dynamodb client
I am trying to query dynamodb using the low-level client api of boto3.

```<code>   response = client.query(
        TableName='People',
        IndexName='country-index',
        KeyConditionExpression='country = :country',
        FilterExpression="attribute_not_exists('age') AND attribute_not_exists('address')",
        ExpressionAttributeValues={
            ":country":{"S": "USA"}
        },
        Limit=100
    )
</code>```

I get a syntax error :

An error occurred (ValidationException) when calling the Query
  operation: Invalid FilterExpression: Syntax error; token: "'", near:
  "('age"

The documentation in boto3 redirects to Amazon developer guide. I was not able to find the syntax for client.query(...). The examples listed there are for using table.query(...)

答:
Please change the FilterExpression as mentioned below.

```<code>FilterExpression="attribute_not_exists(age) AND attribute_not_exists(address)",
</code>```

Body:
I am trying to query dynamodb using the low-level client api of boto3.

   response = client.query(
        TableName='People',
        IndexName='country-index',
        KeyConditionExpression='country = :country',
        FilterExpression="attribute_not_exists('age') AND attribute_not_exists('address')",
        ExpressionAttributeValues={
            ":country":{"S": "USA"}
        },
        Limit=100
    )

I get a syntax error :

An error occurred (ValidationException) when calling the Query
  operation: Invalid FilterExpression: Syntax error; token: "'", near:
  "('age"

The documentation in boto3 redirects to Amazon developer guide. I was not able to find the syntax for client.query(...). The examples listed there are for using table.query(...)

Body:
Please change the FilterExpression as mentioned below.

FilterExpression="attribute_not_exists(age) AND attribute_not_exists(address)",


问:
What features of Scala cannot be translated to Java?
The Scala compiler compiles direct to Java byte code (or .NET CIL). Some of the features of Scala could be re-done in Java straightforwardly (e.g. simple for comprehensions, classes, translating anonymous/inner functionc etc). What are the features that cannot be translated that way?

That is presumably mostly of academic interest. More usefully, perhaps, what are the key features or idioms of Scala that YOU use that cannot be easily represented in Java?

Are there any the other way about? Things that can be done straightforwardly in Java that have no straightforward equivalent in Scala? Idioms in Java that don't translate?

答:
One feature of scala that I have found a good use for is type reification through Manifests. Since the JVM strips out all type information from generics, scala allows you to conserve this information in variables. This is something that Java reflection AFAIK can't handle, since there are no arguments to types in the bytecode.

The case I needed them was to pattern match on a type of List. This is, I had a VertexBuffer object which stored data on the GPU, that could be constructed from a List of floats or integers. The Manifest code looked approximately like this:

```<code>class VertexBuffer[T](data:List[T])(implicit m:Manifest[T]) {
  m.toString.match {
    case "float" => ...
    case "int" => ...
  }
}
</code>```

This link links to a blog post with more information.

There are plenty of SO pages with more information too, like this one.

Body:
One feature of scala that I have found a good use for is type reification through Manifests. Since the JVM strips out all type information from generics, scala allows you to conserve this information in variables. This is something that Java reflection AFAIK can't handle, since there are no arguments to types in the bytecode.

The case I needed them was to pattern match on a type of List. This is, I had a VertexBuffer object which stored data on the GPU, that could be constructed from a List of floats or integers. The Manifest code looked approximately like this:

class VertexBuffer[T](data:List[T])(implicit m:Manifest[T]) {
  m.toString.match {
    case "float" => ...
    case "int" => ...
  }
}

This link links to a blog post with more information.

There are plenty of SO pages with more information too, like this one.


问:
Counting keys in dictionary of dictionary in python
I have dict sample:

dictsample which have this structure dictsample.update({key: dif_k}), and dif_k have this structure dif_k.update({k:v})

dictsample:

```<code>{Object1 : { size : 14, cell: G, capacity : 35}, Object2 : { size : 14, load : 2}, Object3 : { size : 12, cell : F, load : 3, throughput : 55}, ...}
</code>```

I need output like this:

```<code>{Object1 : 3, Object2 : 2, Object3 : 4, ...}
</code>```

Code I have tried:

```<code>ct = {}
for key, dif_k in dictsample.iteritems():
    for k, v in dif_k.iteritems():
        dictcounter = k.count(k)
        ct.update({key:dictcounter})
</code>```

And all I got is:
    {Object1 : 1, Object2 : 1, Object3 : 1, ...}

答:
You can also do this:

```<code>the_list = {i:len(dictsample[i]) for i in dictsample.keys()}
</code>```

this method does not require iteritems and is shorter.

Edit:

To access the values by a numerical element, try this:

```<code>the_list = {len(dictsample[i]):i for i in dictsample.keys()}
</code>```

Body:
I have dict sample:

dictsample which have this structure dictsample.update({key: dif_k}), and dif_k have this structure dif_k.update({k:v})

dictsample:

{Object1 : { size : 14, cell: G, capacity : 35}, Object2 : { size : 14, load : 2}, Object3 : { size : 12, cell : F, load : 3, throughput : 55}, ...}

I need output like this:

{Object1 : 3, Object2 : 2, Object3 : 4, ...}

Code I have tried:

ct = {}
for key, dif_k in dictsample.iteritems():
    for k, v in dif_k.iteritems():
        dictcounter = k.count(k)
        ct.update({key:dictcounter})

And all I got is:
    {Object1 : 1, Object2 : 1, Object3 : 1, ...}

Body:
You can also do this:

the_list = {i:len(dictsample[i]) for i in dictsample.keys()}

this method does not require iteritems and is shorter.

Edit:

To access the values by a numerical element, try this:

the_list = {len(dictsample[i]):i for i in dictsample.keys()}


问:
How to create an array containing 1...N
I'm looking for any alternatives to the below for creating a JavaScript array containing 1 through to N where N is only known at runtime.

```<code>var foo = [];

for (var i = 1; i <= N; i++) {
   foo.push(i);
}
</code>```

To me it feels like there should be a way of doing this without the loop.

答:
Well, simple but important question. Functional JS definitely lacks a generic unfold method under the Array object since we may need to create an array of numeric items not only simple [1,2,3,...,111] but a series resulting from a function, may be like x => x*2 instead of x => x

Currently, to perform this job we have to rely on the Array.prototype.map() method. However in order to use Array.prototype.map() we need to know the size of the array in advance. Well still.. if we don't know the size, then we can utilize Array.prototype.reduce() but Array.prototype.reduce() is intended for reducing (folding) not unfolding right..?

So obviously we need an Array.unfold() tool in functional JS. This is something that we can simply implement ourselves just like;

```<code>Array.unfold = function(p,f,t,s){
  var res = [],
   runner = v =>  p(v,res.length-1,res) ? [] : (res.push(f(v)),runner(t(v)), res);
  return runner(s);
};
</code>```

Arrays.unfold(p,f,t,v) takes 4 arguments.

p This is a function which defines where to stop. The p function takes 3 arguments like many array functors do. The value, the index and the currently resulting array. It shall return a Boolean value. When it returns a true the recursive iteration stops.

f This is a function to return the next items functional value.

t This is a function to return the next argument to feed to f in the next turn.

s Is the seed value that will be used to calculate the comfortable seat of index 0 by f.

So if we intend to create an array filled with a series like 1,4,9,16,25...n^2 we can simply do like.

Array.unfold = function(p,f,t,s){
  var res = [],
   runner = v =>  p(v,res.length-1,res) ? [] : (res.push(f(v)),runner(t(v)), res);
  return runner(s);
};

var myArr = Array.unfold((_,i) => i >= 9, x => Math.pow(x,2), x => x+1, 1);
console.log(myArr);```

ContentLicense: CC BY-SA 4.0

Title: How to create an array containing 1...N

Body:
I'm looking for any alternatives to the below for creating a JavaScript array containing 1 through to N where N is only known at runtime.

var foo = [];

for (var i = 1; i <= N; i++) {
   foo.push(i);
}

To me it feels like there should be a way of doing this without the loop.

Body:
Well, simple but important question. Functional JS definitely lacks a generic unfold method under the Array object since we may need to create an array of numeric items not only simple [1,2,3,...,111] but a series resulting from a function, may be like x => x*2 instead of x => x

Currently, to perform this job we have to rely on the Array.prototype.map() method. However in order to use Array.prototype.map() we need to know the size of the array in advance. Well still.. if we don't know the size, then we can utilize Array.prototype.reduce() but Array.prototype.reduce() is intended for reducing (folding) not unfolding right..?

So obviously we need an Array.unfold() tool in functional JS. This is something that we can simply implement ourselves just like;

Array.unfold = function(p,f,t,s){
  var res = [],
   runner = v =>  p(v,res.length-1,res) ? [] : (res.push(f(v)),runner(t(v)), res);
  return runner(s);
};

Arrays.unfold(p,f,t,v) takes 4 arguments.

p This is a function which defines where to stop. The p function takes 3 arguments like many array functors do. The value, the index and the currently resulting array. It shall return a Boolean value. When it returns a true the recursive iteration stops.

f This is a function to return the next items functional value.

t This is a function to return the next argument to feed to f in the next turn.

s Is the seed value that will be used to calculate the comfortable seat of index 0 by f.

So if we intend to create an array filled with a series like 1,4,9,16,25...n^2 we can simply do like.

Array.unfold = function(p,f,t,s){
  var res = [],
   runner = v =>  p(v,res.length-1,res) ? [] : (res.push(f(v)),runner(t(v)), res);
  return runner(s);
};

var myArr = Array.unfold((_,i) => i >= 9, x => Math.pow(x,2), x => x+1, 1);
console.log(myArr);


问:
Java file logger being hijacked and redirected into a file belonging to another logger (from Gigaspaces API) after creation
I'm seeing a rather odd issue.

I created some standard Java loggers (using Logger.getLogger(), a FileHandle, and a SimpleFormatter.)
Those work fine, and output the log file as expected.

Then, I used some classes from the Gigaspaces API (com.gigaspaces.gs-openspaces - included via a Maven dependency), which includes its own logging.
After that, all of the output of my loggers ended up inside the Gigaspaces log file (e.g. ~/.m2/repository/com/gigaspaces/logs/2017-03-27~12.46-gigaspaces-service-135.60.146.142-23534.log) instead of in the appropriate log files that they are supposed to be using.

If I then create more loggers after I've initialised Gigaspaces, these new loggers work as expected.  Only loggers created before initialising gigaspaces are affected.

I tried poking around in the code for Gigaspaces a little bit, there's a lot of code in there.  I didn't see anything immediately obvious.

Am I doing something wrong with setting up my loggers?  It doesn't seem right that a library can steal the output from pre-existing loggers that are unrelated to its classes.

The below short test program demonstrates the problem:

```<code>    Logger testLog = Logger.getLogger("testlog");
    try {
        FileHandler fh = new FileHandler("testlog.log");
        fh.setFormatter(new SimpleFormatter());
        testLog.addHandler(fh);
    }
    catch (Exception e) {
        // Not important
        e.printStackTrace();
    }

    testLog.log(Level.INFO, "This appears in the main log file");

    // Spin up gigaspaces, even by trying to connect to a space that doesn't exist
    UrlSpaceConfigurer testSpaceConfigurer = new UrlSpaceConfigurer("jini://*/*/testSpace?locators=127.0.01").lookupTimeout(1);
    try {
        GigaSpace g = new GigaSpaceConfigurer(testSpaceConfigurer).gigaSpace();
    }
    catch (Exception e) {
        // This will throw an exception, just ignore it.
    }
    testSpaceConfigurer.close();

    testLog.log(Level.INFO, "This appears in the (wrong) gigaspaces log file");
</code>```

答:
You have to pin the "testlog" logger or you risk losing all of the changes you apply to it.

Modifying loggers requires permissions.  One option might be to use a custom security manager that doesn't let GigaSpaces redirect your logging.

If GigaSpaces is calling LogManager.reset(), then one hacky, smelly, dirty way to get around removing your handler is to extend FileHandler and override equals.

```<code>public class GigaSpaces {

    //Pin the logger
    private static final Logger testLog = Logger.getLogger("testlog");
    static {
        try {
            FileHandler fh = new FileHandler("testlog.log") {
                public boolean equals(Object o) {
                    return false; //Pure Evil.
                }
            };

            fh.setFormatter(new SimpleFormatter());
            testLog.addHandler(fh);
        }
        catch (Exception e) {
            // Not important
            e.printStackTrace();
        }
    }

    public void foo() throws Throwable {
        testLog.log(Level.INFO, "This appears in the main log file");

        // Spin up gigaspaces, even by trying to connect to a space that doesn't exist
        UrlSpaceConfigurer testSpaceConfigurer = new UrlSpaceConfigurer("jini://*/*/testSpace?locators=127.0.01").lookupTimeout(1);
        try {
            GigaSpace g = new GigaSpaceConfigurer(testSpaceConfigurer).gigaSpace();
        }
        catch (Exception e) {
            // This will throw an exception, just ignore it.
        } finally {
            testSpaceConfigurer.close();
        }

        testLog.log(Level.INFO, "This appears in the (wrong) gigaspaces log file");
    }
}
</code>```

Body:
I'm seeing a rather odd issue.

I created some standard Java loggers (using Logger.getLogger(), a FileHandle, and a SimpleFormatter.)
Those work fine, and output the log file as expected.

Then, I used some classes from the Gigaspaces API (com.gigaspaces.gs-openspaces - included via a Maven dependency), which includes its own logging.
After that, all of the output of my loggers ended up inside the Gigaspaces log file (e.g. ~/.m2/repository/com/gigaspaces/logs/2017-03-27~12.46-gigaspaces-service-135.60.146.142-23534.log) instead of in the appropriate log files that they are supposed to be using.

If I then create more loggers after I've initialised Gigaspaces, these new loggers work as expected.  Only loggers created before initialising gigaspaces are affected.

I tried poking around in the code for Gigaspaces a little bit, there's a lot of code in there.  I didn't see anything immediately obvious.

Am I doing something wrong with setting up my loggers?  It doesn't seem right that a library can steal the output from pre-existing loggers that are unrelated to its classes.

The below short test program demonstrates the problem:

    Logger testLog = Logger.getLogger("testlog");
    try {
        FileHandler fh = new FileHandler("testlog.log");
        fh.setFormatter(new SimpleFormatter());
        testLog.addHandler(fh);
    }
    catch (Exception e) {
        // Not important
        e.printStackTrace();
    }

    testLog.log(Level.INFO, "This appears in the main log file");

    // Spin up gigaspaces, even by trying to connect to a space that doesn't exist
    UrlSpaceConfigurer testSpaceConfigurer = new UrlSpaceConfigurer("jini://*/*/testSpace?locators=127.0.01").lookupTimeout(1);
    try {
        GigaSpace g = new GigaSpaceConfigurer(testSpaceConfigurer).gigaSpace();
    }
    catch (Exception e) {
        // This will throw an exception, just ignore it.
    }
    testSpaceConfigurer.close();

    testLog.log(Level.INFO, "This appears in the (wrong) gigaspaces log file");

Body:
You have to pin the "testlog" logger or you risk losing all of the changes you apply to it.

Modifying loggers requires permissions.  One option might be to use a custom security manager that doesn't let GigaSpaces redirect your logging.

If GigaSpaces is calling LogManager.reset(), then one hacky, smelly, dirty way to get around removing your handler is to extend FileHandler and override equals.

public class GigaSpaces {

    //Pin the logger
    private static final Logger testLog = Logger.getLogger("testlog");
    static {
        try {
            FileHandler fh = new FileHandler("testlog.log") {
                public boolean equals(Object o) {
                    return false; //Pure Evil.
                }
            };

            fh.setFormatter(new SimpleFormatter());
            testLog.addHandler(fh);
        }
        catch (Exception e) {
            // Not important
            e.printStackTrace();
        }
    }

    public void foo() throws Throwable {
        testLog.log(Level.INFO, "This appears in the main log file");

        // Spin up gigaspaces, even by trying to connect to a space that doesn't exist
        UrlSpaceConfigurer testSpaceConfigurer = new UrlSpaceConfigurer("jini://*/*/testSpace?locators=127.0.01").lookupTimeout(1);
        try {
            GigaSpace g = new GigaSpaceConfigurer(testSpaceConfigurer).gigaSpace();
        }
        catch (Exception e) {
            // This will throw an exception, just ignore it.
        } finally {
            testSpaceConfigurer.close();
        }

        testLog.log(Level.INFO, "This appears in the (wrong) gigaspaces log file");
    }
}


问:
How to add button listener to ListView?
I have a custom list item XML with 2 Buttons and I want to get when one is clicked (and a way of knowing which one). My ListView is made with data from a database. This is what I use for populating the list:

```<code>private DBManager manager;
private Cursor cursor;
private ListView lista;
SimpleCursorAdapter adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.m_home_layout);

    manager = new DBManager(this);
    lista = (ListView) findViewById(R.id.listview);

    String[] from = new String[]{manager.CN_NAME, manager.CN_DESCRIPTION, manager.CN_TIME, manager.CN_DAY};
    int[] to = new int[] {R.id.list_title, R.id.list_description, R.id.list_time, R.id.list_day};
    cursor = manager.cargarCursorData("data");
    adapter = new SimpleCursorAdapter(this, R.layout.list_item, cursor, from, to,0);
    lista.setAdapter(adapter);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
        this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

}
</code>```

I've seen people saying that you have to use bindView but I don't have anything like that and I don't know what it is. Sorry for my ignorance.

答:
You can go through this tutorials for Creating Custom Adapter, in which you can get the which Button is clicked:

http://www.survivingwithandroid.com/2012/10/android-listview-custom-adapter-and.html

http://www.journaldev.com/10416/android-listview-with-custom-adapter-example-tutorial

Title: How to add button listener to ListView?

Body:
I have a custom list item XML with 2 Buttons and I want to get when one is clicked (and a way of knowing which one). My ListView is made with data from a database. This is what I use for populating the list:

private DBManager manager;
private Cursor cursor;
private ListView lista;
SimpleCursorAdapter adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.m_home_layout);

    manager = new DBManager(this);
    lista = (ListView) findViewById(R.id.listview);

    String[] from = new String[]{manager.CN_NAME, manager.CN_DESCRIPTION, manager.CN_TIME, manager.CN_DAY};
    int[] to = new int[] {R.id.list_title, R.id.list_description, R.id.list_time, R.id.list_day};
    cursor = manager.cargarCursorData("data");
    adapter = new SimpleCursorAdapter(this, R.layout.list_item, cursor, from, to,0);
    lista.setAdapter(adapter);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
        this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

}

I've seen people saying that you have to use bindView but I don't have anything like that and I don't know what it is. Sorry for my ignorance.


问:
Search a text file for two strings and display how many strings are in between
How can I use Binary search in Java to find how many strings lie between the two strings given by the user? I have a large text file to search through.
I was thinking ((word position 2 - word position 1)-1) would give the position from an array but I am not quite sure how to put it into code. I got stuck after checking the file for the words.</p>

```<code>String[] allWords = new String[400000];
        int wordCount = 0;
    Scanner input = new Scanner(new File("C:\\text.txt"));
        while (input.hasNext()) {
    String word = input.next();
    allWords[wordCount] = word;
    wordCount++;

    System.out.println(wordCount);
}

    Scanner sc = new Scanner(new File("C:\\text.txt"));
    while(sc.hasNextLine()){
    String in = sc.nextLine();

    System.out.println("Enter a string:");
    Scanner sc2 = new Scanner(System.in);
    String str = sc2.nextLine();

    System.out.println("Enter a string:");
    Scanner sc3 = new Scanner(System.in);
    String str2 = sc3.nextLine();

    if (str.contains(str)) {
    System.out.println("yes");
}
    if (str.contains(str2)) {
    System.out.println("yes");

    }
</code>```

答: Your math is correct.  As you have surmised, subtract one from the difference of the positions.  If you have any issues with the code, post your attempt to your question.</p>

Body:
How can I use Binary search in Java to find how many strings lie between the two strings given by the user? I have a large text file to search through.
I was thinking ((word position 2 - word position 1)-1) would give the position from an array but I am not quite sure how to put it into code. I got stuck after checking the file for the words.

String[] allWords = new String[400000];
        int wordCount = 0;
    Scanner input = new Scanner(new File("C:\\text.txt"));
        while (input.hasNext()) {
    String word = input.next();
    allWords[wordCount] = word;
    wordCount++;

    System.out.println(wordCount);
}

    Scanner sc = new Scanner(new File("C:\\text.txt"));
    while(sc.hasNextLine()){
    String in = sc.nextLine();

    System.out.println("Enter a string:");
    Scanner sc2 = new Scanner(System.in);
    String str = sc2.nextLine();

    System.out.println("Enter a string:");
    Scanner sc3 = new Scanner(System.in);
    String str2 = sc3.nextLine();

    if (str.contains(str)) {
    System.out.println("yes");
}
    if (str.contains(str2)) {
    System.out.println("yes");

    }


问:
What is a practical use for PHP's sleep()?
I just had a look at the docs on sleep().

Where would you use this function?

Is it there to give the CPU a break in an expensive function?

Any common pitfalls?

答:
This is a bit of an odd case...file transfer throttling.

In a file transfer service we ran a long time ago, the files were served from 10Mbps uplink servers.  To prevent the network from bogging down, the download script tracked how many users were downloading at once, and then calculated how many bytes it could send per second per user.  It would send part of this amount, then sleep a moment (1/4 second, I think) then send more...etc.

In this way, the servers ran continuously at about 9.5Mbps, without having uplink saturation issues...and always dynamically adjusting speeds of the downloads.

I wouldn't do it this way, or in PHP, now...but it worked great at the time.