问:
Regular Expression Log Parsing
I'm using regular expressions to parse logs. I was previously reading the File into a string array, and then iterating through the string array appending if I don't match the timestamp, otherwise I add the line I'm iterating on to a variable and continue the search. Once I get a complete log entry, I use another regular expression to parse it.

Scanning file

```<code>try {
    List<String> lines = Files.readAllLines(filepath);

    Pattern pattern = Pattern.compile("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2},\\d{3}");
    Matcher matcher;
    String currentEntry = "";
    for(String line : lines) {
        matcher = pattern.matcher(line);
        // If this is a new entry, then wrap up the previous one and start again
        if ( matcher.lookingAt() ) {
            // If the previous entry was not empty
            if(!StringUtils.trimWhitespace(currentEntry).isEmpty()) {
                entries.add(new LogEntry(currentEntry));
            }

            // Clear the current entry
            currentEntry = "";
        }

        if (!currentEntry.trim().isEmpty())
            currentEntry += "\n";
        currentEntry += line;
    }
    // At the end, if we have one leftover entry, add it
    if (!currentEntry.isEmpty()) {
        entries.add(new LogEntry(currentEntry));
    }
}catch (Exception ex){
    return null;
}
</code>```

Parsing entry

```<code>final private static String timestampRgx = "(?<timestamp>\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2},\\d{3})";
final private static String levelRgx = "(?<level>(?>INFO|ERROR|WARN|TRACE|DEBUG|FATAL))";
final private static String classRgx = "\\[(?<class>[^]]+)\\]";
final private static String threadRgx = "\\[(?<thread>[^]]+)\\]";
final private static String textRgx = "(?<text>.*)";
private static Pattern PatternFullLog = Pattern.compile(timestampRgx + " " + levelRgx + "\\s+" + classRgx + "-" + threadRgx + "\\s+" + textRgx + "$", Pattern.DOTALL);

public LogEntry(String logText) {

    try {
        Matcher matcher = PatternFullLog.matcher(logText);
        matcher.find();

        String dateStr = matcher.group("timestamp");
        timestamp = new DateLogLevel();
        timestamp.parseLogDate(dateStr);

        String levelStr = matcher.group("level");
        loglevel = LOG_LEVEL.valueOf(levelStr);
        String fullClassStr = matcher.group("class");

        String[] classNameArray = fullClassStr.split("\\.");
        framework = classNameArray[2];
        classname = classNameArray[classNameArray.length - 1];
        threadname = matcher.group("thread");
        logtext = matcher.group("text");
        notes = "";

    } catch (Exception ex) {
        throw ex;
    }
}
</code>```

What I want to figure out

What I really want to do is read the whole file as a single string, then use a single regex to parse this out line by line, using a single regular expression once. My plan was to use the same expression I use in the constructor, but when looking for the log text make it end at either EOF or the next log line, as such

```<code>final String timestampRgx = "(?<timestamp>\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2},\\d{3})";
final String levelRgx = "(?<level>(?>INFO|ERROR|WARN|TRACE|DEBUG|FATAL))";
final String classRgx = "\\[(?<class>[^]]+)\\]";
final String threadRgx = "\\[(?<thread>[^]]+)\\]";
final String textRgx = "(?<text>.*[^(\Z|\\d{4}\-\\d{2}\-\\d{2} \\d{2}:\\d{2}:\\d{2},\\d{3})"; // change to handle multiple lines
private static Pattern PatternFullLog = Pattern.compile(timestampRgx + " " + levelRgx + "\\s+" + classRgx + "-" + threadRgx + "\\s+" + textRgx + "$", Pattern.DOTALL);

try {
    // Read file into string
    String lines = readFile(filepath);

    Pattern pattern = Pattern.compile("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2},\\d{3}");
    Matcher matcher;

    matcher = pattern.matcher(line);
    while(matcher.find())
        String dateStr = matcher.group("timestamp");
        timestamp = new DateLogLevel();
        timestamp.parseLogDate(dateStr);

        String levelStr = matcher.group("level");
        loglevel = LOG_LEVEL.valueOf(levelStr);
        String fullClassStr = matcher.group("class");

        String[] classNameArray = fullClassStr.split("\\.");
        framework = classNameArray[2];
        classname = classNameArray[classNameArray.length - 1];
        threadname = matcher.group("thread");
        logtext = matcher.group("text");
        entries.add(
            new LogEntry(
                timestamp,
                loglevel,
                framework,
                threadname,
                logtext,
                ""/* Notes are empty when importing new file */));
        }
    }

}catch (Exception ex){
    return null;
}
</code>```

The problem is that I can't seem to get the last group (textRgx) to multiline match until either a timestamp or end of file. Does anyone have any thoughts?

Sample Log Entries

```<code>2017-03-14 22:43:14,405 FATAL [org.springframework.web.context.support.XmlWebApplicationContext]-[localhost-startStop-1] Refreshing Root WebApplicationContext: startup date [Tue Mar 14 22:43:14 UTC 2017]; root of context hierarchy
2017-03-14 22:43:14,476 INFO  [org.springframework.beans.factory.xml.XmlBeanDefinitionReader]-[localhost-startStop-1] Loading XML bean definitions from Serv
2017-03-14 22:43:14,476 INFO  [org.springframework.beans.factory.xml.XmlBeanDefinitionReader]-[localhost-startStop-1] Here is a multiline
log entry with another entry after
2017-03-14 22:43:14,476 INFO  [org.springframework.beans.factory.xml.XmlBeanDefinitionReader]-[localhost-startStop-1] Here is a multiline
log entry with no entries after
</code>```

答:
You need to define the patterns like

```<code>final static String timestampRgx = "(?<timestamp>\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2},\\d{3})";
final static String levelRgx = "(?<level>INFO|ERROR|WARN|TRACE|DEBUG|FATAL)";
final static String classRgx = "\\[(?<class>[^\\]]+)]";
final static String threadRgx = "\\[(?<thread>[^\\]]+)]";
final static String textRgx = "(?<text>.*?)(?=\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2},\\d{3}|\\Z)";
private static Pattern PatternFullLog = Pattern.compile(timestampRgx + " " + levelRgx + "\\s+" + classRgx + "-" + threadRgx + "\\s+" + textRgx, Pattern.DOTALL);
</code>```

Then, you may use that like

```<code>Matcher matcher = PatternFullLog.matcher(line);
</code>```

See the Java demo

Here is what the pattern looks like:

```<code>(?<timestamp>\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2},\d{3}) (?<level>INFO|ERROR|WARN|TRACE|DEBUG|FATAL)\s+\[(?<class>[^\]]+)]-\[(?<thread>[^\]]+)]\s+(?<text>.*?)(?=\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2},\d{3}|\Z)
</code>```

See the regex demo.

Some notes:

You had several issues with escaping symbols (] inside a character class must be escaped, and \- should have been replaced with -

The pattern to match text up to the datetime or end of string is (?<text>.*?)(?=\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2},\d{3}|\Z) where .*? matches any char, 0+ occurrences, reluctantly, up to the first occurrence of the timestamp pattern (\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2},\d{3}) or end of string (\Z).

Title: Regular Expression Log Parsing

Body:
I'm using regular expressions to parse logs. I was previously reading the File into a string array, and then iterating through the string array appending if I don't match the timestamp, otherwise I add the line I'm iterating on to a variable and continue the search. Once I get a complete log entry, I use another regular expression to parse it.

Scanning file

try {
    List<String> lines = Files.readAllLines(filepath);

    Pattern pattern = Pattern.compile("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2},\\d{3}");
    Matcher matcher;
    String currentEntry = "";
    for(String line : lines) {
        matcher = pattern.matcher(line);
        // If this is a new entry, then wrap up the previous one and start again
        if ( matcher.lookingAt() ) {
            // If the previous entry was not empty
            if(!StringUtils.trimWhitespace(currentEntry).isEmpty()) {
                entries.add(new LogEntry(currentEntry));
            }

            // Clear the current entry
            currentEntry = "";
        }

        if (!currentEntry.trim().isEmpty())
            currentEntry += "\n";
        currentEntry += line;
    }
    // At the end, if we have one leftover entry, add it
    if (!currentEntry.isEmpty()) {
        entries.add(new LogEntry(currentEntry));
    }
}catch (Exception ex){
    return null;
}

Parsing entry

final private static String timestampRgx = "(?<timestamp>\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2},\\d{3})";
final private static String levelRgx = "(?<level>(?>INFO|ERROR|WARN|TRACE|DEBUG|FATAL))";
final private static String classRgx = "\\[(?<class>[^]]+)\\]";
final private static String threadRgx = "\\[(?<thread>[^]]+)\\]";
final private static String textRgx = "(?<text>.*)";
private static Pattern PatternFullLog = Pattern.compile(timestampRgx + " " + levelRgx + "\\s+" + classRgx + "-" + threadRgx + "\\s+" + textRgx + "$", Pattern.DOTALL);

