问:
R package: read in data via system.file() and read.table() from R data.table
I'm creating an R package with several files in /data. The way one loads data in the R package is to use the system.file(),

```<code>system.file(..., package = "base", lib.loc = NULL, mustWork = FALSE)
</code>```

The file in /data I would like to load into an R data.table has the extension *.txt.gz, my_file.txt.gz. How do I load this into a data.table via read.table() or fread()?

Within the R script, I tried :

```<code>#' @import data.table
#' @export
my_function = function(){

    my_table = read.table(system.file("data", "my_file.txt.gz", package = "FusionVizR"), header=TRUE)

}
</code>```

This leads to an error via devtools document():

```<code>Error in read.table(system.file("data", "my_file.txt.gz", package = "FusionVizR"), header = TRUE) (from script1.R#7) :
  no lines available in input
In addition: Warning message:
In file(file, "rt") :
  file("") only supports open = "w+" and open = "w+b": using the former
</code>```

I appear to get the same issue via fread()

```<code>#' @import data.table
#' @export
my_function() = function(){

    my_table = fread(system.file("data", "my_file.txt.gz", package = "FusionVizR"), header=TRUE)

}
</code>```

This outputs the error:

```<code>Input is either empty or fully whitespace after the skip or autostart. Run again with verbose=TRUE.
</code>```

So, it appears that system.file() doesn't give an object to the file which I could load into an R data.table. How do I do this?

答:
Do yourself a HUGE favour and study fread() closely: it is one of the very best features in data.table. I have examples (at work) of reading from a pipe of other commands, of reading compresse data and more.

Here is a simple mock example:

```<code>R> write.csv(iris, file="/tmp/demo.csv")
R> system("gzip /tmp/demo.csv")  # to be very plain
R> fread("zcat /tmp/demo.csv.gz")
      V1 Sepal.Length Sepal.Width Petal.Length Petal.Width   Species
  1:   1          5.1         3.5          1.4         0.2    setosa
  2:   2          4.9         3.0          1.4         0.2    setosa
  3:   3          4.7         3.2          1.3         0.2    setosa
  4:   4          4.6         3.1          1.5         0.2    setosa
  5:   5          5.0         3.6          1.4         0.2    setosa
 ---
146: 146          6.7         3.0          5.2         2.3 virginica
147: 147          6.3         2.5          5.0         1.9 virginica
148: 148          6.5         3.0          5.2         2.0 virginica
149: 149          6.2         3.4          5.4         2.3 virginica
150: 150          5.9         3.0          5.1         1.8 virginica
R>
</code>```

Seems in the hast I wrote one column too many (rownames) but you get the idea.

Now, you don't even need fread (but it still more powerful than the alternatives):

```<code>R> head(read.csv(file="/tmp/demo.csv.gz"))
  X Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 1          5.1         3.5          1.4         0.2  setosa
2 2          4.9         3.0          1.4         0.2  setosa
3 3          4.7         3.2          1.3         0.2  setosa
4 4          4.6         3.1          1.5         0.2  setosa
5 5          5.0         3.6          1.4         0.2  setosa
6 6          5.4         3.9          1.7         0.4  setosa
R>
</code>```

R figured out by itself it needed to compress the file.

Edit: I was editing this question earlier when it was deleted under me, which is about as de-motivating as it gets.  In a nutshell:

system.file() works, e.g. file <- system.file("rawdata", "population.csv", package="gunsales") does contain the complete path as the file exists: "/usr/local/lib/R/site-library/gunsales/rawdata/population.csv". But this is easy to mess up. (Needless to say I do have the package and the file.)

look into the data/ directory and what Writing R Extensions says. It is a good mechanism.

Body:
I'm creating an R package with several files in /data. The way one loads data in the R package is to use the system.file(),

system.file(..., package = "base", lib.loc = NULL, mustWork = FALSE)

The file in /data I would like to load into an R data.table has the extension *.txt.gz, my_file.txt.gz. How do I load this into a data.table via read.table() or fread()?

Within the R script, I tried :

#' @import data.table
#' @export
my_function = function(){

    my_table = read.table(system.file("data", "my_file.txt.gz", package = "FusionVizR"), header=TRUE)

}

This leads to an error via devtools document():

Error in read.table(system.file("data", "my_file.txt.gz", package = "FusionVizR"), header = TRUE) (from script1.R#7) :
  no lines available in input
In addition: Warning message:
In file(file, "rt") :
  file("") only supports open = "w+" and open = "w+b": using the former

I appear to get the same issue via fread()

#' @import data.table
#' @export
my_function() = function(){

    my_table = fread(system.file("data", "my_file.txt.gz", package = "FusionVizR"), header=TRUE)

}

This outputs the error:

Input is either empty or fully whitespace after the skip or autostart. Run again with verbose=TRUE.

So, it appears that system.file() doesn't give an object to the file which I could load into an R data.table. How do I do this?

Body:
Do yourself a HUGE favour and study fread() closely: it is one of the very best features in data.table. I have examples (at work) of reading from a pipe of other commands, of reading compresse data and more.

Here is a simple mock example:

R> write.csv(iris, file="/tmp/demo.csv")
R> system("gzip /tmp/demo.csv")  # to be very plain
R> fread("zcat /tmp/demo.csv.gz")
      V1 Sepal.Length Sepal.Width Petal.Length Petal.Width   Species
  1:   1          5.1         3.5          1.4         0.2    setosa
  2:   2          4.9         3.0          1.4         0.2    setosa
  3:   3          4.7         3.2          1.3         0.2    setosa
  4:   4          4.6         3.1          1.5         0.2    setosa
  5:   5          5.0         3.6          1.4         0.2    setosa
 ---
146: 146          6.7         3.0          5.2         2.3 virginica
147: 147          6.3         2.5          5.0         1.9 virginica
148: 148          6.5         3.0          5.2         2.0 virginica
149: 149          6.2         3.4          5.4         2.3 virginica
150: 150          5.9         3.0          5.1         1.8 virginica
R>

Seems in the hast I wrote one column too many (rownames) but you get the idea.

Now, you don't even need fread (but it still more powerful than the alternatives):

R> head(read.csv(file="/tmp/demo.csv.gz"))
  X Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 1          5.1         3.5          1.4         0.2  setosa
2 2          4.9         3.0          1.4         0.2  setosa
3 3          4.7         3.2          1.3         0.2  setosa
4 4          4.6         3.1          1.5         0.2  setosa
5 5          5.0         3.6          1.4         0.2  setosa
6 6          5.4         3.9          1.7         0.4  setosa
R>

R figured out by itself it needed to compress the file.

Edit: I was editing this question earlier when it was deleted under me, which is about as de-motivating as it gets.  In a nutshell:

system.file() works, e.g. file <- system.file("rawdata", "population.csv", package="gunsales") does contain the complete path as the file exists: "/usr/local/lib/R/site-library/gunsales/rawdata/population.csv". But this is easy to mess up. (Needless to say I do have the package and the file.)

look into the data/ directory and what Writing R Extensions says. It is a good mechanism.


来源: stackexchange

问:
Spring boot mongodb autoconfigure throws exception "Cannot determine embedded database driver class for database type NONE"
I am using Spring boot to develop a Spring batch application. I will need my application to write the data finally to MongoDB and thus needs to configure org.springframework.data.mongodb.core.MongoTemplate for org.springframework.batch.item.data.MongoItemWriter.

My pom.xml dependency section looks like this-

```<code><dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-batch</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.batch</groupId>
            <artifactId>spring-batch-test</artifactId>
            <version>${spring.batch.version}</version>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.18</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.jongo/jongo -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.jvnet.jaxb2_commons/jaxb2-basics-runtime -->
        <dependency>
            <groupId>org.jvnet.jaxb2_commons</groupId>
            <artifactId>jaxb2-basics-runtime</artifactId>
            <version>1.11.1</version>
        </dependency>

        <!--<dependency>-->
            <!--<groupId>de.flapdoodle.embed</groupId>-->
            <!--<artifactId>de.flapdoodle.embed.mongo</artifactId>-->
            <!--<version>1.50.5</version>-->
            <!--<scope>test</scope>-->
        <!--</dependency>-->

        <!--<dependency>-->
            <!--<groupId>cz.jirutka.spring</groupId>-->
            <!--<artifactId>embedmongo-spring</artifactId>-->
            <!--<version>RELEASE</version>-->
            <!--<scope>test</scope>-->
        <!--</dependency>-->

        <!-- https://mvnrepository.com/artifact/org.mongodb/mongo-java-driver -->
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongo-java-driver</artifactId>
            <version>3.6.0</version>
        </dependency>

    </dependencies>
</code>```

The application.properties file looks like this

```<code>spring.data.mongodb.host=mongohost
spring.data.mongodb.port=27017
spring.data.mongodb.authentication-database=authdb
spring.data.mongodb.username=user
spring.data.mongodb.password=pwd

spring.datasource.driver-class-name=<< I don't know what to put here >>
</code>```

Main class is also simple enough and looks like this-

```<code>@SpringBootApplication
public class Main {
    public static void main(String[] args) {
        SpringApplication.run(Main.class, args);
    }
}
</code>```

Now, whenever I try to run my Main class it gives out error

```<code>***************************
APPLICATION FAILED TO START
***************************

Description:

Cannot determine embedded database driver class for database type NONE

Action:

If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active).
</code>```

After researching a lot about this problem, I figured out that I need to let Spring know about my data store by providing the value of spring.datasource.driver-class-name in application.properties

```<code>spring.datasource.driver-class-name=com.mongodb.Server
</code>```

If I provide com.mongodb.Server as my drive class name its not found on classpath and isn't recognised despite I have mongo java driver dependency on my classpath.

What should I put the value for mongoDB's driver-class-name provided I want to use mongo-java-driver?

If driver class name is not the cause of this issue, what should be the resolution of issue "Cannot determine embedded database driver class for database type NONE"mentioned in title of this question?

答:
Try exluding DataSourceAutoConfiguration.class in your main class:

```<code>@SpringBootApplication
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
public class Main {
    public static void main(String[] args) {
        SpringApplication.run(Main.class, args);
    }
}
</code>```

Also you don't need this:

```<code>spring.datasource.driver-class-name
</code>```

unless you need jpa configuration as well.

ContentLicense: CC BY-SA 3.0

Body:
I am using Spring boot to develop a Spring batch application. I will need my application to write the data finally to MongoDB and thus needs to configure org.springframework.data.mongodb.core.MongoTemplate for org.springframework.batch.item.data.MongoItemWriter.

My pom.xml dependency section looks like this-

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-batch</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.batch</groupId>
            <artifactId>spring-batch-test</artifactId>
            <version>${spring.batch.version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.18</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>${slf4j.version}</version>
        </dependency>

        <dependency>
            <groupId>org.jvnet.jaxb2_commons</groupId>
            <artifactId>jaxb2-basics-runtime</artifactId>
            <version>1.11.1</version>
        </dependency>

        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongo-java-driver</artifactId>
            <version>3.6.0</version>
        </dependency>

    </dependencies>

The application.properties file looks like this

spring.data.mongodb.host=mongohost
spring.data.mongodb.port=27017
spring.data.mongodb.authentication-database=authdb
spring.data.mongodb.username=user
spring.data.mongodb.password=pwd

spring.datasource.driver-class-name=<>

Main class is also simple enough and looks like this-

@SpringBootApplication
public class Main {
    public static void main(String[] args) {
        SpringApplication.run(Main.class, args);
    }
}

Now, whenever I try to run my Main class it gives out error

***************************
APPLICATION FAILED TO START
***************************

Description:

Cannot determine embedded database driver class for database type NONE

Action:

If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active).

After researching a lot about this problem, I figured out that I need to let Spring know about my data store by providing the value of spring.datasource.driver-class-name in application.properties

spring.datasource.driver-class-name=com.mongodb.Server

If I provide com.mongodb.Server as my drive class name its not found on classpath and isn't recognised despite I have mongo java driver dependency on my classpath.

What should I put the value for mongoDB's driver-class-name provided I want to use mongo-java-driver?

If driver class name is not the cause of this issue, what should be the resolution of issue "Cannot determine embedded database driver class for database type NONE"mentioned in title of this question?

Body:
Try exluding DataSourceAutoConfiguration.class in your main class:

@SpringBootApplication
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
public class Main {
    public static void main(String[] args) {
        SpringApplication.run(Main.class, args);
    }
}

Also you don't need this:

spring.datasource.driver-class-name

unless you need jpa configuration as well.


问:
When Language is set on Korean，enter Youtube“Search”Page and input some character，character ghosting
When Language is set on Korean for TV，enter Youtube “Search” Page and input some character，we found that character ghosting.As shown in image Linux_TV.jpg. It is NG. It should be noted that only some combinations of characters will appear this phenomenon

For comparison, I use a PC browser test.The result is shown in picture PC.png. It is OK.

From the picture PC.png we can see that when you enter some combination of characters, the top and bottom of different characters are not aligned.

Can you help to check it.

答:
This does not look like a Cobalt issue. Can you please work with your YouTube technical account manager with more details?
1. If this happens only with Cobalt or not.
2. Which fonts do you use.</p>


问:
Cannot append extra data to jquery-fileupload call
I am trying to integrate file uploading functionality to my Django app using jQuery File Upload Plugin which can be found here. Now, I am already attaching csrf token with the input tag in the template like that:

```<code><input id="fileupload" type="file" name="document" multiple
               style="display: none;"
               data-url="{% url 'upload' %}"
               data-form-data='{"csrfmiddlewaretoken": "{{ csrf_token }}"}'>
</code>```

However, later in JS file I would like to append some extra information to this form. The proposed way is to do that by using formData as shown:

```<code>$("#fileupload").fileupload({
    dataType: 'json',
    formData: {employee_id: get_selected_employee()},
    done: function (e, data) {
        }
    }
});
</code>```

However, this new data does not get appended to formData, which is already created in the template and contains csrf_token.

If I try to append the csrf token and employee_id in .fileupload call I get 403 (CSRF token missing or incorrect) even though the csrf token seems to be valid. I cannot append employee_id in the template as it's dynamically changing. Does anyone have any thoughts?

答:
I dynamically appended the data to data-form-data, so it looked something like that:

```<code>data-form-data='{"csrfmiddlewaretoken": "{{ csrf_token }}", "employee_id": "<employee_id>"}'
</code>```

However, I had multiple other issues with jQuery File Upload, thus decided to switch to Dropzone, it took me 3 hrs to set up everything whereas I spent 3 days trying to integrate jQuery File Upload.

Body:
I am trying to integrate file uploading functionality to my Django app using jQuery File Upload Plugin which can be found here. Now, I am already attaching csrf token with the input tag in the template like that:

<input id="fileupload" type="file" name="document" multiple
               style="display: none;"
               data-url="{% url 'upload' %}"
               data-form-data='{"csrfmiddlewaretoken": "{{ csrf_token }}"}'>

However, later in JS file I would like to append some extra information to this form. The proposed way is to do that by using formData as shown:

$("#fileupload").fileupload({
    dataType: 'json',
    formData: {employee_id: get_selected_employee()},
    done: function (e, data) {
        }
    }
});

However, this new data does not get appended to formData, which is already created in the template and contains csrf_token.

If I try to append the csrf token and employee_id in .fileupload call I get 403 (CSRF token missing or incorrect) even though the csrf token seems to be valid. I cannot append employee_id in the template as it's dynamically changing. Does anyone have any thoughts?

Body:
I dynamically appended the data to data-form-data, so it looked something like that:

data-form-data='{"csrfmiddlewaretoken": "{{ csrf_token }}", "employee_id": "<employee_id>"}'

However, I had multiple other issues with jQuery File Upload, thus decided to switch to Dropzone, it took me 3 hrs to set up everything whereas I spent 3 days trying to integrate jQuery File Upload.


问:
Comparing two integers without any comparison
Is it possible to find the greatest of two integers without any comparison? I found some  solutions:

```<code>if(!(a/b)) // if a is less than b then division result will be zero.
{
    cout << " b is greater than a";
}
else if (!(a-b)) // we know a is greater than or equal to b now.  check whether they are equal.
{
    cout << "a and b are equal";
}
else
    cout << "a is greater than b";
</code>```

But if(c) or if(!c) is a comparison to zero. In addition it doesn't work for negative numbers. In fact I need a solution that avoids any if statement. Instead I should use switch statements and arithmetic operators. ThanX.

答:
```<code>void greater(int a, int b) {
    int c = a - b;
    switch(c) {
        case 0:
            cout << "a and b are equal" << endl;
            break;
        default:
            int d = c & (1<<31);
            switch(d) {
                case 0:
                    cout << "a is bigger than b" << endl;
                    break;
                default:
                    cout << "a is less than b" << endl;
            }
    }
}
</code>```

OwnerDisplayName: kvphxga

ContentLicense: CC BY-SA 2.5

Body:
Is it possible to find the greatest of two integers without any comparison? I found some  solutions:

if(!(a/b)) // if a is less than b then division result will be zero.
{
    cout << " b is greater than a";
}
else if (!(a-b)) // we know a is greater than or equal to b now.  check whether they are equal.
{
    cout << "a and b are equal";
}
else
    cout << "a is greater than b";

But if(c) or if(!c) is a comparison to zero. In addition it doesn't work for negative numbers. In fact I need a solution that avoids any if statement. Instead I should use switch statements and arithmetic operators. ThanX.

LastEditorDisplayName: kvphxga


问:
Starred files in a spreadsheet
My starring workflow needs some work. I thought about creating a script to run in drive that looks for starred files (docs, slides, sheets) and adds them to spreadsheet.

I'm a complete noob, so I've checked the script reference to try and find snippets that might work.

```<code>iterate through drive
if starred file found
  add to new row in spreadsheet
</code>```

```<code>// Log the name of every starred file in the Designated Spreedsheet.
function addStarred() {
  var sheet = SpreadsheetApp.getActiveSheet(); //this will need to change to a designated sheet
  var files = DriveApp.getFiles();

  while (files.isStarred()) {
    var file = files.next();
    sheet.appendRow(file.getName());
  }
}
</code>```

The ideal would be a list in my spreadsheet that can then be filtered to find the correct starred file.

The first error I see is:

"Cannot find function isStarred in object FileIterator. (line 6, file "Code")"

Appreciate any help.

答: This is a bit of a curve ball, but this might be a good use case for IFTTT. I looked and they support starred files as a trigger and adding a row to a spreadsheet as an output. You'll have to load the spreadsheet initially since the trigger only fires for new stars.</p>

Title: Starred files in a spreadsheet

Body:
My starring workflow needs some work. I thought about creating a script to run in drive that looks for starred files (docs, slides, sheets) and adds them to spreadsheet.

I'm a complete noob, so I've checked the script reference to try and find snippets that might work.

iterate through drive
if starred file found
  add to new row in spreadsheet

// Log the name of every starred file in the Designated Spreedsheet.
function addStarred() {
  var sheet = SpreadsheetApp.getActiveSheet(); //this will need to change to a designated sheet
  var files = DriveApp.getFiles();

  while (files.isStarred()) {
    var file = files.next();
    sheet.appendRow(file.getName());
  }
}

The ideal would be a list in my spreadsheet that can then be filtered to find the correct starred file.

The first error I see is:

"Cannot find function isStarred in object FileIterator. (line 6, file "Code")"

Appreciate any help.


问:
Spark ML Logistic Regression in Python: Set the model threshold to maximize F-Measure
I've trained a logistic regression in Spark using pipeline. It ran and I am looking at model diagnostics.

I created my model summary (lr_summary = lrModel.stages[-1].summary).
After that I pretty much copied the code from this webpage. It all works until I try to determine the best threshold based on F-measure using this example Python code:

```<code># Set the model threshold to maximize F-Measure
fMeasure = lr_summary.fMeasureByThreshold
maxFMeasure = fMeasure.groupBy().max('F-Measure').select('max(F-Measure)').head()
bestThreshold = fMeasure.where(fMeasure['F-Measure'] == maxFMeasure['max(F-Measure)']).select('threshold').head()['threshold']
lr.setThreshold(bestThreshold)
</code>```

Unfortunately, I am getting an error in line 3 (bestThreshold = ):
TypeError: 'NoneType' object has no attribute 'getitem'

Any advice?

Thank you so much!

答:
I cannot reproduce this problem, but it is possible that model doesn't have summary (in that case I would expect attribute error in maxFMeasure = ... line). You can check if model has one:

```<code>lrModel.stages[-1].hasSummary
</code>```

Also you can make this code much simpler:

```<code>bestThreshold = fMeasure.orderBy(fMeasure['F-Measure'].desc()).first().threshold
</code>```

Body:
I've trained a logistic regression in Spark using pipeline. It ran and I am looking at model diagnostics.

I created my model summary (lr_summary = lrModel.stages[-1].summary).
After that I pretty much copied the code from this webpage. It all works until I try to determine the best threshold based on F-measure using this example Python code:

# Set the model threshold to maximize F-Measure
fMeasure = lr_summary.fMeasureByThreshold
maxFMeasure = fMeasure.groupBy().max('F-Measure').select('max(F-Measure)').head()
bestThreshold = fMeasure.where(fMeasure['F-Measure'] == maxFMeasure['max(F-Measure)']).select('threshold').head()['threshold']
lr.setThreshold(bestThreshold)