public LogEntry(String logText) {

    try {
        Matcher matcher = PatternFullLog.matcher(logText);
        matcher.find();

        String dateStr = matcher.group("timestamp");
        timestamp = new DateLogLevel();
        timestamp.parseLogDate(dateStr);

        String levelStr = matcher.group("level");
        loglevel = LOG_LEVEL.valueOf(levelStr);
        String fullClassStr = matcher.group("class");

        String[] classNameArray = fullClassStr.split("\\.");
        framework = classNameArray[2];
        classname = classNameArray[classNameArray.length - 1];
        threadname = matcher.group("thread");
        logtext = matcher.group("text");
        notes = "";

    } catch (Exception ex) {
        throw ex;
    }
}

What I want to figure out

What I really want to do is read the whole file as a single string, then use a single regex to parse this out line by line, using a single regular expression once. My plan was to use the same expression I use in the constructor, but when looking for the log text make it end at either EOF or the next log line, as such

final String timestampRgx = "(?<timestamp>\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2},\\d{3})";
final String levelRgx = "(?<level>(?>INFO|ERROR|WARN|TRACE|DEBUG|FATAL))";
final String classRgx = "\\[(?<class>[^]]+)\\]";
final String threadRgx = "\\[(?<thread>[^]]+)\\]";
final String textRgx = "(?<text>.*[^(\Z|\\d{4}\-\\d{2}\-\\d{2} \\d{2}:\\d{2}:\\d{2},\\d{3})"; // change to handle multiple lines
private static Pattern PatternFullLog = Pattern.compile(timestampRgx + " " + levelRgx + "\\s+" + classRgx + "-" + threadRgx + "\\s+" + textRgx + "$", Pattern.DOTALL);

try {
    // Read file into string
    String lines = readFile(filepath);

    Pattern pattern = Pattern.compile("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2},\\d{3}");
    Matcher matcher;

    matcher = pattern.matcher(line);
    while(matcher.find())
        String dateStr = matcher.group("timestamp");
        timestamp = new DateLogLevel();
        timestamp.parseLogDate(dateStr);

        String levelStr = matcher.group("level");
        loglevel = LOG_LEVEL.valueOf(levelStr);
        String fullClassStr = matcher.group("class");

        String[] classNameArray = fullClassStr.split("\\.");
        framework = classNameArray[2];
        classname = classNameArray[classNameArray.length - 1];
        threadname = matcher.group("thread");
        logtext = matcher.group("text");
        entries.add(
            new LogEntry(
                timestamp,
                loglevel,
                framework,
                threadname,
                logtext,
                ""/* Notes are empty when importing new file */));
        }
    }

}catch (Exception ex){
    return null;
}

The problem is that I can't seem to get the last group (textRgx) to multiline match until either a timestamp or end of file. Does anyone have any thoughts?

Sample Log Entries

2017-03-14 22:43:14,405 FATAL [org.springframework.web.context.support.XmlWebApplicationContext]-[localhost-startStop-1] Refreshing Root WebApplicationContext: startup date [Tue Mar 14 22:43:14 UTC 2017]; root of context hierarchy
2017-03-14 22:43:14,476 INFO  [org.springframework.beans.factory.xml.XmlBeanDefinitionReader]-[localhost-startStop-1] Loading XML bean definitions from Serv
2017-03-14 22:43:14,476 INFO  [org.springframework.beans.factory.xml.XmlBeanDefinitionReader]-[localhost-startStop-1] Here is a multiline
log entry with another entry after
2017-03-14 22:43:14,476 INFO  [org.springframework.beans.factory.xml.XmlBeanDefinitionReader]-[localhost-startStop-1] Here is a multiline
log entry with no entries after

Body:
You need to define the patterns like

final static String timestampRgx = "(?<timestamp>\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2},\\d{3})";
final static String levelRgx = "(?<level>INFO|ERROR|WARN|TRACE|DEBUG|FATAL)";
final static String classRgx = "\\[(?<class>[^\\]]+)]";
final static String threadRgx = "\\[(?<thread>[^\\]]+)]";
final static String textRgx = "(?<text>.*?)(?=\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2},\\d{3}|\\Z)";
private static Pattern PatternFullLog = Pattern.compile(timestampRgx + " " + levelRgx + "\\s+" + classRgx + "-" + threadRgx + "\\s+" + textRgx, Pattern.DOTALL);

Then, you may use that like

Matcher matcher = PatternFullLog.matcher(line);

See the Java demo

Here is what the pattern looks like:

(?<timestamp>\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2},\d{3}) (?<level>INFO|ERROR|WARN|TRACE|DEBUG|FATAL)\s+\[(?<class>[^\]]+)]-\[(?<thread>[^\]]+)]\s+(?<text>.*?)(?=\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2},\d{3}|\Z)

See the regex demo.

Some notes:

You had several issues with escaping symbols (] inside a character class must be escaped, and \- should have been replaced with -

The pattern to match text up to the datetime or end of string is (?<text>.*?)(?=\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2},\d{3}|\Z) where .*? matches any char, 0+ occurrences, reluctantly, up to the first occurrence of the timestamp pattern (\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2},\d{3}) or end of string (\Z).


来源: stackexchange

问:
Brace placement after init list in C++
For anyone who places braces thus:

```<code>void f() {
    stuff();
}
</code>```

How do you prefer to place braces after long initializer lists?

The same way?

```<code>Object::Object()
    : foo(1)
    , bar(2) {
    stuff();
}
</code>```

Or make an exception so you actually see where the init list ends?

```<code>Object::Object()
    : foo(1)
    , bar(2)
{
    stuff();
}
</code>```

Or leave a blank line?

```<code>Object::Object()
    : foo(1)
    , bar(2) {

    stuff();
}
</code>```

Or maybe make a weird hybrid?

```<code>Object::Object()
    : foo(1)
    , bar(2)
    {
    stuff();
}
</code>```

Or abuse indentation

```<code>Object::Object()
: foo(1)
, bar(2) {
    stuff();
}

Object::Object() : foo(1)
                            , bar(2) {
    stuff();
}
</code>```

In this small example all are pretty but crank a dozen initializers and a moderately long function body and this quickly changes.

答:
I like to have as much code on the screen as possible at once, so that my eyes can jump back and forth with as little scrolling as possible.  There is, of course, a limit.  Once I start needing to hunt too hard for something within a line, I have reached a point of diminishing returns.  If I'm not initializing more than 3 or 4 fields, I usually do something like this.

```<code>Object::Object() : foo(1), bar(2) {
    stuff();
}
</code>```

If I need to initialize lots of fields, it tends to look like this.

```<code>Object::Object() : foo(1),
                   bar(2),
                   baz(3) {
    stuff();
}
</code>```

OwnerDisplayName: Iraimbilanja

LastEditorDisplayName: Iraimbilanja

ContentLicense: CC BY-SA 2.5

Title: Brace placement after init list in C++

Body:
For anyone who places braces thus:

void f() {
    stuff();
}

How do you prefer to place braces after long initializer lists?

The same way?

Object::Object()
    : foo(1)
    , bar(2) {
    stuff();
}

Or make an exception so you actually see where the init list ends?

Object::Object()
    : foo(1)
    , bar(2)
{
    stuff();
}

Or leave a blank line?

Object::Object()
    : foo(1)
    , bar(2) {

    stuff();
}

Or maybe make a weird hybrid?

Object::Object()
    : foo(1)
    , bar(2)
    {
    stuff();
}

Or abuse indentation

Object::Object()
: foo(1)
, bar(2) {
    stuff();
}

Object::Object() : foo(1)
                            , bar(2) {
    stuff();
}

In this small example all are pretty but crank a dozen initializers and a moderately long function body and this quickly changes.

Body:
I like to have as much code on the screen as possible at once, so that my eyes can jump back and forth with as little scrolling as possible.  There is, of course, a limit.  Once I start needing to hunt too hard for something within a line, I have reached a point of diminishing returns.  If I'm not initializing more than 3 or 4 fields, I usually do something like this.

Object::Object() : foo(1), bar(2) {
    stuff();
}

If I need to initialize lots of fields, it tends to look like this.

Object::Object() : foo(1),
                   bar(2),
                   baz(3) {
    stuff();
}

OwnerDisplayName: Glomek

ContentLicense: CC BY-SA 4.0

LastEditorDisplayName: Glomek


问:
I can't get my arraylist to print on separate lines...what am I doing wrong? JAVA
Hey all I would like my code to print like this:

John Smith, Math, 4.0, True

Jessica Snow, Communications, 4.0, false

Chris Christopherson, Science, 3.2, True

Currently it prints all on one line like this:
John Smith, Math, 4.0, True, Jessica Snow, Communications, 4.0, false , Chris Christopherson, Science, 3.2, True

How can I get it to print on different lines?

```<code>    public static int addStudent(ArrayList students){
    Scanner inputStudents = new Scanner(System.in);

    System.out.println("Please Enter first name");
    String fname = inputStudents.nextLine();
    students.add(fname);

    System.out.println("Please Enter Last name");
    String lname = inputStudents.nextLine();
    students.add(lname);

    System.out.println("Please enter department of student's major");
    String department = inputStudents.nextLine();
    students.add(department);

    System.out.println("Please Enter GPA");
    Double gpa = inputStudents.nextDouble();
    students.add(gpa);

    System.out.println("Is the student involved in extracurriculars")
   (true/false):");
    boolean extras = inputStudents.nextBoolean();
    students.add(extras);

    return 0;
</code>```

Sorry I'm an idiot here is my print code:

```<code>}
public void print(){
    System.out.println(this.fname + " " +this.lname + " " + this.department+ "
" + this.gpa + " "+ this.extras);
   }
}
</code>```

答:
Iterate the ArrayList via for loop after you've collected the students in your function return. In this case, here is a sample loop:

```<code>students.forEach((name) -> {
System.out.println(name);
});
</code>```

Also, make the function null since you don't necessarily return anything other than 0 unless you're planning to do something.

EDIT: fixed.

ContentLicense: CC BY-SA 3.0

Body:
Hey all I would like my code to print like this:

John Smith, Math, 4.0, True

Jessica Snow, Communications, 4.0, false

Chris Christopherson, Science, 3.2, True

Currently it prints all on one line like this:
John Smith, Math, 4.0, True, Jessica Snow, Communications, 4.0, false , Chris Christopherson, Science, 3.2, True

How can I get it to print on different lines?

    public static int addStudent(ArrayList students){
    Scanner inputStudents = new Scanner(System.in);

    System.out.println("Please Enter first name");
    String fname = inputStudents.nextLine();
    students.add(fname);

    System.out.println("Please Enter Last name");
    String lname = inputStudents.nextLine();
    students.add(lname);

    System.out.println("Please enter department of student's major");
    String department = inputStudents.nextLine();
    students.add(department);

    System.out.println("Please Enter GPA");
    Double gpa = inputStudents.nextDouble();
    students.add(gpa);

    System.out.println("Is the student involved in extracurriculars")
   (true/false):");
    boolean extras = inputStudents.nextBoolean();
    students.add(extras);

    return 0;

Sorry I'm an idiot here is my print code:

}
public void print(){
    System.out.println(this.fname + " " +this.lname + " " + this.department+ "
" + this.gpa + " "+ this.extras);
   }
}

Body:
Iterate the ArrayList via for loop after you've collected the students in your function return. In this case, here is a sample loop:

students.forEach((name) -> {
System.out.println(name);
});

Also, make the function null since you don't necessarily return anything other than 0 unless you're planning to do something.

EDIT: fixed.


问:
IntelliJ IDEA / WebStorm: how to make all files unselected by default in the commit dialog?
When I open the Commit Changes Dialog (Ctrl + K) in WebStorm, it selects all changed/added/removed files. I'd like to avoid accidentally committing files. And often I uncheck all files and then check those files that I want to commit.