Unfortunately, I am getting an error in line 3 (bestThreshold = ):
TypeError: 'NoneType' object has no attribute 'getitem'

Any advice?

Thank you so much!

Body:
I cannot reproduce this problem, but it is possible that model doesn't have summary (in that case I would expect attribute error in maxFMeasure = ... line). You can check if model has one:

lrModel.stages[-1].hasSummary

Also you can make this code much simpler:

bestThreshold = fMeasure.orderBy(fMeasure['F-Measure'].desc()).first().threshold


问:
Unable to get numbers from window.location.search
I am using the following code in my JS file:

```<code>var match = window.location.search.match(/(\d*)/);
this.room = (match) ? decodeURIComponent(match) : 0;
</code>```

And I am trying to just get the numbers from my URL. For example, in www.myurl.com/streams228, I just want to get the 228.

The issue I am getting is it is just returning %2, nothing else, or 0.

答:
Try the following:

var url ="www.myurl.com/streams228"
var match = url.match(/([\d]+)/g);
console.log(match[0]);```

Body:
I am using the following code in my JS file:

var match = window.location.search.match(/(\d*)/);
this.room = (match) ? decodeURIComponent(match) : 0;

And I am trying to just get the numbers from my URL. For example, in www.myurl.com/streams228, I just want to get the 228.

The issue I am getting is it is just returning %2, nothing else, or 0.


问:
VS2017 15.5 installs .NET core 2.1.2?
I've installed the 15.5 update for VS2017 on two separate machines. I now see on both that I have something claiming to be Microsoft .NET Core SDK - 2.1.2 (x64). I've found no trace of this on Google. Is this a mistake? A prerelease?

答:
This is expected.

The 2.1.2 release of the .NET Core SDK (not runtime!) contains the same MSBuild version, build extensions and SDKs (the bits referenced <Project Sdk="(this SDK string)">) as VS 2017 15.5.

At the time of writing, the official download sites have not been updated to include this release.

The source code for this release can be found in the release/2.1 branch of the dotnet/cli GitHub repository.

Title: VS2017 15.5 installs .NET core 2.1.2?


问:
Regex for find accent letters that aren't inside html/jsp comments

Hello I need to find all the accent words that aren't inside comments in jsp files.
By example.

```<code><%--This jsp comment have accents áóéí--%>
<html>
<!--This html comment have accents áóéí-->

<h1>This text have accents áóí</h1>
<html>
</code>```

I need to find the accent letter inside the h1 tag but no the ones inside the comments.

Until now I had the regex to find the comments but I don't know how to negate that part.
This is the Regex I had:

```<code>\<[!%][ \r\n\t]*(--([^\-]|[\r\n]|-[^\-])*--[ \r\n\t]*)\%*>
</code>```

I try

```<code>[ó](?!(\<[!%][ \r\n\t]*(--([^\-]|[\r\n]|-[^\-])*--[ \r\n\t]*)\%*>))
</code>```

But it didn't works.

How I could negate that expresion?

答:
It is not feasible to match the inner text of each and every HTML tag with a regex.

I suggest using a Java HTML parser instead. jsoup is a good one. See jsoup cookbook for more examples.

```<code>String html = "<p>An <a href='http://example.com/'><b>example</b></a> link.</p>";
Document doc = Jsoup.parse(html);
Element link = doc.select("a").first();

String text = doc.body().text(); // "An example link"
String linkHref = link.attr("href"); // "http://example.com/"
String linkText = link.text(); // "example""
</code>```

Body:
Hello I need to find all the accent words that aren't inside comments in jsp files.
By example.

<%--This jsp comment have accents áóéí--%>

This text have accents áóí

I need to find the accent letter inside the h1 tag but no the ones inside the comments.

Until now I had the regex to find the comments but I don't know how to negate that part.
This is the Regex I had:

\<[!%][ \r\n\t]*(--([^\-]|[\r\n]|-[^\-])*--[ \r\n\t]*)\%*>

I try

[ó](?!(\<[!%][ \r\n\t]*(--([^\-]|[\r\n]|-[^\-])*--[ \r\n\t]*)\%*>))

But it didn't works.

How I could negate that expresion?

Body:
It is not feasible to match the inner text of each and every HTML tag with a regex.

I suggest using a Java HTML parser instead. jsoup is a good one. See jsoup cookbook for more examples.

String html = "<p>An <a href='http://example.com/'><b>example</b></a> link.</p>";
Document doc = Jsoup.parse(html);
Element link = doc.select("a").first();

String text = doc.body().text(); // "An example link"
String linkHref = link.attr("href"); // "http://example.com/"
String linkText = link.text(); // "example""


问:
Should I ask my web host to use PHP Version 5.3.5 on my VPS
Situation:: My current web host has given me a brand new VPS today with PHP 5.2.9 (released: Feb 2009).

What I did: I asked my web host to upgrade it to latest PHP 5.3.5 so I can get all security vulnerabilities fixed.

What web host replied: No, you should not. Your PHP scripts will break. Instead you can use PHP 5.2.17.

My Question: Should I force my web host to install PHP 5.3.5 on my VPS? What problem can possibly I get by upgrading. I currently do not use any PHP 5.3 features but may use those in future. My main concern is to get fully secure from known vulnerabilities.

Please don't close this question. It's not directly related to programming but is related to PHP which only PHP experts at SO can answer, I guess.

答:
Well, simply install PHP 5.3.5 locally and see if any of your scripts break. If everything's okay, let them install PHP 5.3.

Concerning "It will break things": PHP normally is backwards compatible. Maybe it will give you some E_STRICT errors, but those don't break scripts. But really, you should just try ;)


问:
Why React setState is not triggering re-render?
I am trying to use react and update properties with setState, however, it doesnt seem to re-render.

In the following code, you will see that the onStart and onComplete use setState to update the style property.

The property gets updated, but the style does not get changed in the dom, despite my render function appearing to be set up in the correct way?

```<code>export default class FirstScene extends React.Component {
    constructor() {
        super();
        let self=this;
        this.state = {
            style:{display:'hidden'}
        };
        this.mainTimeline= new TimelineMax({repeat:0,paused:true,
            onStart:function(){
                self.setState({style:{display:'block'}})
            }.bind(self),
            onComplete:function(){
                self.setState({style:{display:'hidden'}})
                console.log(this.state);
            }.bind(self)
        });
    }

    render() {
        return (
            <div style={this.state.style} >test hey</div>
        )
    }

};
</code>```

答:
The constructor should be used only to initialize the state. You should not call this.setState in the contructor you should indeed try to move TimelineMax to componentDidMount. Moreover because this.setState is asynchronous calling it multiple times won't work e.g.

```<code>class Counter extends React.Component{
        constructor(props){
            super(props)
            //initial state set up
            this.state = {value:0}
        }
        componentDidMount(){
            //updating state, OUTPUT will be 1
            this.setState({value:this.state.value+1})
            this.setState({value:this.state.value+1})
            this.setState({value:this.state.value+1})
            this.setState({value:this.state.value+1})
        }
        render(){
            return <div>Message:{this.state.value}</div>
        }
    }
</code>```

I believe this is why your module doesn't work. So you should either use the callback to this.SetState that is triggered after the state is updated or use componentDidUpdate
docs ref

Body:
I am trying to use react and update properties with setState, however, it doesnt seem to re-render.

In the following code, you will see that the onStart and onComplete use setState to update the style property.

The property gets updated, but the style does not get changed in the dom, despite my render function appearing to be set up in the correct way?

export default class FirstScene extends React.Component {
    constructor() {
        super();
        let self=this;
        this.state = {
            style:{display:'hidden'}
        };
        this.mainTimeline= new TimelineMax({repeat:0,paused:true,
            onStart:function(){
                self.setState({style:{display:'block'}})
            }.bind(self),
            onComplete:function(){
                self.setState({style:{display:'hidden'}})
                console.log(this.state);
            }.bind(self)
        });
    }

    render() {
        return (

test hey

        )
    }

};

Body:
The constructor should be used only to initialize the state. You should not call this.setState in the contructor you should indeed try to move TimelineMax to componentDidMount. Moreover because this.setState is asynchronous calling it multiple times won't work e.g.

class Counter extends React.Component{
        constructor(props){
            super(props)
            //initial state set up
            this.state = {value:0}
        }
        componentDidMount(){
            //updating state, OUTPUT will be 1
            this.setState({value:this.state.value+1})
            this.setState({value:this.state.value+1})
            this.setState({value:this.state.value+1})
            this.setState({value:this.state.value+1})
        }
        render(){
            return <div>Message:{this.state.value}</div>
        }
    }

I believe this is why your module doesn't work. So you should either use the callback to this.SetState that is triggered after the state is updated or use componentDidUpdate
docs ref


问:
Importing CSV While Creating Relationship In Neo4j
I am trying to create a relationship between two different graphs, using information in a CSV file. I built the query the way I did because the size of each graph, one being 500k+ and the other 1.5m+.

This is the query I have:

```<code>LOAD CSV WITH HEADERS FROM "file:///customers_table.csv" AS row WITH row
MATCH (m:Main) WITH m
MATCH (c:Customers) USING INDEX c:Customers(customer)
WHERE m.ASIN = row.asin AND c.customer = row.customer
CREATE (c)-[:RATED]->(m)
</code>```

This is the error I receive:

```<code>Variable `row` not defined (line 4, column 16 (offset: 164))
"WHERE m.ASIN = row.asin AND c.customer = row.customer"
                ^