Is there a way to disable auto-selection of all files by default in the Commit Dialog (I didn't find such option in the settings)?

答:
Since you said in the comments that you really wanted to not select one particular file by default, changelog.txt, you can tell Git to ignore changes to that file, and then hopefully WebStorm will not detect the changes either.

There are two similar features for ignoring changes to a file in Git: --assume-unchanged and --skip-worktree. See Git - Difference Between 'assume-unchanged' and 'skip-worktree' for the difference. You probably want --skip-worktree.

You can use it in your case like this:

```<code>git update-index --skip-worktree changelog.txt
</code>```

Now git status won't include your change to changelog.txt in its list.

When you're finally ready to actually commit the change, run

```<code>git update-index --no-skip-worktree changelog.txt
</code>```

The comments of http://gitready.com/intermediate/2009/02/18/temporarily-ignoring-files.html suggest some aliases to make the above commands easier to run, although that article only discusses --assume-unchanged, not --skip-worktree.

Body:
Since you said in the comments that you really wanted to not select one particular file by default, changelog.txt, you can tell Git to ignore changes to that file, and then hopefully WebStorm will not detect the changes either.

There are two similar features for ignoring changes to a file in Git: --assume-unchanged and --skip-worktree. See Git - Difference Between 'assume-unchanged' and 'skip-worktree' for the difference. You probably want --skip-worktree.

You can use it in your case like this:

git update-index --skip-worktree changelog.txt

Now git status won't include your change to changelog.txt in its list.

When you're finally ready to actually commit the change, run

git update-index --no-skip-worktree changelog.txt

The comments of http://gitready.com/intermediate/2009/02/18/temporarily-ignoring-files.html suggest some aliases to make the above commands easier to run, although that article only discusses --assume-unchanged, not --skip-worktree.


问:
Xcode Not Immediately Recognizing New Classes (iOS)
I've been working with Xcode for about 5 months now and I just recently ran across a problem when I add a new class. If I add a new class, say for example "CustomCell" and I try to import '#import CustomCell.h' into a different .m file it will give me an error saying 'CustomCell.h file not found' even though it's right there on the list. I've had no problem with this in the past and I know what I'm doing when it comes to importing (at least I haven't changed the way I previously went about it when it worked).

I've had this problem more than once recently and sometimes if I just close out XCode and restart it it will recognize the class. Has anyone else had this problem? Is there a quick way to just refresh the project to see if Xcode can recognize the new class?

答:
Multiple Targets: Make sure your file belongs to the necessary targets!

For a new file, make sure the appropriate targets are checked.

For an existing file, check the file inspector to verify target membership.


问:
Reducing the time complexity of the code below
The following code is a solution to a problem statement from a contest.
The time constraint given was 1s. The code worked correctly for 5/7 test cases. For the rest cases, the time limit was exceeded.
How can the time complexity for the code below be reduced?

Edit:
The problem statement is defined as return the value of number n or sum of n/2,n/3,n/4 whichever is maximum.
For example, if input is 24
it can be reduced or exchanged for
12+8+6=26
Further, 12 can be reduced to 6+4+3=13.
8 and 6 should not be reduced as it may decrease the value.
So final answer is 13+8+6=27

```<code>#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#define lli long long int
using namespace std;

lli exchange(lli n){
    if(n<12)
        return n;

    else{

        lli sum=0;
        sum+=max(n/2,exchange(n/2));
        sum+=max(n/3,exchange(n/3));
        sum+=max(n/4,exchange(n/4));
        return sum;
    }
}

int main() {
    lli t;
    cin>>t;
    while(t--){
        lli n;
        cin>>n;
        lli ans;
        ans=max(n,exchange(n));
        cout<<ans<<endl;
    }
    return 0;
}
</code>```

答:
One of the standard trade-offs in any algorithm is time vs. space; the more memory or disk space you have, the more time you can save, or vice versa.  In this case, you need to run within a specific time, but you appear to be allowed to use the full memory of the machine.  Therefore, noting that this particular algorithm frequently requests values that it has already calculated, it should be worth saving them all for quick lookup.

Indeed, Python, not often regarded as particularly fast, can calculate 10295 in about a second, though 10300 runs into a maximum recursion depth error if run with an empty result cache:

```<code>exchanged = {}
def exchange(n):
    if n in exchanged:
        value = exchanged[n]
    elif n < 12:
        exchanged[n] = value = n
    else:
        exchanged[n] = value = exchange(n//2) + exchange(n//3) + exchange(n//4)
    return value
exchange(10**295)
</code>```

For C++, a static std::map<lli, lli> should work for in place of the exchanged dict.  Don't try using an array, though, because you don't need nearly as many values as the largest one calculated; 10295, for example, uses less than 300,000 results.

And yes, the max part can be omitted, because it's handled by the n < 12 check.  We can prove this by noting that it would only be necessary if (n-1)/2 + (n-2)/3 + (n-3)/4 < n (accounting for the way integer division throws away the remainder), throwing out all cases above 23; the remaining cases are easy to check by hand, and the largest exception happens to be 11.  But that's a minor optimization compared with changing your algorithm from O(n*log(n)) to O(log(n)).

Body:
The following code is a solution to a problem statement from a contest.
The time constraint given was 1s. The code worked correctly for 5/7 test cases. For the rest cases, the time limit was exceeded.
How can the time complexity for the code below be reduced?

Edit:
The problem statement is defined as return the value of number n or sum of n/2,n/3,n/4 whichever is maximum.
For example, if input is 24
it can be reduced or exchanged for
12+8+6=26
Further, 12 can be reduced to 6+4+3=13.
8 and 6 should not be reduced as it may decrease the value.
So final answer is 13+8+6=27

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#define lli long long int
using namespace std;

lli exchange(lli n){
    if(n<12)
        return n;

    else{

        lli sum=0;
        sum+=max(n/2,exchange(n/2));
        sum+=max(n/3,exchange(n/3));
        sum+=max(n/4,exchange(n/4));
        return sum;
    }
}

int main() {
    lli t;
    cin>>t;
    while(t--){
        lli n;
        cin>>n;
        lli ans;
        ans=max(n,exchange(n));
        cout<<ans<<endl;
    }
    return 0;
}

Body:
One of the standard trade-offs in any algorithm is time vs. space; the more memory or disk space you have, the more time you can save, or vice versa.  In this case, you need to run within a specific time, but you appear to be allowed to use the full memory of the machine.  Therefore, noting that this particular algorithm frequently requests values that it has already calculated, it should be worth saving them all for quick lookup.

Indeed, Python, not often regarded as particularly fast, can calculate 10295 in about a second, though 10300 runs into a maximum recursion depth error if run with an empty result cache:

exchanged = {}
def exchange(n):
    if n in exchanged:
        value = exchanged[n]
    elif n < 12:
        exchanged[n] = value = n
    else:
        exchanged[n] = value = exchange(n//2) + exchange(n//3) + exchange(n//4)
    return value
exchange(10**295)

For C++, a static std::map<lli, lli> should work for in place of the exchanged dict.  Don't try using an array, though, because you don't need nearly as many values as the largest one calculated; 10295, for example, uses less than 300,000 results.

And yes, the max part can be omitted, because it's handled by the n < 12 check.  We can prove this by noting that it would only be necessary if (n-1)/2 + (n-2)/3 + (n-3)/4 < n (accounting for the way integer division throws away the remainder), throwing out all cases above 23; the remaining cases are easy to check by hand, and the largest exception happens to be 11.  But that's a minor optimization compared with changing your algorithm from O(n*log(n)) to O(log(n)).


问:
remove items when looping/iterating a list
I see some discussion about how to handle the task of "delete items when looping a list", e.g., this post.

An answer in this link says:

You are not permitted to remove elements from the list while iterating
  over it using a for loop.

It seems I can do it without problem:

```<code>words = ['DROP', 'TABLE', 'table_name']

for ii, word in enumerate(words):

    print(ii)
    print(word)

    if words[ii] == 'DROP' and words[ii + 1] == 'TABLE':
        words[ii] = 'DROP TABLE'
        del words[ii + 1]

print(words)
</code>```

yields:

```<code>0
DROP
1
table_name
['DROP TABLE', 'table_name']
</code>```

Has python changed the restriction and we can remove items when looping now?
I'm using python 3.7.

答:
There is (and also was) absolutely nothing stopping you from modifying the list you are iterating through (dictionaries can't be modified in python3 though - results in an error), but the results can be... surprising. Even your question is based on such surprising result - you don't have an error, because you look ahead and you "merge" two results into one. If you would ONLY remove every DROPyou would end up missing some entries:

```<code>words = ['DROP', 'one_drop_will_be_missed', 'DROP', 'DROP' ]

for ii, word in enumerate(words):
    print(ii)
    print(word)
    if words[ii] == 'DROP':
        del words[ii]

print(words)
</code>```

Results in a:

```<code>0
DROP
1
DROP
['one_drop_will_be_missed', 'DROP']
</code>```

What would happen if somehow DROP would be the last word in your list?

Body:
I see some discussion about how to handle the task of "delete items when looping a list", e.g., this post.

An answer in this link says:

You are not permitted to remove elements from the list while iterating
  over it using a for loop.

It seems I can do it without problem:

words = ['DROP', 'TABLE', 'table_name']

for ii, word in enumerate(words):

    print(ii)
    print(word)

    if words[ii] == 'DROP' and words[ii + 1] == 'TABLE':
        words[ii] = 'DROP TABLE'
        del words[ii + 1]

print(words)

yields:

0
DROP
1
table_name
['DROP TABLE', 'table_name']

Has python changed the restriction and we can remove items when looping now?
I'm using python 3.7.

Body:
There is (and also was) absolutely nothing stopping you from modifying the list you are iterating through (dictionaries can't be modified in python3 though - results in an error), but the results can be... surprising. Even your question is based on such surprising result - you don't have an error, because you look ahead and you "merge" two results into one. If you would ONLY remove every DROPyou would end up missing some entries:

words = ['DROP', 'one_drop_will_be_missed', 'DROP', 'DROP' ]

for ii, word in enumerate(words):
    print(ii)
    print(word)
    if words[ii] == 'DROP':
        del words[ii]

print(words)

Results in a:

0
DROP
1
DROP
['one_drop_will_be_missed', 'DROP']

What would happen if somehow DROP would be the last word in your list?


问:
Pcregrep include file extension bug
I'm using pcregrep to search for a multiline pattern, and I only want pcregrep to search through files with specific file extensions, i.e.

pcregrep -Mrl --include=*.sv -e '<my_multi-line_pattern>' /path/to/search

However, this throws an error: pcregrep: Error in 'include' regex at offset 0: nothing to repeat.

I've tried escaping & double-escaping the * to no avail. This syntax seems to work just fine for grep

grep -rl --include=*.sv '<my_single-line_pattern>' /path/to/search

Any help or hints greatly appreciated.

EDIT: Example multi-line pattern: '(?s)^\salu.*\.opa_i('
should match

```<code>alu u_alu(
     ...
   .opa_i(opa),
   .opb_i(opb),
     ...
)
</code>```

答:
Here's what pcregrep's docs say about --include (emphasis mine):

--include=pattern If any --include patterns are specified, the only files that are processed are those that match one of the patterns (and do not match an --exclude pattern). This option does not affect directories, but it applies to all files, whether listed on the command line, obtained from --file-list, or by scanning a directory. The pattern is a PCRE regular expression, and is matched against the final component of the file name, not the entire path. The -F, -w, and -x options do not apply to this pattern. The option may be given any number of times. If a file name matches both an --include and an --exclude pattern, it is excluded. There is no short form for this option.

And a * at the start of a regex is of course not valid.

Now you can make sense of the error message :)

Solution: --include='.*\.sv$' or just --include='\.sv$'

Title: Pcregrep include file extension bug

Body:
I'm using pcregrep to search for a multiline pattern, and I only want pcregrep to search through files with specific file extensions, i.e.

pcregrep -Mrl --include=*.sv -e '<my_multi-line_pattern>' /path/to/search

However, this throws an error: pcregrep: Error in 'include' regex at offset 0: nothing to repeat.

I've tried escaping & double-escaping the * to no avail. This syntax seems to work just fine for grep

grep -rl --include=*.sv '<my_single-line_pattern>' /path/to/search

Any help or hints greatly appreciated.

EDIT: Example multi-line pattern: '(?s)^\salu.*\.opa_i('
should match

alu u_alu(
     ...
   .opa_i(opa),
   .opb_i(opb),
     ...
)


问:
The right way to compare two variable php
Im trying to compare 2 variables which contain these query results

Query :

```<code>$cekFitur = mysqli_num_rows(mysqli_query($db,"SELECT * FROM selected_feature"));

$totalTerm = mysqli_num_rows(mysqli_query($db,"SELECT * FROM token_preprocessing_latih"));

if (($cekFitur && $totalTerm) == 0) {
    do something
}else{
    do something
}
</code>```

Is this the correct way to check those 2 variables together ?

Please tell me if I have to change something in my code.
Thank you.

答:
No. ($cekFitur && $totalTerm) == 0 is comparing like

($var1 == true && $var2 == true) == 0 = true OR false == 0 = 1 OR 0 == 0

This is not what you want. You've to compare them individually.

```<code>if ($cekFitur == 0 && $totalTerm == 0) {
</code>```

Body:
Im trying to compare 2 variables which contain these query results

Query :

$cekFitur = mysqli_num_rows(mysqli_query($db,"SELECT * FROM selected_feature"));

$totalTerm = mysqli_num_rows(mysqli_query($db,"SELECT * FROM token_preprocessing_latih"));

if (($cekFitur && $totalTerm) == 0) {
    do something
}else{
    do something
}

Is this the correct way to check those 2 variables together ?

Please tell me if I have to change something in my code.
Thank you.

Body:
No. ($cekFitur && $totalTerm) == 0 is comparing like

($var1 == true && $var2 == true) == 0 = true OR false == 0 = 1 OR 0 == 0

This is not what you want. You've to compare them individually.

if ($cekFitur == 0 && $totalTerm == 0) {


问:
react-router v4: prevent transition with custom hook instead of Prompt
In react-router v3, I've been using router.setRouteLeaveHook to check if a form has unsaved changes, and if so return false to prevent the transition.  Then I would display a custom bootstrap modal dialog with 3 buttons: Save Changes, Discard Changes, and Stay Here.

I can't use react-router v4's Prompt component to do this because it's not possible to customize the buttons shown in a browser confirm dialog.  It seems like they got rid of any way to cancel the transition in favor of only allowing you to ask the user to approve the transition in a browser confirm dialog.

I tried looking in the code for Prompt but it just passes the dialog message to history, so that doesn't give me any idea how to set up a v3-style route leave hook.

Is it even possible anymore or did the react-router devs intentionally decide to remove this capability this for some reason?

答:
I don't think this is possible. react-router-v4 uses a package called history that in turns uses the HTML5 history api. The history api only notifies you when you hit the back button (onpopstate), If you think about it this makes lots of sense, since you would not want to give a website the power of not letting you move between pages.

The best you can do is the window onbeforeunload event, that creates a prompt for you asking confirmation from the user, but this is exactly what react-router exposes for you to use.

You might get some of the functionality you want by monkey-patching react-router's internal history object, and that way you can add your own behaviour. But there is a caveat, this is only going to work when you react-router's <Link /> component and friends, so you will not be able to intercept refreshes and other things you may want.

If you want to go that route, let me know I can give you some insight or code examples about how might that work and I will update my answer.


问:
Using delphi code in java
I have an old yet very complicated algorithm written is Delphi that i want to use as a service for a java project.

My plan is to build a site that can serve the algorithms benefits through a web interface without re-writing the code due to it's complicity.

I have seen many options for doing the exact opposite (that's make sense) but couldn't find what I was looking for.

答: To use your Delphi code directly in a Java process, you would have to put the Delphi code into a DLL and then use JNI/JNA or ActiveX/COM to access that DLL in your Java code.  Otherwise, move the Delphi code to a separate process and have your Java process communicate with it as needed.</p>

Title: Using delphi code in java


问:
How to change this jQuery widget (written for jQueryUI 1.7) so that it works with jQueryUI 1.8
This jQuery plugin, which lets users draw rectangles in a div, works with jQueryUI 1.7.2.

I need to get it working with jQueryUI 1.8.4. From reading the widget upgrade guide, I can't work out what needs to change. I tried renaming _init() to _create(), but that didn't do anything. What else do I need to change to get it working? Thanks for reading.

答:
The $.widget signature changed to do the extend internally, so change this:

```<code>$.widget("ui.boxer", $.extend({}, $.ui.mouse, {
</code>```

To this:

```<code>$.widget("ui.boxer", $.ui.mouse, {
</code>```

And at the bottom, remove the extra ) as well, changing })); to });