</code>```

An example of the Main table is:

```<code>{
  "ASIN": "0827229534",
  "totalreviews": "2",
  "categories": "2",
  "title": "Patterns of Preaching: A Sermon Sampler",
  "avgrating": "5",
  "group": "Book"
}
</code>```

And an example of a customer is:

```<code>{
  "customer": "A2FMUVHRO76A32"
}
</code>```

And inside the customers table csv, I have:

```<code>Customer, ASIN, rating
A2FMUVHRO76A32, 0827229534, 5
</code>```

I can't seem to figure out why it's throwing back that error.

答:
The first WITH clause in your query (WITH row) is unnecessary, but you have to add the variable to the WITH clause. So this version compiles.

```<code>LOAD CSV WITH HEADERS FROM "file:///customers_table.csv" AS row
MATCH (m:Main)
WITH m, row
MATCH (c:Customers) USING INDEX c:Customers(customer)
WHERE m.ASIN = row.asin AND c.customer = row.customer
CREATE (c)-[:RATED]->(m)
</code>```

The reason for this is, that, in essence, WITH chains two query parts together, while limiting the scope to its variables (and in some cases,  also performing calculations, aggregations, etc.).

Having said that, you do not even need the second WITH clause, you can just omit it and even merge the two MATCH clauses to a single one:

```<code>LOAD CSV WITH HEADERS FROM "file:///customers_table.csv" AS row
MATCH (m:Main), (c:Customers) USING INDEX c:Customers(customer)
WHERE m.ASIN = row.asin AND c.customer = row.customer
CREATE (c)-[:RATED]->(m)
</code>```

Body:
I am trying to create a relationship between two different graphs, using information in a CSV file. I built the query the way I did because the size of each graph, one being 500k+ and the other 1.5m+.

This is the query I have:

LOAD CSV WITH HEADERS FROM "file:///customers_table.csv" AS row WITH row
MATCH (m:Main) WITH m
MATCH (c:Customers) USING INDEX c:Customers(customer)
WHERE m.ASIN = row.asin AND c.customer = row.customer
CREATE (c)-[:RATED]->(m)

This is the error I receive:

Variable `row` not defined (line 4, column 16 (offset: 164))
"WHERE m.ASIN = row.asin AND c.customer = row.customer"
                ^

An example of the Main table is:

{
  "ASIN": "0827229534",
  "totalreviews": "2",
  "categories": "2",
  "title": "Patterns of Preaching: A Sermon Sampler",
  "avgrating": "5",
  "group": "Book"
}

And an example of a customer is:

{
  "customer": "A2FMUVHRO76A32"
}

And inside the customers table csv, I have:

Customer, ASIN, rating
A2FMUVHRO76A32, 0827229534, 5

I can't seem to figure out why it's throwing back that error.

Body:
The first WITH clause in your query (WITH row) is unnecessary, but you have to add the variable to the WITH clause. So this version compiles.

LOAD CSV WITH HEADERS FROM "file:///customers_table.csv" AS row
MATCH (m:Main)
WITH m, row
MATCH (c:Customers) USING INDEX c:Customers(customer)
WHERE m.ASIN = row.asin AND c.customer = row.customer
CREATE (c)-[:RATED]->(m)

The reason for this is, that, in essence, WITH chains two query parts together, while limiting the scope to its variables (and in some cases,  also performing calculations, aggregations, etc.).

Having said that, you do not even need the second WITH clause, you can just omit it and even merge the two MATCH clauses to a single one:

LOAD CSV WITH HEADERS FROM "file:///customers_table.csv" AS row
MATCH (m:Main), (c:Customers) USING INDEX c:Customers(customer)
WHERE m.ASIN = row.asin AND c.customer = row.customer
CREATE (c)-[:RATED]->(m)


问:
Iress feed - Excel and VBA
So I am running a spreadsheet with a whole bunch of stock codes.
I don't have any problem going via the IRESS addin for excel to get a data feed of prices.

However in my sheet, it gives the option for client to stocks and then it pre-populates a table with information such as stock code, price. However it also is meant to do a calculation of how many units a person would have if they were to invest $x amount into each stock. The problem here is when I run a macro, the iress feed does not refresh and just shows #Value in the cell.

However when I end the macro, the prices start feeding.
This is what I get:

The macro breaks when I try to calculate the units.

For formula that the code enters into the cell is:

```<code>  Cells(i, cp.Column) = "=IRESSRtd( ""Quote"" , ""13"" , ""0"" , "" " & Cells(i, stock.Column) & """)/100"
</code>```

'i' is a loop starting at the first row where there is a stock code, to the lastrow where there is a stock code, then under the "current price" column, it enters that formula.

cp.column is the column reference for 'cp' where 'cp' is set by a .find function.
Same with the stock.column reference.
Might be a bit of a long shot, but does anyone know how I can get the Iress feed to update without having to stop my macro?

答: IRESS support recommends to either use the UI of the Excel addin to generate the RTD links, or if you really want to do a lot more number crunching in the VBA you could call the IRESS API directly - i.e. IRESS Server API COM interface calling the PricingQuoteGet method (with Updates enabled). There is a sample on getting quote info back in the IRESS help files ”IRESS PRO FE > Help | API Documentation | IRESS Server API | Programmer's Guide</p>

Title: Iress feed - Excel and VBA

Body:
So I am running a spreadsheet with a whole bunch of stock codes.
I don't have any problem going via the IRESS addin for excel to get a data feed of prices.

However in my sheet, it gives the option for client to stocks and then it pre-populates a table with information such as stock code, price. However it also is meant to do a calculation of how many units a person would have if they were to invest $x amount into each stock. The problem here is when I run a macro, the iress feed does not refresh and just shows #Value in the cell.

However when I end the macro, the prices start feeding.
This is what I get:

The macro breaks when I try to calculate the units.

For formula that the code enters into the cell is:

  Cells(i, cp.Column) = "=IRESSRtd( ""Quote"" , ""13"" , ""0"" , "" " & Cells(i, stock.Column) & """)/100"

'i' is a loop starting at the first row where there is a stock code, to the lastrow where there is a stock code, then under the "current price" column, it enters that formula.

cp.column is the column reference for 'cp' where 'cp' is set by a .find function.
Same with the stock.column reference.
Might be a bit of a long shot, but does anyone know how I can get the Iress feed to update without having to stop my macro?


问:
Applescript: Rsync multiple drives to 1 organised drive
I've been working on a simple automator backup utility using applescript and rsync and got everything working apart from 1 more issue, when starting the script, I want to be able to select multiple hard drives to back up (which works), afterwards, I allow selection of only 1 backup drive, the problem is, I want all the selected drives to reside in their own folder on the backup drive (see attached screenshots), but am a bit lost on how I should do this (I am new to applescript and rsync and only got this far by doing a lot of research, but am now stuck)

This is the code I have, all the drive paths are in the 'sources' variable, which i iterate over in a for loop.

```<code>    set sources to (choose folder with prompt "Select drives to back up" default location "Volumes" with multiple selections allowed)
    set destination to (the POSIX path of (choose folder with prompt "Select destination volume" default location "Volumes"))

    #for loop iterating all sources to backup
    repeat with aliasPath in sources

        set source to the POSIX path of aliasPath

        set sciptsFinished to false

        tell application "Terminal"
            if not (exists window 1) then reopen
            activate
            do script "rsync --dry-run --archive -v --progress --exclude=\".*\"  --delete --delete-during --stats --human-readable --human-readable " & quoted form of source & " " & quoted form of destination in window 1

            delay 5 #give terminal time to activate
            repeat while (window 1 is busy)
                delay 1
            end repeat

            do script "osascript -e 'display notification \"RSYNC file changes calculated.\" with title \"RSYNC Backup\"'" in window 1

            #mark scripts completed
            set scriptsFinished to true

        end tell

        #wait for scripts to finish before proceeding
        repeat while (scriptsFinished is false)
            delay 2
        end repeat
</code>```

Any help would be greatly appreciated (and if you have remarks regarding the code, please feel free to enlighten me, as I am still a rookie at applescript)

Thanks in advance!

Sources to backup (multiple selections allowed

Destination drive (only 1 selection allowed)

答:
Fixed this using a little trick:

The path returned from choose folder and converted to POSIX path has an ending forward slash, e.g.
Volumes/Data Drive X/

However, when not providing this last slash, a folder with the same name is expected at the path destination (and created if not available), which is exactly what i needed.

To remove the last slash from the path, I simply added the following after converting the alias to a POSIX path:
    set source to text 1 thru -2 of source

so that
    Volumes/Data Drive X/
becomes
    Volumes/Data Drive X

Hope this helps anyone with the same issue! :)

Body:
I've been working on a simple automator backup utility using applescript and rsync and got everything working apart from 1 more issue, when starting the script, I want to be able to select multiple hard drives to back up (which works), afterwards, I allow selection of only 1 backup drive, the problem is, I want all the selected drives to reside in their own folder on the backup drive (see attached screenshots), but am a bit lost on how I should do this (I am new to applescript and rsync and only got this far by doing a lot of research, but am now stuck)

This is the code I have, all the drive paths are in the 'sources' variable, which i iterate over in a for loop.

    set sources to (choose folder with prompt "Select drives to back up" default location "Volumes" with multiple selections allowed)
    set destination to (the POSIX path of (choose folder with prompt "Select destination volume" default location "Volumes"))

    #for loop iterating all sources to backup
    repeat with aliasPath in sources

        set source to the POSIX path of aliasPath

        set sciptsFinished to false

        tell application "Terminal"
            if not (exists window 1) then reopen
            activate
            do script "rsync --dry-run --archive -v --progress --exclude=\".*\"  --delete --delete-during --stats --human-readable --human-readable " & quoted form of source & " " & quoted form of destination in window 1

            delay 5 #give terminal time to activate
            repeat while (window 1 is busy)
                delay 1
            end repeat

            do script "osascript -e 'display notification \"RSYNC file changes calculated.\" with title \"RSYNC Backup\"'" in window 1

            #mark scripts completed
            set scriptsFinished to true

        end tell

        #wait for scripts to finish before proceeding
        repeat while (scriptsFinished is false)
            delay 2
        end repeat

Any help would be greatly appreciated (and if you have remarks regarding the code, please feel free to enlighten me, as I am still a rookie at applescript)

Thanks in advance!

Sources to backup (multiple selections allowed

Destination drive (only 1 selection allowed)


问:
python mock exception handling
I have couple of tasks in my workflow..Now, I want to mock the output of Task1 returning exception and just test task2.run method  is not called.

```<code>class Task1():
    def run(self):
        try:
            return 2,2
        except Exception as e:
            print e
            raise Exception('Task1 Exception')

class Task2():
    def run(self,x,y):
        try:
            return 2 * (x*y)
        except Exception as e:
            print e
            raise Exception('Task2 Exception')

class Workflow():
    def run(self,task1, task2):
        x,y = task1.run()
        print task2.run(x,y)

task1 = Task1()
task2 = Task2()

w = Workflow()
w.run(task1,task2)
</code>```

Here is my unittest -

```<code>import unittest
import mock
from test2 import Task1, Task2, Workflow
class TestWorkflow(unittest.TestCase):
    def test_workflow(self):
        self.task1 = mock.MagicMock(Task1()) # mocking task1
        self.task2 = mock.MagicMock(Task2())
        self.task1.side_effect = Exception() # setting task1 exception to an exception object

        self.workflow = Workflow()
        self.workflow.run(self.task1, self.task2)
        self.task2.run.assert_not_called() # checking task2 is not called.

if __name__ == '__main__':
    unittest.main()
</code>```

Exception:-

```<code>    x,y = task1.run()
ValueError: need more than 0 values to unpack
</code>```

答:
Given the syntax, you are using Python 2, but I will refer to the documentation in the Python 3 official documentation anyway. I believe the solution applies.

The first example is:

```<code>from unittest.mock import MagicMock

thing = ProductionClass()
thing.method = MagicMock(return_value=3)
thing.method(3, 4, 5, key='value')
#prints 3

thing.method.assert_called_with(3, 4, 5, key='value')
</code>```

Bringing this your problem you would have the code below instead of your current code. See that I'm assigning the Task1.run and Task2.run methods to a MagicMock instance.

```<code>import unittest
import mock
from t import Task1, Task2, Workflow
class TestWorkflow(unittest.TestCase):
    def test_workflow(self):
        self.task1 = Task1()
        self.task1.run = mock.MagicMock() # mocking run from task1
        self.task2 = Task2()
        self.task2.run = mock.MagicMock()
        self.task1.run.side_effect = Exception() # setting task1 exception to an exception object

        self.workflow = Workflow()
        self.workflow.run(self.task1, self.task2)
        self.task2.run.assert_not_called() # checking task2 is not called.

if __name__ == '__main__':
    unittest.main()
</code>```

Title: python mock exception handling

Body:
I have couple of tasks in my workflow..Now, I want to mock the output of Task1 returning exception and just test task2.run method  is not called.

class Task1():
    def run(self):
        try:
            return 2,2
        except Exception as e:
            print e
            raise Exception('Task1 Exception')

class Task2():
    def run(self,x,y):
        try:
            return 2 * (x*y)
        except Exception as e:
            print e
            raise Exception('Task2 Exception')

class Workflow():
    def run(self,task1, task2):
        x,y = task1.run()
        print task2.run(x,y)

task1 = Task1()
task2 = Task2()

w = Workflow()
w.run(task1,task2)

Here is my unittest -

import unittest
import mock
from test2 import Task1, Task2, Workflow
class TestWorkflow(unittest.TestCase):
    def test_workflow(self):
        self.task1 = mock.MagicMock(Task1()) # mocking task1
        self.task2 = mock.MagicMock(Task2())
        self.task1.side_effect = Exception() # setting task1 exception to an exception object

        self.workflow = Workflow()
        self.workflow.run(self.task1, self.task2)
        self.task2.run.assert_not_called() # checking task2 is not called.

if __name__ == '__main__':
    unittest.main()

Exception:-

    x,y = task1.run()
ValueError: need more than 0 values to unpack

Body:
Given the syntax, you are using Python 2, but I will refer to the documentation in the Python 3 official documentation anyway. I believe the solution applies.

The first example is:

from unittest.mock import MagicMock

thing = ProductionClass()
thing.method = MagicMock(return_value=3)
thing.method(3, 4, 5, key='value')
#prints 3

thing.method.assert_called_with(3, 4, 5, key='value')

Bringing this your problem you would have the code below instead of your current code. See that I'm assigning the Task1.run and Task2.run methods to a MagicMock instance.

import unittest
import mock
from t import Task1, Task2, Workflow
class TestWorkflow(unittest.TestCase):
    def test_workflow(self):
        self.task1 = Task1()
        self.task1.run = mock.MagicMock() # mocking run from task1
        self.task2 = Task2()
        self.task2.run = mock.MagicMock()
        self.task1.run.side_effect = Exception() # setting task1 exception to an exception object

        self.workflow = Workflow()
        self.workflow.run(self.task1, self.task2)
        self.task2.run.assert_not_called() # checking task2 is not called.

if __name__ == '__main__':
    unittest.main()

ContentLicense: CC BY-SA 4.0


问:
remove value from string
If I have a string with IDs

```<code>$myIDs = '22,34,445,67889,23';
</code>```

and I am given a value, how do I remove it from the string, assuming I know for sure it is in the string?

```<code>$removeID = '445';
</code>```

Do I user preg_replace or is there a better method? For example, if it is in the middle of the string and I remove just a value, I'll end up with two commas and then I need to replace those with a single comma?

```<code>preg_replace($removeID, '', $myIDs);
</code>```

UPDATE: These are all great suggestions. However, I just thought about one potential issue. This probably need to be handled as an array instead of regex. What is my string looks like this

```<code>$myIDs = '2312,23,234234';
</code>```

and ID to remove

```<code>$removeID = '23';
</code>```

There's too many potential matches...

答:
Here's a regular expression to do the job, for the item "89":

```<code>/(^|,)89(?=,|$)/
</code>```

It matches ",89" (or just "89" if it's at the beginning of the input), as long as it's followed directly by either another "," or the end of the input.

With proper escaping and some abstraction:

```<code><?php
$myIDs = '23,45,678967,89,12';
$toRemove = 89;

$myIDs = preg_replace('/(^|,)' . preg_quote($toRemove) . '(?=,|$)/', '', $myIDs);
?>
</code>```

Tested with multiple inputs.

Hope that helps!

Title: remove value from string

Body:
If I have a string with IDs

$myIDs = '22,34,445,67889,23';

and I am given a value, how do I remove it from the string, assuming I know for sure it is in the string?

$removeID = '445';

Do I user preg_replace or is there a better method? For example, if it is in the middle of the string and I remove just a value, I'll end up with two commas and then I need to replace those with a single comma?

preg_replace($removeID, '', $myIDs);

UPDATE: These are all great suggestions. However, I just thought about one potential issue. This probably need to be handled as an array instead of regex. What is my string looks like this

$myIDs = '2312,23,234234';

and ID to remove

$removeID = '23';

There's too many potential matches...

Body:
Here's a regular expression to do the job, for the item "89":

/(^|,)89(?=,|$)/

It matches ",89" (or just "89" if it's at the beginning of the input), as long as it's followed directly by either another "," or the end of the input.

With proper escaping and some abstraction:

<?php
$myIDs = '23,45,678967,89,12';
$toRemove = 89;

$myIDs = preg_replace('/(^|,)' . preg_quote($toRemove) . '(?=,|$)/', '', $myIDs);
?>

Tested with multiple inputs.

Hope that helps!


答:
The solution was setting the parameter maxsum to some max number:

```<code>summary = summary(d, maxsum = 2000)
</code>```

Title: get summary to compute more values

Body:
Currently, running the summary command on my data only prints the first 100 values. The remaining 876671 values in the (Other) category, as show below, are NA values. How can I get these values?

>summary(d)

  7/4/2015  8/27/2015   7/4/2012  8/29/2015   7/5/2015   8/7/2015   6/6/2015  8/26/2016   7/6/2015
       754        738        736        725        723        721        719        719        717
  7/3/2015  8/15/2015  9/12/2015  7/10/2015  8/21/2015  8/28/2015  9/11/2015   7/4/2014 10/31/2015
       714        709        709        708        708        704        702        701        699
 8/26/2015  8/20/2015  10/8/2015   7/1/2016  9/12/2016  7/28/2015  8/22/2015   8/3/2015   7/2/2015
       697        695        690        689        686        682        682        681        680
 7/23/2015   7/4/2013   8/2/2015 10/16/2015 10/17/2015  9/27/2016   8/1/2014  8/19/2015  9/16/2016
       680        680        679        676        676        676        673        673        673
 9/30/2015   5/7/2016  6/25/2015  6/28/2016   5/2/2016  9/19/2015   9/9/2015   4/8/2016  5/13/2016
       673        671        671        671        670        670        670        669        668
  7/8/2015   8/1/2015  11/1/2014   4/7/2016   8/2/2016   8/2/2014  8/22/2016  10/6/2015  7/20/2016
       668        668        667        665        665        664        663        661        661
 4/18/2016  8/17/2015  8/27/2016   5/6/2016   8/8/2015  9/20/2014  10/4/2015   5/8/2015  7/24/2015
       659        658        658        657        657        657        656        656        656
 8/10/2013  8/13/2016  8/20/2016  9/20/2015   7/6/2016  8/12/2015  6/25/2016  8/23/2015  10/3/2015
       656        656        656        655        654        654        653        653        652
 9/25/2016  6/27/2016   6/3/2016   6/8/2015   7/1/2015  9/26/2016   7/3/2014  8/14/2015  8/15/2014
       652        650        650        650        650        650        649        649        649
  9/2/2016  9/30/2016  10/2/2015  4/17/2015  7/25/2016  7/31/2015   7/7/2015   8/4/2013   8/4/2015
       649        649        648        647        647        647        647        647        646
10/30/2015  11/4/2016  9/29/2015  7/17/2015   9/6/2014  9/18/2015  9/25/2015 10/29/2016  6/19/2015
       645        645        645        644        644        643        643        642        642
   (Other)
    876671

Body:
The solution was setting the parameter maxsum to some max number:

summary = summary(d, maxsum = 2000)


问:
Counting even and odd number of letters in words
I am currently trying to count how many words from a textfile have even numbers and odd numbers of characters but I cant seem to get it to work. so far i have done

```<code>    int countEven = 0;
    int countOdd = 0;
    for (int i = 0; i <latinLength.length(); i++) {
        if (Character.isLetter(latinLength.charAt(i))) {
            countEven++;
        } else {
            countOdd++;
        }
    }
    System.out.println("Total number of unique even words in Latin names = " + countEven);
    System.out.println("Total number of unique odd words in Latin names = " + countOdd);
}
</code>```

i think what i did wrong is i am not accessing the right part of the text file. i do have a get function for the information i want which is getLatinName, but i am not sure how to implement it correctly

```<code>    String tempLatinName = " ";
    String latinLength = " ";
    int letters = 0;
    for (int i = 0; i < info.size(); i++) {
        tempLatinName = info.get(i).getLatinName();
        latinLength = tempLatinName.replace(" ","");
        letters += latinLength.length();
    }
    System.out.println("Total number of letters in all Latin names = " + letters);
</code>```

i have edited the code to show the bit i have done before trying to calculate how many words have odd and even number of characters, the code above is to calculate the total number of characters in each word and then gives me a total

```<code>/**
*
* @author g_ama
*/
import java.io.*;
import java.util.*;

public class Task1 {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) throws FileNotFoundException, IOException {

    BufferedReader reader = new BufferedReader(new FileReader("shark-data.txt"));
    String line;
    List<Shark> info = new ArrayList<>();
    while ((line = reader.readLine()) != null) {
        String[] data = line.split(":");

        int MaxLength = Integer.parseInt(data[2]);
        int MaxDepth = Integer.parseInt(data[3]);
        int MaxYoung;
        try {
            MaxYoung = Integer.parseInt(data[4]);
        } catch (Exception X) {
            MaxYoung = -1;
        }
        int GlobalPresence = Integer.parseInt(data[5]);

        ArrayList<String> OceanicRegion = new ArrayList<>();
        String[] Region = data[6].split(",");
        for (String Element : Region) {
            OceanicRegion.add(Element);
        }

        Shark shark = new Shark(data[0], data[1], MaxLength, MaxDepth, MaxYoung, GlobalPresence, OceanicRegion);

        info.add(shark);
    }
    Collections.sort(info);
    System.out.println("The three largest sharks");
    System.out.println(info.get(info.size() - 1).getCommonName() + ", " + info.get(info.size() - 1).MaxLength + " cm");
    System.out.println(info.get(info.size() - 2).getCommonName() + ", " + info.get(info.size() - 2).MaxLength + " cm");
    System.out.println(info.get(info.size() - 3).getCommonName() + ", " + info.get(info.size() - 3).MaxLength + " cm");

    System.out.println("The three smallest sharks");
    System.out.println(info.get(0).getCommonName() + ", " + info.get(0).MaxLength + " cm");
    System.out.println(info.get(1).getCommonName() + ", " + info.get(1).MaxLength + " cm");
    System.out.println(info.get(2).getCommonName() + ", " + info.get(2).MaxLength + " cm");

    //count total characters for Latin Name
    String tempLatinName = " ";
    String latinLength = " ";
    int letters = 0;
    for (int i = 0; i < info.size(); i++) {
        tempLatinName = info.get(i).getLatinName();
        latinLength = tempLatinName.replace(" ", "");
        letters += latinLength.length();
    }
    System.out.println("Total number of letters in all Latin names = " + letters);

    //count even or odd words
    int countEven = 0;
    int countOdd = 0;
    for (int i = 0; i < latinLength.length(); i++) {
        if (Character.isLetter(latinLength.charAt(i))) {
            countEven++;
        } else {
            countOdd++;
        }
    }
    System.out.println("Total number of unique even words in Latin names = " + countEven);
    System.out.println("Total number of unique odd words in Latin names = " + countOdd);
}
</code>```

}

答:
Explanation

Currently you are only counting how many letters and non-letters your text has. That is of course not the amount of even words or odd words.

For example if you have a word like

```<code>test12foo!$bar
</code>```

Your code will currently output

```<code>countEven => 10  // Amount of letters (testfoobar)
countOdd  => 4   // Amount of non-letters (12!$)
</code>```

Compare this to your if-condition:

```<code>if (Character.isLetter(latinLength.charAt(i))) {
    countEven++;
} else {
    countOdd++;
}
</code>```

What you want is to count how often the length of your words is even or odd, so suppose words like

```<code>test     // length 4, even
foo      // length 3, odd
bartest  // length 7, odd
</code>```

then you want

```<code>countEven => 1 // (test)
countOdd  => 2 // (foo, bartest)
</code>```

Solution

Instead you will need to split your text into words (tokenize). After that you will need to count, for each word, the amount of characters. If that is even you may increase countEven by one. Likewise countOdd++ if it's an odd number.

The core will be this condition

```<code>word.length() % 2 == 0
</code>```

it is true if the word has an even length and false if it's odd. You can easily verify this yourself (% returns the remainder after division, 0 or 1 in this case).

Let's assume your text structure is simple and words are always separated by whitespace, i.e. something like

```<code>test foo bar John Doe
</code>```

All in all your code could then look like

```<code>Path path = Paths.get("myFile.txt");
AtomicInteger countEven = new AtomicInteger(0);
AtomicInteger countOdd = new AtomicInteger(0);
Pattern wordPattern = Pattern.compile(" ");

Files.lines(path)                         // Stream<String> lines
    .flatMap(wordPattern::splitAsStream)  // Stream<String> words
    .mapToInt(String::length)             // IntStream length
    .forEach(length -> {
        if (length % 2 == 0) {
            countEven.getAndIncrement();
        } else {
            countOdd.getAndIncrement();
        }
    });

System.out.println("Even words: " + countEven.get());
System.out.println("Odd words: " + countOdd.get());
</code>```

Or without all that Stream stuff:

```<code>Path path = Paths.get("myFile.txt");

List<String> lines = Files.readAllLines(path);
List<String> words = new ArrayList<>();

// Read words
for (String line : lines) {
    String[] wordsOfLine = line.split(" ");
    words.addAll(Arrays.asList(wordsOfLine));
}

// Count even and odd words
int countEven = 0;
int countOdd = 0;
for (String word : words) {
    if (word.length() % 2 == 0) {
        countEven++;
    } else {
        countOdd++;
    }
}

System.out.println("Even words: " + countEven);
System.out.println("Odd words: " + countOdd);
</code>```

Adjusted to your specific code

As you've just added your specific code I'll add a solution adapted to it.

In your code the list info contains all Sharks. From those sharks the words you want to consider is represented by Shark#getLatinName. So all you will need to do is some kind of this:

```<code>List<String> words = info.stream()  // Stream<Shark> sharks
    .map(Shark::getLatinName)       // Stream<String> names
    .collect(Collectors.toList());
</code>```

and you can use this words exactly as shown in the other code examples. Alternatively you don't need to collect everything into a new list, you can directly stay in the Stream and continue with the stream-approach shown before. All in all:

```<code>AtomicInteger countEven = new AtomicInteger(0);
AtomicInteger countOdd = new AtomicInteger(0);

info.stream()                             // Stream<Shark> sharks
    .map(Shark::getLatinName)             // Stream<String> names
    .mapToInt(String::length)             // IntStream length of names
    .forEach(length -> {
        if (length % 2 == 0) {
            countEven.getAndIncrement();
        } else {
            countOdd.getAndIncrement();
        }
    });

System.out.println("Even words: " + countEven);
System.out.println("Odd words: " + countOdd);
</code>```

And substitute this into that part in your code:

```<code>//count even or odd words

(substitute here)
</code>```

Body:
I am currently trying to count how many words from a textfile have even numbers and odd numbers of characters but I cant seem to get it to work. so far i have done

    int countEven = 0;
    int countOdd = 0;
    for (int i = 0; i <latinLength.length(); i++) {
        if (Character.isLetter(latinLength.charAt(i))) {
            countEven++;
        } else {
            countOdd++;
        }
    }
    System.out.println("Total number of unique even words in Latin names = " + countEven);
    System.out.println("Total number of unique odd words in Latin names = " + countOdd);
}

i think what i did wrong is i am not accessing the right part of the text file. i do have a get function for the information i want which is getLatinName, but i am not sure how to implement it correctly

    String tempLatinName = " ";
    String latinLength = " ";
    int letters = 0;
    for (int i = 0; i < info.size(); i++) {
        tempLatinName = info.get(i).getLatinName();
        latinLength = tempLatinName.replace(" ","");
        letters += latinLength.length();
    }
    System.out.println("Total number of letters in all Latin names = " + letters);

i have edited the code to show the bit i have done before trying to calculate how many words have odd and even number of characters, the code above is to calculate the total number of characters in each word and then gives me a total

/**
*
* @author g_ama
*/
import java.io.*;
import java.util.*;

public class Task1 {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) throws FileNotFoundException, IOException {

    BufferedReader reader = new BufferedReader(new FileReader("shark-data.txt"));
    String line;
    List<Shark> info = new ArrayList<>();
    while ((line = reader.readLine()) != null) {
        String[] data = line.split(":");

        int MaxLength = Integer.parseInt(data[2]);
        int MaxDepth = Integer.parseInt(data[3]);
        int MaxYoung;
        try {
            MaxYoung = Integer.parseInt(data[4]);
        } catch (Exception X) {
            MaxYoung = -1;
        }
        int GlobalPresence = Integer.parseInt(data[5]);

        ArrayList<String> OceanicRegion = new ArrayList<>();
        String[] Region = data[6].split(",");
        for (String Element : Region) {
            OceanicRegion.add(Element);
        }

        Shark shark = new Shark(data[0], data[1], MaxLength, MaxDepth, MaxYoung, GlobalPresence, OceanicRegion);

        info.add(shark);
    }
    Collections.sort(info);
    System.out.println("The three largest sharks");
    System.out.println(info.get(info.size() - 1).getCommonName() + ", " + info.get(info.size() - 1).MaxLength + " cm");
    System.out.println(info.get(info.size() - 2).getCommonName() + ", " + info.get(info.size() - 2).MaxLength + " cm");
    System.out.println(info.get(info.size() - 3).getCommonName() + ", " + info.get(info.size() - 3).MaxLength + " cm");

    System.out.println("The three smallest sharks");
    System.out.println(info.get(0).getCommonName() + ", " + info.get(0).MaxLength + " cm");
    System.out.println(info.get(1).getCommonName() + ", " + info.get(1).MaxLength + " cm");
    System.out.println(info.get(2).getCommonName() + ", " + info.get(2).MaxLength + " cm");

    //count total characters for Latin Name
    String tempLatinName = " ";
    String latinLength = " ";
    int letters = 0;
    for (int i = 0; i < info.size(); i++) {
        tempLatinName = info.get(i).getLatinName();
        latinLength = tempLatinName.replace(" ", "");
        letters += latinLength.length();
    }
    System.out.println("Total number of letters in all Latin names = " + letters);

    //count even or odd words
    int countEven = 0;
    int countOdd = 0;
    for (int i = 0; i < latinLength.length(); i++) {
        if (Character.isLetter(latinLength.charAt(i))) {
            countEven++;
        } else {
            countOdd++;
        }
    }
    System.out.println("Total number of unique even words in Latin names = " + countEven);
    System.out.println("Total number of unique odd words in Latin names = " + countOdd);
}

}