Also, to get the default options, it's best to move them right inside, like this:

```<code>$.widget("ui.boxer", $.ui.mouse, {
  options: {
    appendTo: 'body',
    distance: 0
  },
  ///rest of widget, unchanged...
});
</code>```

Here's a sample of the updated version with only the changes above, working.

Body:
The $.widget signature changed to do the extend internally, so change this:

$.widget("ui.boxer", $.extend({}, $.ui.mouse, {

To this:

$.widget("ui.boxer", $.ui.mouse, {

And at the bottom, remove the extra ) as well, changing })); to });

Also, to get the default options, it's best to move them right inside, like this:

$.widget("ui.boxer", $.ui.mouse, {
  options: {
    appendTo: 'body',
    distance: 0
  },
  ///rest of widget, unchanged...
});

Here's a sample of the updated version with only the changes above, working.


问:
'java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException:'
Problem 1:
I am importing the project on maven in eclipse on  my System and i found the problem while running with the port number .

Solution 1:
I changed the port number from 8080 because it was currently used by oracle10g.
Now while performing the run operation-
'tomcat7:run -Dmaven.tomcat.port=8083'

Problem 2:
NEXT an Exception occured ...

I got this Exception followed by many more exceptions and couldn't find the exact cause of this .
AS This code was runnig fine on another System.

EXCEPTION

```<code>SEVERE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Tomcat].StandardHost[localhost].StandardContext[/NSBTPortal1]]
    at java.util.concurrent.FutureTask.report(Unknown Source)
    at java.util.concurrent.FutureTask.get(Unknown Source)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1123)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:800)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Tomcat].StandardHost[localhost].StandardContext[/NSBTPortal1]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    ... 6 more
Caused by: java.lang.ClassCastException: org.springframework.web.SpringServletContainerInitializer cannot be cast to javax.servlet.ServletContainerInitializer
    at org.apache.catalina.startup.ContextConfig.getServletContainerInitializer(ContextConfig.java:1670)
    at org.apache.catalina.startup.ContextConfig.getServletContainerInitializers(ContextConfig.java:1652)
    at org.apache.catalina.startup.ContextConfig.processServletContainerInitializers(ContextConfig.java:1562)
    at org.apache.catalina.startup.ContextConfig.webConfig(ContextConfig.java:1270)
    at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:878)
    at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:376)
    at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119)
    at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5322)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 6 more

Mar 30, 2017 10:26:42 PM org.apache.catalina.core.ContainerBase startInternal
SEVERE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Tomcat].StandardHost[localhost]]
    at java.util.concurrent.FutureTask.report(Unknown Source)
    at java.util.concurrent.FutureTask.get(Unknown Source)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1123)
    at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:302)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.StandardService.startInternal(StandardService.java:443)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:732)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.startup.Tomcat.start(Tomcat.java:341)
    at org.apache.tomcat.maven.plugin.tomcat7.run.AbstractRunMojo.startContainer(AbstractRunMojo.java:1238)
    at org.apache.tomcat.maven.plugin.tomcat7.run.AbstractRunMojo.execute(AbstractRunMojo.java:592)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:134)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:208)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:116)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:80)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:51)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:307)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:193)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:106)
    at org.apache.maven.cli.MavenCli.execute(MavenCli.java:862)
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:286)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:197)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Tomcat].StandardHost[localhost]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: org.apache.catalina.LifecycleException: A child container failed during start
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1131)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:800)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 6 more

[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 17.003 s
[INFO] Finished at: 2017-03-30T22:26:42+05:30
[INFO] Final Memory: 12M/80M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.tomcat.maven:tomcat7-maven-plugin:2.2:run (default-cli) on project NSBTPortal1: Could not start Tomcat: Failed to start component [StandardServer[-1]]: Failed to start component [StandardService[Tomcat]]: Failed to start component [StandardEngine[Tomcat]]: A child container failed during start -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
</code>```

答: This has something to do with your source code and not the deployment. In order to handle concurrent execution exception please take a look here how to handle java.util.concurrent.ExecutionException exception</p>

Body:
Problem 1:
I am importing the project on maven in eclipse on  my System and i found the problem while running with the port number .

Solution 1:
I changed the port number from 8080 because it was currently used by oracle10g.
Now while performing the run operation-
'tomcat7:run -Dmaven.tomcat.port=8083'

Problem 2:
NEXT an Exception occured ...

I got this Exception followed by many more exceptions and couldn't find the exact cause of this .
AS This code was runnig fine on another System.

EXCEPTION

SEVERE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Tomcat].StandardHost[localhost].StandardContext[/NSBTPortal1]]
    at java.util.concurrent.FutureTask.report(Unknown Source)
    at java.util.concurrent.FutureTask.get(Unknown Source)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1123)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:800)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Tomcat].StandardHost[localhost].StandardContext[/NSBTPortal1]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    ... 6 more
Caused by: java.lang.ClassCastException: org.springframework.web.SpringServletContainerInitializer cannot be cast to javax.servlet.ServletContainerInitializer
    at org.apache.catalina.startup.ContextConfig.getServletContainerInitializer(ContextConfig.java:1670)
    at org.apache.catalina.startup.ContextConfig.getServletContainerInitializers(ContextConfig.java:1652)
    at org.apache.catalina.startup.ContextConfig.processServletContainerInitializers(ContextConfig.java:1562)
    at org.apache.catalina.startup.ContextConfig.webConfig(ContextConfig.java:1270)
    at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:878)
    at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:376)
    at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119)
    at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5322)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 6 more

Mar 30, 2017 10:26:42 PM org.apache.catalina.core.ContainerBase startInternal
SEVERE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Tomcat].StandardHost[localhost]]
    at java.util.concurrent.FutureTask.report(Unknown Source)
    at java.util.concurrent.FutureTask.get(Unknown Source)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1123)
    at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:302)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.StandardService.startInternal(StandardService.java:443)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:732)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.startup.Tomcat.start(Tomcat.java:341)
    at org.apache.tomcat.maven.plugin.tomcat7.run.AbstractRunMojo.startContainer(AbstractRunMojo.java:1238)
    at org.apache.tomcat.maven.plugin.tomcat7.run.AbstractRunMojo.execute(AbstractRunMojo.java:592)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:134)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:208)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:116)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:80)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:51)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:307)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:193)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:106)
    at org.apache.maven.cli.MavenCli.execute(MavenCli.java:862)
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:286)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:197)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Tomcat].StandardHost[localhost]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: org.apache.catalina.LifecycleException: A child container failed during start
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1131)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:800)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 6 more

[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 17.003 s
[INFO] Finished at: 2017-03-30T22:26:42+05:30
[INFO] Final Memory: 12M/80M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.tomcat.maven:tomcat7-maven-plugin:2.2:run (default-cli) on project NSBTPortal1: Could not start Tomcat: Failed to start component [StandardServer[-1]]: Failed to start component [StandardService[Tomcat]]: Failed to start component [StandardEngine[Tomcat]]: A child container failed during start -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException


问:
mobile version of a website click and hide
I have a problem with some JavaScript: for the computer version of a website, when I hover over a button, some text appears, and when I click anywhere else on the site, the text hides.

I don't know how to construct a page for the mobile version of the same website, on which when I click on a button, text shall appear and when I click anywhere else I want the text to hide.
I've tried:

```<code>if(jQuery.browser.mobile)  {
    $(".button").on("click", function()  {
        $(".text").show();
    });
    //this section doesn't work
    $("body").on("click", function()  {
        $(".text").hide();
    });
}
else  {
    //desktop code here, irrelevant
}
</code>```

答:
There is a conflict in your code because class is part of body. So when you click class both events are called.

The information in this post will help you solve your problem:

How do I detect a click outside an element?

By using event.stopPropagation(); in your class event, you should be able to differentiate both event.

Note that this solution may raise other problems if your class element or any element contained by it handle other events. In this case, you might want to try other solution from the post I quoted.

I don't think that the fact that that your working on a mobile version is relevant.

Body:
I have a problem with some JavaScript: for the computer version of a website, when I hover over a button, some text appears, and when I click anywhere else on the site, the text hides.

I don't know how to construct a page for the mobile version of the same website, on which when I click on a button, text shall appear and when I click anywhere else I want the text to hide.
I've tried:

if(jQuery.browser.mobile)  {
    $(".button").on("click", function()  {
        $(".text").show();
    });
    //this section doesn't work
    $("body").on("click", function()  {
        $(".text").hide();
    });
}
else  {
    //desktop code here, irrelevant
}


问:
PHP Warning: PHP Startup: Unable to load dynamic library 'C:\xampp\php\ext\php_oci8.dll' - The specified module could not be found
I want to use php oci8 function , but I got this error

```<code>PHP Warning: PHP Startup: Unable to load dynamic library 'C:\xampp\php\ext\php_oci8.dll' - The specified module could not be found. (C:\xampp\apache\bin\httpd.exe -d C:/xampp/apache)
</code>```

I have follow all this step

How to enable Oracle Connection to PHP on XAMPP

Install XAMPP 1.7.3 on your Windows. (Please remove the old version of XAMPP and please delete C:\xampp BEFORE installing the new version of XAMPP).

Extract InstantClient to C:\instantclient_11_2 folder.

Open system setting at Start Menu > My Computer(right click on the icon) > Select Properties > Advanced Tabs > Environment Variables.

Add to ‘System Variables’ by clicking ‘New’ button and insert the following values:
a.  Variable Name : PATH
b.  Variable Value  : c:\instantclient_11_2

Click OK to accept new modification.

Open C:\xampp\php\php.ini by using notepad.

Find string oci8 and remove the ; symbol at the beginning of the string line.

Save and Exit.

Restart you laptop/pc to accept new modification on xampp.

I setup at Window Server 2008 R2 64bit.

Can anyone help?

答: Have you ever try to copy the files orannzsbb11.dll , oci.dll and oraociei11.dll to c:\windows\system32 ? try it. It worked for me :)</p>