Body:
Explanation

Currently you are only counting how many letters and non-letters your text has. That is of course not the amount of even words or odd words.

For example if you have a word like

test12foo!$bar

Your code will currently output

countEven => 10  // Amount of letters (testfoobar)
countOdd  => 4   // Amount of non-letters (12!$)

Compare this to your if-condition:

if (Character.isLetter(latinLength.charAt(i))) {
    countEven++;
} else {
    countOdd++;
}

What you want is to count how often the length of your words is even or odd, so suppose words like

test     // length 4, even
foo      // length 3, odd
bartest  // length 7, odd

then you want

countEven => 1 // (test)
countOdd  => 2 // (foo, bartest)

Solution

Instead you will need to split your text into words (tokenize). After that you will need to count, for each word, the amount of characters. If that is even you may increase countEven by one. Likewise countOdd++ if it's an odd number.

The core will be this condition

word.length() % 2 == 0

it is true if the word has an even length and false if it's odd. You can easily verify this yourself (% returns the remainder after division, 0 or 1 in this case).

Let's assume your text structure is simple and words are always separated by whitespace, i.e. something like

test foo bar John Doe

All in all your code could then look like

Path path = Paths.get("myFile.txt");
AtomicInteger countEven = new AtomicInteger(0);
AtomicInteger countOdd = new AtomicInteger(0);
Pattern wordPattern = Pattern.compile(" ");