Body:
I want to use php oci8 function , but I got this error

PHP Warning: PHP Startup: Unable to load dynamic library 'C:\xampp\php\ext\php_oci8.dll' - The specified module could not be found. (C:\xampp\apache\bin\httpd.exe -d C:/xampp/apache)

I have follow all this step

How to enable Oracle Connection to PHP on XAMPP

Install XAMPP 1.7.3 on your Windows. (Please remove the old version of XAMPP and please delete C:\xampp BEFORE installing the new version of XAMPP).

Extract InstantClient to C:\instantclient_11_2 folder.

Open system setting at Start Menu > My Computer(right click on the icon) > Select Properties > Advanced Tabs > Environment Variables.

Add to ‘System Variables’ by clicking ‘New’ button and insert the following values:
a.  Variable Name : PATH
b.  Variable Value  : c:\instantclient_11_2

Click OK to accept new modification.

Open C:\xampp\php\php.ini by using notepad.

Find string oci8 and remove the ; symbol at the beginning of the string line.

Save and Exit.

Restart you laptop/pc to accept new modification on xampp.

I setup at Window Server 2008 R2 64bit.

Can anyone help?


问:
JS: Item List - copy value content to clipboard
I have a item list (listview), something like this:

```<code><option value="String I want to get copied" title="String I want to get copied">Item1</option>
<option value="String I want to get copied-1" title="String I want to get copied-1">Item2</option>
</code>```

I need to get copied to clipboard the content of (Please, attention!) Title or Value, but NOT "Item1" or "Item2".

Select an item- Right click-Copy the value or title field to clipboard...