Files.lines(path)                         // Stream<String> lines
    .flatMap(wordPattern::splitAsStream)  // Stream<String> words
    .mapToInt(String::length)             // IntStream length
    .forEach(length -> {
        if (length % 2 == 0) {
            countEven.getAndIncrement();
        } else {
            countOdd.getAndIncrement();
        }
    });

System.out.println("Even words: " + countEven.get());
System.out.println("Odd words: " + countOdd.get());

Or without all that Stream stuff:

Path path = Paths.get("myFile.txt");

List<String> lines = Files.readAllLines(path);
List<String> words = new ArrayList<>();

// Read words
for (String line : lines) {
    String[] wordsOfLine = line.split(" ");
    words.addAll(Arrays.asList(wordsOfLine));
}

// Count even and odd words
int countEven = 0;
int countOdd = 0;
for (String word : words) {
    if (word.length() % 2 == 0) {
        countEven++;
    } else {
        countOdd++;
    }
}

System.out.println("Even words: " + countEven);
System.out.println("Odd words: " + countOdd);

Adjusted to your specific code

As you've just added your specific code I'll add a solution adapted to it.

In your code the list info contains all Sharks. From those sharks the words you want to consider is represented by Shark#getLatinName. So all you will need to do is some kind of this:

List<String> words = info.stream()  // Stream<Shark> sharks
    .map(Shark::getLatinName)       // Stream<String> names
    .collect(Collectors.toList());

and you can use this words exactly as shown in the other code examples. Alternatively you don't need to collect everything into a new list, you can directly stay in the Stream and continue with the stream-approach shown before. All in all:

AtomicInteger countEven = new AtomicInteger(0);
AtomicInteger countOdd = new AtomicInteger(0);

info.stream()                             // Stream<Shark> sharks
    .map(Shark::getLatinName)             // Stream<String> names
    .mapToInt(String::length)             // IntStream length of names
    .forEach(length -> {
        if (length % 2 == 0) {
            countEven.getAndIncrement();
        } else {
            countOdd.getAndIncrement();
        }
    });

System.out.println("Even words: " + countEven);
System.out.println("Odd words: " + countOdd);

And substitute this into that part in your code:

//count even or odd words

(substitute here)


问:
Python data.table from h2o
I've seen two H2O demos including Sri's keynote at H2O World 2017, and they have mentioned a Python version of the R data.table package.  However, I have been unable to find any additional info regarding this.

Is this available as a stand alone python module (or planning on becoming one)?

答:
Your understanding is correct. H2O is currently developing Python datatable package, with the goal to make it as close to R's data.table as possible, both in syntax and in speed. The package will be released open source once it has a certain minimal number of features. Currently there is no set date for the release, but we hope to do it before the end of March.

UPDATE: datatable is now publicly open.

Title: Python data.table from h2o


问:
C++ subclassing access modifier?
I'm C++ newbie, and I have many years of experience about OO languages such as C/C#/Objective-C. Now, I'm learning C++.

I saw this C++ code:

```<code>    class World : public State
    {
    };
</code>```

It seems class World inherits the class State publicly.
Public subclassing? It's hard to understand.

What's the concept of this feature?
And when is this useful or required?

答:
The public/protected/private keyword before the name of the ancestor class indicates the desired visibility of members from the ancestor. With private inheritance, the descendant inherits only the implementation from the ancestor, but not the interface.

```<code>class A {
public:
  void foo();
};

class B : private A {
public:
  void bar();
};

void B::bar()
{
  foo();  // can access foo()
}

B b;
b.foo(); // forbidden
b.bar(); // allowed
</code>```

In general, you should use public inheritance because inheritance shouldn't be used for implementation re-use only (which is what private inheritance does).

Title: C++ subclassing access modifier?

Body:
I'm C++ newbie, and I have many years of experience about OO languages such as C/C#/Objective-C. Now, I'm learning C++.

I saw this C++ code:

    class World : public State
    {
    };

It seems class World inherits the class State publicly.
Public subclassing? It's hard to understand.

What's the concept of this feature?
And when is this useful or required?

Body:
The public/protected/private keyword before the name of the ancestor class indicates the desired visibility of members from the ancestor. With private inheritance, the descendant inherits only the implementation from the ancestor, but not the interface.

class A {
public:
  void foo();
};

class B : private A {
public:
  void bar();
};

void B::bar()
{
  foo();  // can access foo()
}

B b;
b.foo(); // forbidden
b.bar(); // allowed

In general, you should use public inheritance because inheritance shouldn't be used for implementation re-use only (which is what private inheritance does).


问:
Regular expression to match all digits of unknown length except the last 4 digits
There is a number with unknown length and the idea is to build a regular expression which matches all digits except last 4 digits.

I have tried a lot to achieve this but no luck yet.

Currently I have this regex: "^(\d*)\d{0}\d{0}\d{0}\d{0}.*$"

Input: 123456789089775

Expected output: XXXXXXXXXXX9775