It would be great if it possible to do it via menu right mouse click (I'm making a chrome extension). But any idea where to dig will be much appreciated!

答: Did you Try using clipboard js - https://clipboardjs.com/</p>

Body:
I have a item list (listview), something like this:

<option value="String I want to get copied" title="String I want to get copied">Item1</option>
<option value="String I want to get copied-1" title="String I want to get copied-1">Item2</option>

I need to get copied to clipboard the content of (Please, attention!) Title or Value, but NOT "Item1" or "Item2".

Select an item- Right click-Copy the value or title field to clipboard...

It would be great if it possible to do it via menu right mouse click (I'm making a chrome extension). But any idea where to dig will be much appreciated!


问:
StringTokenizer vs. String.split?
Someone just asked a question on String.split() and the solution was to use StringTokenizer. String split comma and parenthisis-JAVA Why doesn't String.split() split on parentheses?

```<code>public static void main(String[] args) {
   String a = "(id,created,employee(id,firstname," +
         "employeeType(id), lastname),location)";
   StringTokenizer tok = new StringTokenizer(a, "(), ");
   System.out.println("StringTokenizer example");
   while (tok.hasMoreElements()) {
      String b = (String)tok.nextElement();
      System.out.println(b);
   }

  System.out.println("Split example");
  String[] array = a.split("(),");
  for (String ii: array) {
      System.out.println(ii);
  }
}
</code>```

Outputs:

```<code>StringTokenizer example
id
created
employee
id
firstname
employeeType
id
lastname
location
Split example
(id
created
employee(id
firstname
employeeType(id)
lastname)
location)
</code>```

There was a discussion on String.split() vs. StringTokenizer at Scanner vs. StringTokenizer vs. String.Split but it doesn't explain the parentheses. Is this by design? What's going on here?

答:
StringTokenizer does not support regular expressions . The token characters "()," for the StringTokenizer are split , so the StringTokenizer code will split the input when it encounters any one of the following ( or ) or ,

String.split takes a regular expression and parenthesis are used to term different expressions. Since there is nothing in the parenthesis , they are ignored and only the comma , is used.

Title: StringTokenizer vs. String.split?

Body:
Someone just asked a question on String.split() and the solution was to use StringTokenizer. String split comma and parenthisis-JAVA Why doesn't String.split() split on parentheses?

public static void main(String[] args) {
   String a = "(id,created,employee(id,firstname," +
         "employeeType(id), lastname),location)";
   StringTokenizer tok = new StringTokenizer(a, "(), ");
   System.out.println("StringTokenizer example");
   while (tok.hasMoreElements()) {
      String b = (String)tok.nextElement();
      System.out.println(b);
   }

  System.out.println("Split example");
  String[] array = a.split("(),");
  for (String ii: array) {
      System.out.println(ii);
  }
}

Outputs:

StringTokenizer example
id
created
employee
id
firstname
employeeType
id
lastname
location
Split example
(id
created
employee(id
firstname
employeeType(id)
lastname)
location)

There was a discussion on String.split() vs. StringTokenizer at Scanner vs. StringTokenizer vs. String.Split but it doesn't explain the parentheses. Is this by design? What's going on here?


答:
If you want split to split on the characters '(', ')', ',', and ' ', you need to pass a regex that matches any of those. The easiest is to use a character class:

```<code>String[] array = a.split("[(), ]");
</code>```

Normally, parentheses in a regex are a grouping operator and would have to be escaped if you intended them to be used as literals. However, inside the character class delimiters, the parenthesis characters do not have to be escaped.

Title: StringTokenizer vs. String.split?

Body:
If you want split to split on the characters '(', ')', ',', and ' ', you need to pass a regex that matches any of those. The easiest is to use a character class:

String[] array = a.split("[(), ]");

Normally, parentheses in a regex are a grouping operator and would have to be escaped if you intended them to be used as literals. However, inside the character class delimiters, the parenthesis characters do not have to be escaped.


问:
ASP.NET MVC 4 Custom Routing
I have an area for admin functionality. I want my URLs to look like so:

admin/{controller}/{slug}.{id}/{action} (i.e. admin/user/getoutofmylab.1/edit)
admin/{controller}/{action} (i.e. admin/user, this is just the index page of the user controller)

When I browse from the root of my app to the user controller, I get admin/user. Links for the edit action of the user controller generate correctly. However, if I link to the index action from within any other action in that controller, the URL is generated as such: admin/user/{slug}.{id}, which, if clicked, generates a 404 not found error.

Here's my AdminAreaRegisration:

```<code>    public override void RegisterArea(AreaRegistrationContext context)
    {
        context.MapRouteLowercase(
            "Admin_Applications",
            "admin/{controller}/{slug}.{id}/{action}",
            new { controller = "Application", action = "Index", id = UrlParameter.Optional, slug = "" },
            new string[] { "Web.Portal.Areas.Admin.Controllers" }
            );

        context.MapRouteLowercase(
            "Admin_default",
            "Admin/{controller}/{action}/{id}",
            new { controller = "Home", action = "Index", id = UrlParameter.Optional },
            new string[] { "Web.Portal.Areas.Admin.Controllers" }
            );
    }
</code>```

How can I achieve the desired result?

Thanks

答:
It seems using Html.RouteLink and specifying the action works rather than using Html.ActionLink:
    @Html.RouteLink("List Applications", "Admin_Default", new { action = "Index" })</p>

Title: ASP.NET MVC 4 Custom Routing

Body:
I have an area for admin functionality. I want my URLs to look like so:

admin/{controller}/{slug}.{id}/{action} (i.e. admin/user/getoutofmylab.1/edit)
admin/{controller}/{action} (i.e. admin/user, this is just the index page of the user controller)

When I browse from the root of my app to the user controller, I get admin/user. Links for the edit action of the user controller generate correctly. However, if I link to the index action from within any other action in that controller, the URL is generated as such: admin/user/{slug}.{id}, which, if clicked, generates a 404 not found error.

Here's my AdminAreaRegisration:

    public override void RegisterArea(AreaRegistrationContext context)
    {
        context.MapRouteLowercase(
            "Admin_Applications",
            "admin/{controller}/{slug}.{id}/{action}",
            new { controller = "Application", action = "Index", id = UrlParameter.Optional, slug = "" },
            new string[] { "Web.Portal.Areas.Admin.Controllers" }
            );

        context.MapRouteLowercase(
            "Admin_default",
            "Admin/{controller}/{action}/{id}",
            new { controller = "Home", action = "Index", id = UrlParameter.Optional },
            new string[] { "Web.Portal.Areas.Admin.Controllers" }
            );
    }

How can I achieve the desired result?

Thanks


问:
Some Excel Files not moving from Shared Path to SQL Server
We have an application where the data in Excel file (present in shared path) moves to Database. In case of any error, the files moves to error folder by writing the error in a log file.It uses a windows service for the operation.

Sometimes the file doesn't have any error still moves to error folder by writing log External table is not in the expected format. But the same file uploading again for once or multiple times, its moving to Database without any errors.

The windows service, DB and shared path are present in XP Server. Application was running fine all these years. But in the recent days, above mentioned problem is occurring for almost every file.

We have installed Microsoft 2003, 2007,2012 office components and access engines too. But still the issue still persists.

I am mentioning the Windows service code below. Pls help. Thanks in advance.

```<code>using System.IO;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Data.Common;

namespace Impexp_Service
{
    public partial class Service1 : ServiceBase
    {
        System.Timers.Timer T1 = new System.Timers.Timer();
        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
          {
            ///start
            ///

            {
                SqlConnection strconnection = new SqlConnection();
                strconnection.ConnectionString = @"Data Source=XXXXXX;Initial Catalog=XXXX;User ID=XX;Password=XXXXXX;";
                strconnection.Open();
                // To get the all files placed at the shared path
                DirectoryInfo directory = new DirectoryInfo(@"D:\Impexp\Data\");
                FileInfo[] files = directory.GetFiles("*.xlsx");

                foreach (var f in files)
                {
                    string path = f.FullName;

                    // TO establish connection to the excel sheet
                    string excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=1\";";
                    //Create Connection to Excel work book
                    OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);

                    excelConnection.Open();
                    //Create OleDbCommand to fetch data from Excel
                    OleDbCommand cmd = new OleDbCommand("Select * from [Report$]", excelConnection);

                    DbDataReader dr = cmd.ExecuteReader();
                    // OleDbDataReader dReader;
                    // dReader = cmd.ExecuteReader();
                    SqlBulkCopy sqlBulk = new SqlBulkCopy(strconnection);
                    //Give your Destination table name
                    sqlBulk.DestinationTableName = "imp_master_test";
                    sqlBulk.WriteToServer(dr);

                    excelConnection.Close();

                    File.Delete(path);

                    // To move error files to the error folder

                    /// end

                    T1.Interval = 20000;
                    T1.Enabled = true;
                    T1.Start();

                    T1.Elapsed += new System.Timers.ElapsedEventHandler(T1_Elapsed);
                }
            }
    }

        void T1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            T1.Enabled = false;
            try
            {
                SqlConnection strconnection = new SqlConnection();
                strconnection.ConnectionString = @"Data Source=10.91.XXXXXX;Initial Catalog=XXXXX;User ID=XXXXX;Password=XXXXX;";
                strconnection.Open();
                // To get the all files placed at the shared path
                DirectoryInfo directory = new DirectoryInfo(@"D:\Impexp\Data\");
                FileInfo[] files = directory.GetFiles("*.xlsx");

                foreach (var f in files)
                {
                    string path = f.FullName;

                    // TO establish connection to the excel sheet
                    string excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=1\";";
                    //Create Connection to Excel work book
                    OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);

                try
                {
                    excelConnection.Open();
                    //Create OleDbCommand to fetch data from Excel
                    OleDbCommand cmd = new OleDbCommand("Select * from [Report$]", excelConnection);

                    DbDataReader dr = cmd.ExecuteReader();
                    // OleDbDataReader dReader;
                    // dReader = cmd.ExecuteReader();
                    SqlBulkCopy sqlBulk = new SqlBulkCopy(strconnection);
                    //Give your Destination table name
                    sqlBulk.DestinationTableName = "imp_master_prod";
                    sqlBulk.WriteToServer(dr);

                    excelConnection.Close();

                    File.Delete(path);

                }
                // To move error files to the error folder
                catch (Exception exp)
                {

                    excelConnection.Close();
                    File.Move(path, Path.Combine(@"D:\Impexp\error\", f.Name));
                    string path1 = @"D:\Impexp\error\error.txt";
                    if (File.Exists(path1))
                    {
                        // Create a file to write to.
                        using (StreamWriter sw = File.AppendText(path1))
                        {
                            sw.WriteLine("File : " + path + " : " + exp.Message);
                            sw.Flush();

                        }
                    }

                        T1.Enabled = true;
                        T1.Start();

                    }
                }
                strconnection.Close();

            // End of TRY 1

            }
            catch (UnauthorizedAccessException UAEx)
            {
                string path1 = @"D:\Impexp\error\error.txt";
                if (File.Exists(path1))
                {
                    // Create a file to write to.
                    using (StreamWriter sw = File.AppendText(path1))
                    {
                        sw.WriteLine(UAEx.Message);
                        sw.Flush();

                    }
                }
                T1.Enabled = true;
                T1.Start();
            }
            catch (PathTooLongException PathEx)
            {
                string path1 = @"D:\Impexp\error\error.txt";
                if (File.Exists(path1))
                {
                    // Create a file to write to.
                    using (StreamWriter sw = File.AppendText(path1))
                    {
                        sw.WriteLine(PathEx.Message);
                        sw.Flush();

                    }
                }
                T1.Enabled = true;
                T1.Start();
            }
            T1.Enabled = true;
            T1.Start();

        }

        protected override void OnStop()
        {
        }
    }
}
</code>```

答:
Looking at this question, this appears to be an issue with reading the excel file, not the SQL table. Try changing the Excel connection string.

```<code>string excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=1\";";
</code>```

to

```<code>string excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;HDR=Yes;IMEX=1\";
</code>```

Also, looking at another answer, the root cause could be uploading newer versions of excel.

Body:
We have an application where the data in Excel file (present in shared path) moves to Database. In case of any error, the files moves to error folder by writing the error in a log file.It uses a windows service for the operation.

Sometimes the file doesn't have any error still moves to error folder by writing log External table is not in the expected format. But the same file uploading again for once or multiple times, its moving to Database without any errors.

The windows service, DB and shared path are present in XP Server. Application was running fine all these years. But in the recent days, above mentioned problem is occurring for almost every file.

We have installed Microsoft 2003, 2007,2012 office components and access engines too. But still the issue still persists.

I am mentioning the Windows service code below. Pls help. Thanks in advance.

using System.IO;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Data.Common;

namespace Impexp_Service
{
    public partial class Service1 : ServiceBase
    {
        System.Timers.Timer T1 = new System.Timers.Timer();
        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
          {
            ///start
            ///

            {
                SqlConnection strconnection = new SqlConnection();
                strconnection.ConnectionString = @"Data Source=XXXXXX;Initial Catalog=XXXX;User ID=XX;Password=XXXXXX;";
                strconnection.Open();
                // To get the all files placed at the shared path
                DirectoryInfo directory = new DirectoryInfo(@"D:\Impexp\Data\");
                FileInfo[] files = directory.GetFiles("*.xlsx");

                foreach (var f in files)
                {
                    string path = f.FullName;

                    // TO establish connection to the excel sheet
                    string excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=1\";";
                    //Create Connection to Excel work book
                    OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);

                    excelConnection.Open();
                    //Create OleDbCommand to fetch data from Excel
                    OleDbCommand cmd = new OleDbCommand("Select * from [Report$]", excelConnection);

                    DbDataReader dr = cmd.ExecuteReader();
                    // OleDbDataReader dReader;
                    // dReader = cmd.ExecuteReader();
                    SqlBulkCopy sqlBulk = new SqlBulkCopy(strconnection);
                    //Give your Destination table name
                    sqlBulk.DestinationTableName = "imp_master_test";
                    sqlBulk.WriteToServer(dr);

                    excelConnection.Close();

                    File.Delete(path);

                    // To move error files to the error folder

                    /// end

                    T1.Interval = 20000;
                    T1.Enabled = true;
                    T1.Start();

                    T1.Elapsed += new System.Timers.ElapsedEventHandler(T1_Elapsed);
                }
            }
    }

        void T1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            T1.Enabled = false;
            try
            {
                SqlConnection strconnection = new SqlConnection();
                strconnection.ConnectionString = @"Data Source=10.91.XXXXXX;Initial Catalog=XXXXX;User ID=XXXXX;Password=XXXXX;";
                strconnection.Open();
                // To get the all files placed at the shared path
                DirectoryInfo directory = new DirectoryInfo(@"D:\Impexp\Data\");
                FileInfo[] files = directory.GetFiles("*.xlsx");

                foreach (var f in files)
                {
                    string path = f.FullName;

                    // TO establish connection to the excel sheet
                    string excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=1\";";
                    //Create Connection to Excel work book
                    OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);

                try
                {
                    excelConnection.Open();
                    //Create OleDbCommand to fetch data from Excel
                    OleDbCommand cmd = new OleDbCommand("Select * from [Report$]", excelConnection);

                    DbDataReader dr = cmd.ExecuteReader();
                    // OleDbDataReader dReader;
                    // dReader = cmd.ExecuteReader();
                    SqlBulkCopy sqlBulk = new SqlBulkCopy(strconnection);
                    //Give your Destination table name
                    sqlBulk.DestinationTableName = "imp_master_prod";
                    sqlBulk.WriteToServer(dr);

                    excelConnection.Close();

                    File.Delete(path);

                }
                // To move error files to the error folder
                catch (Exception exp)
                {

                    excelConnection.Close();
                    File.Move(path, Path.Combine(@"D:\Impexp\error\", f.Name));
                    string path1 = @"D:\Impexp\error\error.txt";
                    if (File.Exists(path1))
                    {
                        // Create a file to write to.
                        using (StreamWriter sw = File.AppendText(path1))
                        {
                            sw.WriteLine("File : " + path + " : " + exp.Message);
                            sw.Flush();

                        }
                    }

                        T1.Enabled = true;
                        T1.Start();

                    }
                }
                strconnection.Close();

            // End of TRY 1

            }
            catch (UnauthorizedAccessException UAEx)
            {
                string path1 = @"D:\Impexp\error\error.txt";
                if (File.Exists(path1))
                {
                    // Create a file to write to.
                    using (StreamWriter sw = File.AppendText(path1))
                    {
                        sw.WriteLine(UAEx.Message);
                        sw.Flush();

                    }
                }
                T1.Enabled = true;
                T1.Start();
            }
            catch (PathTooLongException PathEx)
            {
                string path1 = @"D:\Impexp\error\error.txt";
                if (File.Exists(path1))
                {
                    // Create a file to write to.
                    using (StreamWriter sw = File.AppendText(path1))
                    {
                        sw.WriteLine(PathEx.Message);
                        sw.Flush();

                    }
                }
                T1.Enabled = true;
                T1.Start();
            }
            T1.Enabled = true;
            T1.Start();

        }

        protected override void OnStop()
        {
        }
    }
}

Body:
Looking at this question, this appears to be an issue with reading the excel file, not the SQL table. Try changing the Excel connection string.

string excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=1\";";

to

string excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;HDR=Yes;IMEX=1\";

Also, looking at another answer, the root cause could be uploading newer versions of excel.


问:
How to print the first n lines of file?
I'm sure I'm missing something obvious and probably asked before but I can't seem to get the right combination of keywords together to give me an answer.

How can I write out the first n lines of a file (in effect, the opposite of file.readlines()[0:10])?

e.g. I have a function that takes in an input file, and needs to process information from the latter part, throwing out a header. However I want to keep the multi-line header, to be put back in to an output file.

```<code>def readInfile(infile):

    with open(infile, 'r') as ifh:
        # Skip exta info at top of file
        header = ifh.readline()[0:10] # Keep the header for later?

        noheader = ifh.readlines()[11:]
        for line in noheader:
        # Do the useful stuff
            usefulstuff = foo()

return usefulstuff, header
</code>```

Then later I want to write out in the format of the input file, using their header:

```<code>print(header)
for thing in usefulstuff:
   print(thing)
</code>```

Is there a method I'm missing, or is readlines no good for this as it returns a list?

I assumed

```<code>for line in header:
     print(line)
</code>```

would work, but it doesn't seem to in this case - so I must be doing something wrong?

EDIT

Why does trying to use readlines()[] twice fail for the second range?

I fixed the code as @pbuck pointed out, that the header line should have been readlines() not readline but now the noheader variable is empty? Do I really have to open the file twice?!

答:
I have checked on your solution and it seams you are on track. Consider this solution using mmap python package (https://docs.python.org/2/library/mmap.html) where you can treat the file as a string as well as a file. Here is my solution:</p>

```<code>import mmap

def main(offset):
    with open("pks.txt","r+b") as fd:
        #Get the lines to skip
        try:
            skip=fd.readlines()[0:offset]
            lines=sum([len(x) for x in skip])
            rfile=mmap.mmap(fd.fileno(),0)
            rfile.seek(lines)
            print("Header: %s"%skip)
            print("Other lines:")
            line=rfile.readline()
            usefulStuff=list()
            while (len(line)>0):
                usefulStuff.append(line.lstrip()) #Remove new line
                line=rfile.readline()
            return usefulStuff,skip
        except TypeError as e:
            #Handle this error when offset is greater than the file length
            print("Error: %s"%str(e))
    return None,None
if __name__=='__main__':
    footer,header=main(3)
    print("Header: %s\nFooter: %s"%(header,footer))
</code>```

Title: How to print the first n lines of file?

Body:
I'm sure I'm missing something obvious and probably asked before but I can't seem to get the right combination of keywords together to give me an answer.

How can I write out the first n lines of a file (in effect, the opposite of file.readlines()[0:10])?

e.g. I have a function that takes in an input file, and needs to process information from the latter part, throwing out a header. However I want to keep the multi-line header, to be put back in to an output file.

def readInfile(infile):

    with open(infile, 'r') as ifh:
        # Skip exta info at top of file
        header = ifh.readline()[0:10] # Keep the header for later?

        noheader = ifh.readlines()[11:]
        for line in noheader:
        # Do the useful stuff
            usefulstuff = foo()

return usefulstuff, header

Then later I want to write out in the format of the input file, using their header:

print(header)
for thing in usefulstuff:
   print(thing)

Is there a method I'm missing, or is readlines no good for this as it returns a list?

I assumed

for line in header:
     print(line)

would work, but it doesn't seem to in this case - so I must be doing something wrong?

EDIT

Why does trying to use readlines()[] twice fail for the second range?

I fixed the code as @pbuck pointed out, that the header line should have been readlines() not readline but now the noheader variable is empty? Do I really have to open the file twice?!

Body:
I have checked on your solution and it seams you are on track. Consider this solution using mmap python package (https://docs.python.org/2/library/mmap.html) where you can treat the file as a string as well as a file. Here is my solution:

import mmap

def main(offset):
    with open("pks.txt","r+b") as fd:
        #Get the lines to skip
        try:
            skip=fd.readlines()[0:offset]
            lines=sum([len(x) for x in skip])
            rfile=mmap.mmap(fd.fileno(),0)
            rfile.seek(lines)
            print("Header: %s"%skip)
            print("Other lines:")
            line=rfile.readline()
            usefulStuff=list()
            while (len(line)>0):
                usefulStuff.append(line.lstrip()) #Remove new line
                line=rfile.readline()
            return usefulStuff,skip
        except TypeError as e:
            #Handle this error when offset is greater than the file length
            print("Error: %s"%str(e))
    return None,None
if __name__=='__main__':
    footer,header=main(3)
    print("Header: %s\nFooter: %s"%(header,footer))


问:
Couchbase: Could not dispatch request, cancelling instead of retrying
In the case of running queries asynchronously, client crash with the error:

```<code>com.couchbase.client.core.RequestCancelledException: Could not dispatch request, canceling instead of retrying.
</code>```

Connection Settings:

```<code>final CouchbaseEnvironment env = DefaultCouchbaseEnvironment
  .builder()
  .queryEndpoints(1)
  .retryStrategy(FailFastRetryStrategy.INSTANCE)
  .build();
</code>```

Async query example:

```<code>Observable<SiteData> dataList = bucket
  .async()
  .query(query)
  .flatMap(AsyncN1qlQueryResult::rows)
  .map(row -> new SiteData(row.value()));
</code>```

答:
The reason is queryEndpoints set to 1 and strategy to FailFastRetryStrategy, so, running two requests asynchronously, will fail because there is only one endpoint and strategy is to fail in the case of any exception.

Rise the queryEndpoints or change strategy to BestEffortRetryStrategy or do both:

```<code>final CouchbaseEnvironment env = DefaultCouchbaseEnvironment
  .builder()
  .queryEndpoints(2)
  .retryStrategy(BestEffortRetryStrategy.INSTANCE)
  .build();
</code>```

Body:
In the case of running queries asynchronously, client crash with the error:

com.couchbase.client.core.RequestCancelledException: Could not dispatch request, canceling instead of retrying.

Connection Settings:

final CouchbaseEnvironment env = DefaultCouchbaseEnvironment
  .builder()
  .queryEndpoints(1)
  .retryStrategy(FailFastRetryStrategy.INSTANCE)
  .build();

Async query example:

Observable<SiteData> dataList = bucket
  .async()
  .query(query)
  .flatMap(AsyncN1qlQueryResult::rows)
  .map(row -> new SiteData(row.value()));

Body:
The reason is queryEndpoints set to 1 and strategy to FailFastRetryStrategy, so, running two requests asynchronously, will fail because there is only one endpoint and strategy is to fail in the case of any exception.

Rise the queryEndpoints or change strategy to BestEffortRetryStrategy or do both:

final CouchbaseEnvironment env = DefaultCouchbaseEnvironment
  .builder()
  .queryEndpoints(2)
  .retryStrategy(BestEffortRetryStrategy.INSTANCE)
  .build();