which I am using as follows(and this doesn't work):

```<code>String accountNumber ="123456789089775";
String pattern = "^(\\d*)\\d{1}\\d{1}\\d{1}\\d{1}.*$";
String result = accountNumber.replaceAll(pattern, "X");
</code>```

Please suggest how I should approach this problem or give me the solution.
In this case my whole point is to negate the regex : "\d{4}$"

答:
still not allowed to comment as I don't have that "50 rep" yet but DDeMartini's answer would swallow prefixed non-number-accounts as "^(.*)" would match stuff like abcdef1234 as well - stick to your \d-syntax

```<code>"^(\\d+)(\\d{4}$)"
</code>```

seems to work fine and demands numbers (minimum length 6 chars). Tested it like

```<code>public class AccountNumberPadder {

    private static final Pattern LAST_FOUR_DIGITS = Pattern.compile("^(\\d+)(\\d{4})");

    public static void main(String[] args) {
        String[] accountNumbers = new String[] { "123456789089775", "999775", "1234567890897" };
        for (String accountNumber : accountNumbers) {
            Matcher m = LAST_FOUR_DIGITS.matcher(accountNumber);
            if (m.find()) {
                System.out.println(paddIt(accountNumber, m));
            } else {
                throw new RuntimeException(String.format("Whooaaa - don't work for %s", accountNumber));
            }
        }
    }

    public static String paddIt(String input, Matcher m) {
        StringBuilder b = new StringBuilder();
        for (int i = 0; i < m.group(1).length(); i++) {
            b.append("X");
        }
       return input.replace(m.group(1), b.toString());
    }
}
</code>```

Body:
There is a number with unknown length and the idea is to build a regular expression which matches all digits except last 4 digits.

I have tried a lot to achieve this but no luck yet.

Currently I have this regex: "^(\d*)\d{0}\d{0}\d{0}\d{0}.*$"

Input: 123456789089775

Expected output: XXXXXXXXXXX9775

which I am using as follows(and this doesn't work):

String accountNumber ="123456789089775";
String pattern = "^(\\d*)\\d{1}\\d{1}\\d{1}\\d{1}.*$";
String result = accountNumber.replaceAll(pattern, "X");

Please suggest how I should approach this problem or give me the solution.
In this case my whole point is to negate the regex : "\d{4}$"

Body:
still not allowed to comment as I don't have that "50 rep" yet but DDeMartini's answer would swallow prefixed non-number-accounts as "^(.*)" would match stuff like abcdef1234 as well - stick to your \d-syntax

"^(\\d+)(\\d{4}$)"

seems to work fine and demands numbers (minimum length 6 chars). Tested it like

public class AccountNumberPadder {

    private static final Pattern LAST_FOUR_DIGITS = Pattern.compile("^(\\d+)(\\d{4})");

    public static void main(String[] args) {
        String[] accountNumbers = new String[] { "123456789089775", "999775", "1234567890897" };
        for (String accountNumber : accountNumbers) {
            Matcher m = LAST_FOUR_DIGITS.matcher(accountNumber);
            if (m.find()) {
                System.out.println(paddIt(accountNumber, m));
            } else {
                throw new RuntimeException(String.format("Whooaaa - don't work for %s", accountNumber));
            }
        }
    }

    public static String paddIt(String input, Matcher m) {
        StringBuilder b = new StringBuilder();
        for (int i = 0; i < m.group(1).length(); i++) {
            b.append("X");
        }
       return input.replace(m.group(1), b.toString());
    }
}


问:
passing values from one function to another function in different file using javascript
UserList.cshtml

```<code>`<script>
    $(document).ready(function () {
                $(document).on('click', '.View', function () {
showDetail($(this), '/Admin/User/'); });
</script>`
</code>```

logical.js

```<code>`function showDetails(soid){
      var soid="1234";
      return soid;
}`
</code>```

User.cshtml

```<code>`<div class="InlineButton" style="width: 30px; margin-top: 4px;"
onclick="savePassword(soid)">Save</div>
<script>
function savePassword(soid){
console.log(soid);
}
</script>`
</code>```

So it's just bits and pieces from the whole code. I am in need of some help to pass the soid from showDetails() in logical.js to User.cshtml.

答:
When "UserList.cshtml" is being displayed and the user clicks on an element with the .View class, the anonymous function that calls showDetail($(this) will be invoked. showDetail() returns soid and you are not capturing that return value in "UserList.cshtml", so the first thing you need to do is modify "UserList.cshtml" to something like this:

```<code>$(document).ready(function () {
   $(document).on('click', '.View', function () {
   // Call showDetail() and store the return value in localStorage:
   localStorage.setItem("showDetailResults", showDetail($(this), '/Admin/User/'));
});
</code>```

Then, in any other page where you need that value (i.e. "User.cshtm"), you'd have the following line after you are sure that there is a value to get out of localStorage:

```<code>var storedValue = localStorage.getItem("showDetailResults");
</code>```

Body:
UserList.cshtml

``

logical.js

`function showDetails(soid){
      var soid="1234";
      return soid;
}`

User.cshtml

`
Save

`

So it's just bits and pieces from the whole code. I am in need of some help to pass the soid from showDetails() in logical.js to User.cshtml.

Body:
When "UserList.cshtml" is being displayed and the user clicks on an element with the .View class, the anonymous function that calls showDetail($(this) will be invoked. showDetail() returns soid and you are not capturing that return value in "UserList.cshtml", so the first thing you need to do is modify "UserList.cshtml" to something like this:

$(document).ready(function () {
   $(document).on('click', '.View', function () {
   // Call showDetail() and store the return value in localStorage:
   localStorage.setItem("showDetailResults", showDetail($(this), '/Admin/User/'));
});

Then, in any other page where you need that value (i.e. "User.cshtm"), you'd have the following line after you are sure that there is a value to get out of localStorage:

var storedValue = localStorage.getItem("showDetailResults");


问:
Pros and cons for MySQL snapshots vs SQL dumps
What are the advantages/disadvantages of using database snapshots vs. backing up SQL dumps (from mysqldump)?

I find SQL dump files easy to backup and restore. It seems to be much faster than using database snapshots as well so I am not sure what's the point of using snapshots when they take longer to use.

For additional context, I use MySQL 5.6 and more specifically AWS RDS Aurora (MySQL edition).

答:
Probably the most significant reason people use snapshots is that it can take days to import a large dump file.

Snapshots have several advantages:

It's faster to create a snapshot or restore a snapshot after your database gets very large. You might not yet have a database that is large enough to show this advantage.

You don't need an EC2 instance to run mysqldump on, nor do you need to provision storage for the dump file. The snapshot infrastructure takes care of both of those for you, as you invoke a snapshot in a "serverless" manner via GUI or API.

Snapshot lifecycle management is included in the AWS console. You can auto-expire snapshots, or save them to Glacier, etc. You can do the same with dump files, but you're kind of on your own for managing them.

Dump files have advantages too:

Dumps are in human-readable files. You can even use grep to search for data in a dump file.

Dumps are more-or-less portable between platforms and MySQL versions.

Dumps are a good way to transfer data between RDS and your on-prem data center (although there's a recent announcement that RDS now supports import using Percona XtraBackups).


问:
Changing java file
Can I change a java file, when I'm running it on JVM, using this file?

For example:
I run abc.java. In this program I've a textarea and I want to paste text from the text area into abc.java and save the changes. Is it possible?

答:
(new answer for updated question)

"In this program I've a textarea and I want to paste text from the text area into abc.java and save the changes."

This seems like a strange loop, self-modifying java code?

Then yes, the tools nrobey describes would be the way to go, though I agree with Ralph that it might be a bad idea.

Title: Changing java file


问:
How to Get Groups of Files from GetFiles()
I have to process files everyday.  The files are named like so:

```<code> fg1a.mmddyyyy
 fg1b.mmddyyyy
 fg1c.mmddyyyy

 fg2a.mmddyyyy
 fg2b.mmddyyyy
 fg2c.mmddyyyy
 fg2d.mmddyyyy
</code>```

If the entire file group is there for a particular date, I can process it.  If it isn't there, I should not process it.  I may have several partial file groups that run over several days.  So when I have fg1a.12062017, fg1b.12062017 and fg1c.12062017, I can process that group (fg1) only.

Here is my code so far.  It doesn't work because I can't figure out how to get only the full groups to add to the the processing file list.

```<code>        fileList = Directory.GetFiles(@"c:\temp\");

        string[] fileGroup1 = { "FG1A", "FG1B", "FG1C" }; // THIS IS A FULL GROUP
        string[] fileGroup2 = { "FG2A", "FG2B", "FG2C", "FG2D" };

        List<string> fileDates = new List<string>();
        List<string> procFileList;

        // get a list of file dates
        foreach (string fn in fileList)
        {
            string dateString = fn.Substring(fn.IndexOf('.'), 9);
            if (!fileDates.Contains(dateString))
            {
                fileDates.Add(dateString);
            }
        }

        bool allFiles = true;
        foreach (string fg in fileGroup1)
        {
            foreach (string fd in fileDates)
            {
                string finder = fg + fd;
                bool foundIt = false;
                foreach (string fn in fileList)
                {
                    if (fn.ToUpper().Contains(finder))
                    {
                        foundIt = true;
                    }

                }
                if (!foundIt)
                {
                    allFiles = false;
                }

                else
                {
                    foreach (string fn in fileList)
                    {
                        procFileList.Add(fn);
                    }

                }

            }

        }

        foreach (string fg in fileGroup2)
        {
            foreach (string fd in fileDates)
            {
                string finder = fg + fd;
                bool foundIt = false;
                foreach (string fn in fileList)
                {
                    if (fn.ToUpper().Contains(finder))
                    {
                        foundIt = true;
                    }

                }
                if (!foundIt)
                {
                    allFiles = false;
                }
                else
                {
                    foreach (string fn in fileList)
                    {
                        procFileList.Add(fn);
                    }

                }
            }

        }
</code>```

Any help or advice would be greatly appreciated.

答:
I think you could simplify your algorithm so you just have file groups as a prefix and a number of files to expect, fg1 is 3 files for a given date

I think your code to find the distinct dates present is a good idea, though you should use a hash set rather than a list, if you occasionally expect a large number of dates.. ("Valentine's Day?" - Ed)

Then you just need to work on the other loop that does the checking. An algorithm like this

```<code>//make a new Dictionary<string,int> for the filegroup prefixes and their counts3
//eg myDict["fg1"] = 3; myDict["fg2"] = 4;

//list the files in the directory, into an array of fileinfo objects
//see the DirectoryInfo.GetFiles method

//foreach string d in the list of dates
 //foreach string fgKey in myDict.Keys - the list of group prefixes

 //use a bit of Linq to get all the fileinfos with a
 //name starting with the group and ending with the date
 var grplist = myfileinfos.Where(fi => fi.Name.StartsWith(fg) && fi.Name.EndsWith(d));

 //if the grplist.Count == the filegroup count ( myDict[fgKey] )
 //then send every file in grplist for processing
 //remember that grplist is a collection of fileinfo objects,
 //if your processing method takes a string filename, use fileinfo.Fullname
</code>```

Putting your file groupings into one dictionary will make things a lot easier than having them as x separate arrays

I haven't written all the code for you, but I've comment sketched the algorithm, and I've put in some of the more awkward bits like the link, dictionary declaration and how to fill it.. have a go at fleshing it out with code, ask any questions in a comment on this post

Body:
I have to process files everyday.  The files are named like so:

 fg1a.mmddyyyy
 fg1b.mmddyyyy
 fg1c.mmddyyyy

 fg2a.mmddyyyy
 fg2b.mmddyyyy
 fg2c.mmddyyyy
 fg2d.mmddyyyy

If the entire file group is there for a particular date, I can process it.  If it isn't there, I should not process it.  I may have several partial file groups that run over several days.  So when I have fg1a.12062017, fg1b.12062017 and fg1c.12062017, I can process that group (fg1) only.

Here is my code so far.  It doesn't work because I can't figure out how to get only the full groups to add to the the processing file list.

        fileList = Directory.GetFiles(@"c:\temp\");

        string[] fileGroup1 = { "FG1A", "FG1B", "FG1C" }; // THIS IS A FULL GROUP
        string[] fileGroup2 = { "FG2A", "FG2B", "FG2C", "FG2D" };

        List<string> fileDates = new List<string>();
        List<string> procFileList;

        // get a list of file dates
        foreach (string fn in fileList)
        {
            string dateString = fn.Substring(fn.IndexOf('.'), 9);
            if (!fileDates.Contains(dateString))
            {
                fileDates.Add(dateString);
            }
        }

        bool allFiles = true;
        foreach (string fg in fileGroup1)
        {
            foreach (string fd in fileDates)
            {
                string finder = fg + fd;
                bool foundIt = false;
                foreach (string fn in fileList)
                {
                    if (fn.ToUpper().Contains(finder))
                    {
                        foundIt = true;
                    }

                }
                if (!foundIt)
                {
                    allFiles = false;
                }

                else
                {
                    foreach (string fn in fileList)
                    {
                        procFileList.Add(fn);
                    }

                }

            }

        }

        foreach (string fg in fileGroup2)
        {
            foreach (string fd in fileDates)
            {
                string finder = fg + fd;
                bool foundIt = false;
                foreach (string fn in fileList)
                {
                    if (fn.ToUpper().Contains(finder))
                    {
                        foundIt = true;
                    }

                }
                if (!foundIt)
                {
                    allFiles = false;
                }
                else
                {
                    foreach (string fn in fileList)
                    {
                        procFileList.Add(fn);
                    }

                }
            }

        }

Any help or advice would be greatly appreciated.

Body:
I think you could simplify your algorithm so you just have file groups as a prefix and a number of files to expect, fg1 is 3 files for a given date

I think your code to find the distinct dates present is a good idea, though you should use a hash set rather than a list, if you occasionally expect a large number of dates.. ("Valentine's Day?" - Ed)

Then you just need to work on the other loop that does the checking. An algorithm like this

//make a new Dictionary<string,int> for the filegroup prefixes and their counts3
//eg myDict["fg1"] = 3; myDict["fg2"] = 4;

//list the files in the directory, into an array of fileinfo objects
//see the DirectoryInfo.GetFiles method

//foreach string d in the list of dates
 //foreach string fgKey in myDict.Keys - the list of group prefixes

 //use a bit of Linq to get all the fileinfos with a
 //name starting with the group and ending with the date
 var grplist = myfileinfos.Where(fi => fi.Name.StartsWith(fg) && fi.Name.EndsWith(d));

 //if the grplist.Count == the filegroup count ( myDict[fgKey] )
 //then send every file in grplist for processing
 //remember that grplist is a collection of fileinfo objects,
 //if your processing method takes a string filename, use fileinfo.Fullname

Putting your file groupings into one dictionary will make things a lot easier than having them as x separate arrays

I haven't written all the code for you, but I've comment sketched the algorithm, and I've put in some of the more awkward bits like the link, dictionary declaration and how to fill it.. have a go at fleshing it out with code, ask any questions in a comment on this post


问:
Unable to get numbers from window.location.search
I am using the following code in my JS file:

```<code>var match = window.location.search.match(/(\d*)/);
this.room = (match) ? decodeURIComponent(match) : 0;
</code>```

And I am trying to just get the numbers from my URL. For example, in www.myurl.com/streams228, I just want to get the 228.

The issue I am getting is it is just returning %2, nothing else, or 0.

答:
After using the code above from everyone I did this

```<code>var match = window.location.pathname.match(/([\d]+)/g);
this.room = (match && match[0]) ? decodeURIComponent(match[0]) : 0;
</code>```

and it works perfectly.

Thanks

Body:
I am using the following code in my JS file:

var match = window.location.search.match(/(\d*)/);
this.room = (match) ? decodeURIComponent(match) : 0;

And I am trying to just get the numbers from my URL. For example, in www.myurl.com/streams228, I just want to get the 228.

The issue I am getting is it is just returning %2, nothing else, or 0.

Body:
After using the code above from everyone I did this

var match = window.location.pathname.match(/([\d]+)/g);
this.room = (match && match[0]) ? decodeURIComponent(match[0]) : 0;

and it works perfectly.

Thanks