问:
Unresolved java.lang.UnsatisfiedLinkError for FaceRecognizer class
Good morning!

I'm working on a project of face recognition using java but I got this error on FaceRecognizer class:

```<code>Exception in thread "main" java.lang.UnsatisfiedLinkError: com.compa.opencv.nativec.FisherFaceRecognizerID.createFisherFaceRecognizer_1()J
    at com.compa.opencv.nativec.FisherFaceRecognizerID.createFisherFaceRecognizer_1(Native Method)
    at com.compa.opencv.nativec.FisherFaceRecognizerID.<init>(FisherFaceRecognizerID.java:15)
    at com.compa.opencv.PlayMain.createRecognizer(PlayMain.java:128)
    at com.compa.opencv.PlayMain.cameraRecognize(PlayMain.java:88)
    at com.compa.opencv.PlayMain.main(PlayMain.java:33)
</code>```

I have tried the solutions in these below links but it didn't work :s

Getting 'java.lang.UnsatisfiedLinkError': no lwjgl in java.library.path

Exception in thread "main" java.lang.UnsatisfiedLinkError: no openalprjni in java.library.path

Exception in thread "main" java.lang.UnsatisfiedLinkError"

Here is the part of the code which contains the error:

```<code>package com.compa.opencv.nativec;

import org.opencv.contrib.FaceRecognizer;

public class FisherFaceRecognizerID extends FaceRecognizer{

    private static native long createFisherFaceRecognizer_1();

    private static native long createFisherFaceRecognizer_1(int num_components);

    private static native long createFisherFaceRecognizer_2(int num_components,
            double threshold);

    public FisherFaceRecognizerID() {
        super(createFisherFaceRecognizer_1());
    }

    public FisherFaceRecognizerID(int num_components) {
        super(createFisherFaceRecognizer_1(num_components));
    }

    public FisherFaceRecognizerID(int num_components, double threshold) {
        super(createFisherFaceRecognizer_2(num_components, threshold));
    }

}
</code>```

Full code here: https://www.dropbox.com/s/pa415f6lz3zbco7/DemoFaceRecognize-master%20%282%29.zip?dl=0

I would be grateful with any kind of help.

答:
This is the temporary solution that I found:

In the main java file right click --> Properties --> Run/Debug settings --> Choose the main java file and click on Edit --> Arguments --> In the VM arguments field enter the following:

```<code>-Djava.library.path="C:\Program Files\Java\opencv2.4.13\build\java\x64; C:\Program Files\Java\opencv2.4.13\build\x64\vc12\bin"
</code>```

Which will point to the path of the dll files, but unfortunately it didn't work with me :(

Does anyone have any different suggestions?

Body:
Good morning!

I'm working on a project of face recognition using java but I got this error on FaceRecognizer class:

Exception in thread "main" java.lang.UnsatisfiedLinkError: com.compa.opencv.nativec.FisherFaceRecognizerID.createFisherFaceRecognizer_1()J
    at com.compa.opencv.nativec.FisherFaceRecognizerID.createFisherFaceRecognizer_1(Native Method)
    at com.compa.opencv.nativec.FisherFaceRecognizerID.<init>(FisherFaceRecognizerID.java:15)
    at com.compa.opencv.PlayMain.createRecognizer(PlayMain.java:128)
    at com.compa.opencv.PlayMain.cameraRecognize(PlayMain.java:88)
    at com.compa.opencv.PlayMain.main(PlayMain.java:33)

I have tried the solutions in these below links but it didn't work :s

Getting 'java.lang.UnsatisfiedLinkError': no lwjgl in java.library.path

Exception in thread "main" java.lang.UnsatisfiedLinkError: no openalprjni in java.library.path

Exception in thread "main" java.lang.UnsatisfiedLinkError"

Here is the part of the code which contains the error:

package com.compa.opencv.nativec;

import org.opencv.contrib.FaceRecognizer;

public class FisherFaceRecognizerID extends FaceRecognizer{

    private static native long createFisherFaceRecognizer_1();

    private static native long createFisherFaceRecognizer_1(int num_components);

    private static native long createFisherFaceRecognizer_2(int num_components,
            double threshold);

    public FisherFaceRecognizerID() {
        super(createFisherFaceRecognizer_1());
    }

    public FisherFaceRecognizerID(int num_components) {
        super(createFisherFaceRecognizer_1(num_components));
    }

    public FisherFaceRecognizerID(int num_components, double threshold) {
        super(createFisherFaceRecognizer_2(num_components, threshold));
    }

}

Full code here: https://www.dropbox.com/s/pa415f6lz3zbco7/DemoFaceRecognize-master%20%282%29.zip?dl=0

I would be grateful with any kind of help.

Body:
This is the temporary solution that I found:

In the main java file right click --> Properties --> Run/Debug settings --> Choose the main java file and click on Edit --> Arguments --> In the VM arguments field enter the following:

-Djava.library.path="C:\Program Files\Java\opencv2.4.13\build\java\x64; C:\Program Files\Java\opencv2.4.13\build\x64\vc12\bin"

Which will point to the path of the dll files, but unfortunately it didn't work with me :(

Does anyone have any different suggestions?


来源: stackexchange

问:
How to create a conversion of Fahrenheit to Celsius in java
The code should output a table for Fahrenheit and Celsius:

```<code>public static void main(String[] args) {
    System.out.println("Fahrenheit\tCelsius");
    System.out.println("=======================");
     for(int temp = -45; temp <= 120; temp += 5) //for(int i = 0; i <= 100; i+= 10)
        {
            System.out.printf("%5d       |", temp);
            double sum = (temp + (9.0/5.0)) * 32;
            System.out.printf("%5d", (int) sum );
            System.out.println();
        }
}
</code>```

答:
If you want to make output result looks like table, you have to use java.util.Formatter.

I rewrote your snippet, a little bit:

```<code>public static void main(String[] args) {
    Formatter formatter = new Formatter(System.out);

    formatter.format("%-20s\n",      "---------------------------");
    formatter.format("%-10s %12s\n", "| Fahrenheit |", "Celsius |");
    formatter.format("%-20s\n",      "---------------------------");

    for (int farValue = -45; farValue <= 80; farValue += 5) {
        double celValue = (farValue + (9.0 / 5.0)) * 32;

        formatter.format("| %10d | %10.0f |\n", farValue, celValue);
    }
    formatter.format("%-20s\n", "---------------------------");
}
</code>```

The output snippet looks exactly like a table:

```<code>---------------------------
| Fahrenheit |    Celsius |
---------------------------
|        -45 |      -1382 |
|        -40 |      -1222 |
 ...
|        -30 |       -902 |
---------------------------
</code>```

ContentLicense: CC BY-SA 3.0

Body:
The code should output a table for Fahrenheit and Celsius:

public static void main(String[] args) {
    System.out.println("Fahrenheit\tCelsius");
    System.out.println("=======================");
     for(int temp = -45; temp <= 120; temp += 5) //for(int i = 0; i <= 100; i+= 10)
        {
            System.out.printf("%5d       |", temp);
            double sum = (temp + (9.0/5.0)) * 32;
            System.out.printf("%5d", (int) sum );
            System.out.println();
        }
}

Body:
If you want to make output result looks like table, you have to use java.util.Formatter.

I rewrote your snippet, a little bit:

public static void main(String[] args) {
    Formatter formatter = new Formatter(System.out);

    formatter.format("%-20s\n",      "---------------------------");
    formatter.format("%-10s %12s\n", "| Fahrenheit |", "Celsius |");
    formatter.format("%-20s\n",      "---------------------------");

    for (int farValue = -45; farValue <= 80; farValue += 5) {
        double celValue = (farValue + (9.0 / 5.0)) * 32;

        formatter.format("| %10d | %10.0f |\n", farValue, celValue);
    }
    formatter.format("%-20s\n", "---------------------------");
}

The output snippet looks exactly like a table:

---------------------------
| Fahrenheit |    Celsius |
---------------------------
|        -45 |      -1382 |
|        -40 |      -1222 |
 ...
|        -30 |       -902 |
---------------------------


问:
dropping columns from dataframes
I have 5 dataframes and I want to drop certain columns from them. I tried for loop, something like this -

```<code>dataframes =[af,bf,cf,df,ef,ff,gf]
for col in dataframes:
  print col.head(1)
  col = col.drop(col.columns[[0,2]],axis=1)
  print col.head(1)
</code>```

I know the approach is wrong. How to do that without doing it repetitively ?

答:
consider the list of dataframes dataframes

```<code>dataframes = [pd.DataFrame(dict(A=[1], B=[2], C=[3])) for _ in range(4)]
</code>```

Use drop and inplace=True

```<code>for d in dataframes:
    d.drop(['B'], 1, inplace=True)

for d in dataframes:
    print(d)

   A  C
0  1  3
   A  C
0  1  3
   A  C
0  1  3
   A  C
0  1  3
</code>```

Title: dropping columns from dataframes

Body:
I have 5 dataframes and I want to drop certain columns from them. I tried for loop, something like this -

dataframes =[af,bf,cf,df,ef,ff,gf]
for col in dataframes:
  print col.head(1)
  col = col.drop(col.columns[[0,2]],axis=1)
  print col.head(1)

I know the approach is wrong. How to do that without doing it repetitively ?

Body:
consider the list of dataframes dataframes

dataframes = [pd.DataFrame(dict(A=[1], B=[2], C=[3])) for _ in range(4)]

Use drop and inplace=True

for d in dataframes:
    d.drop(['B'], 1, inplace=True)

for d in dataframes:
    print(d)

   A  C
0  1  3
   A  C
0  1  3
   A  C
0  1  3
   A  C
0  1  3


答:
I think your solution is correct if need drop columns by positions, also is possible use list comprehension:

```<code>df = pd.DataFrame({'A':[1,2,3],
                   'B':[4,5,6],
                   'C':[7,8,9],
                   'D':[1,3,5],
                   'E':[5,3,6],
                   'F':[7,4,3]})

df1 = df*10
dataframes = [df,df1]

#get changed list of df
dataframes = [df.drop(df.columns[[0,2]],axis=1) for df in dataframes]
print (dataframes)
[   B  D  E  F
0  4  1  5  7
1  5  3  3  4
2  6  5  6  3,     B   D   E   F
0  40  10  50  70
1  50  30  30  40
2  60  50  60  30]

#original not changed
print (df1)
    A   B   C   D   E   F
0  10  40  70  10  50  70
1  20  50  80  30  30  40
2  30  60  90  50  60  30
</code>```

```<code>#get changed all df inplace, operation return `None`, so output is _
_ = [df.drop(df.columns[[0,2]],axis=1, inplace=True) for df in dataframes]
print (df1)
    B   D   E   F
0  40  10  50  70
1  50  30  30  40
2  60  50  60  30
</code>```

and your solution need not assign, but inplace=True:

```<code>for col in dataframes:
  print (col.head(1))
  col.drop(col.columns[[0,2]],axis=1, inplace=True)
  print (col.head(1))

print (df1)
    B   D   E   F
0  40  10  50  70
1  50  30  30  40
2  60  50  60  30
</code>```

Title: dropping columns from dataframes

Body:
I think your solution is correct if need drop columns by positions, also is possible use list comprehension:

df = pd.DataFrame({'A':[1,2,3],
                   'B':[4,5,6],
                   'C':[7,8,9],
                   'D':[1,3,5],
                   'E':[5,3,6],
                   'F':[7,4,3]})

df1 = df*10
dataframes = [df,df1]

#get changed list of df
dataframes = [df.drop(df.columns[[0,2]],axis=1) for df in dataframes]
print (dataframes)
[   B  D  E  F
0  4  1  5  7
1  5  3  3  4
2  6  5  6  3,     B   D   E   F
0  40  10  50  70
1  50  30  30  40
2  60  50  60  30]

#original not changed
print (df1)
    A   B   C   D   E   F
0  10  40  70  10  50  70
1  20  50  80  30  30  40
2  30  60  90  50  60  30

#get changed all df inplace, operation return `None`, so output is _
_ = [df.drop(df.columns[[0,2]],axis=1, inplace=True) for df in dataframes]
print (df1)
    B   D   E   F
0  40  10  50  70
1  50  30  30  40
2  60  50  60  30

and your solution need not assign, but inplace=True:

for col in dataframes:
  print (col.head(1))
  col.drop(col.columns[[0,2]],axis=1, inplace=True)
  print (col.head(1))

print (df1)
    B   D   E   F
0  40  10  50  70
1  50  30  30  40
2  60  50  60  30


问:
Can someone please explain this answer regarding reference variables?
The task was...

Suppose  a reference variable  of type  String  called myString has already  been declared . Create an object  of type  String  and assign  it to the reference variable  myString.

The correct answer is...

```<code>    String myString2 = new String();
    myString = myString2;
</code>```

I don't get it though.  It just says create an object and assign it to the reference variable.  How are you supposed to know to call it myString2, and why create it if is equal to the first one?  What exactly is this doing?  If myString is already an object, is it essentially creating an object of an object?

答:
I am not entirely sure what you are asking but I am going to try to explain it the way I have understood.

So when you first do String String myString = newString();, it is creating a string variable in the memory. Then what myString actually does is to point to the position of that memory.

So when you go String myString2 = new String(); You are doing exactly the same thing except at different position in the memory. Then when you go myString = myString2; you are making the myString reference to equal to myString2 reference, hence making them point to the same position in the memory - having the same reference value.

I hope that was what you were asking

Body:
The task was...

Suppose  a reference variable  of type  String  called myString has already  been declared . Create an object  of type  String  and assign  it to the reference variable  myString.

The correct answer is...

    String myString2 = new String();
    myString = myString2;

I don't get it though.  It just says create an object and assign it to the reference variable.  How are you supposed to know to call it myString2, and why create it if is equal to the first one?  What exactly is this doing?  If myString is already an object, is it essentially creating an object of an object?


问:
Get json from misformatted json string
I have a json string, which look like that:

```<code>data: { "type": "add",
"newsId": "5da979e0-161d-11e7-9e14-bd201bbe920c",
"articleId": "null",
"category": "news",
"timestamp": "1490970103941",
"id": "5daa8b50-161d-11e7-9e14-bd201bbe920c"}
</code>```

I've created pojo to parse this json using Gson.

```<code>public class SSENewsEvent {

    private String type;

    private String newsId;

    private String articleId;

    private String category;

    private String timestamp;

    private String id;
}
</code>```

But, as you can see, it cannot be parsed because it's somehow misformatted by this

```<code>data:
</code>```

at the beginning of the string. Can you help me to find the best way to parse this string?

答:
There is a syntax error in the json string the JSON string should look like this</p>

```<code>{
    "data":
    {
        "type": "add",
        "newsId": "5da979e0-161d-11e7-9e14-bd201bbe920c",
        "articleId": "null",
        "category": "news",
        "timestamp": "1490970103941",
        "id": "5daa8b50-161d-11e7-9e14-bd201bbe920c"
    }
}
</code>```

Title: Get json from misformatted json string

Body:
I have a json string, which look like that:

data: { "type": "add",
"newsId": "5da979e0-161d-11e7-9e14-bd201bbe920c",
"articleId": "null",
"category": "news",
"timestamp": "1490970103941",
"id": "5daa8b50-161d-11e7-9e14-bd201bbe920c"}

I've created pojo to parse this json using Gson.

public class SSENewsEvent {

    private String type;

    private String newsId;

    private String articleId;

    private String category;

    private String timestamp;

    private String id;
}

But, as you can see, it cannot be parsed because it's somehow misformatted by this

data:

at the beginning of the string. Can you help me to find the best way to parse this string?

Body:
There is a syntax error in the json string the JSON string should look like this

{
    "data":
    {
        "type": "add",
        "newsId": "5da979e0-161d-11e7-9e14-bd201bbe920c",
        "articleId": "null",
        "category": "news",
        "timestamp": "1490970103941",
        "id": "5daa8b50-161d-11e7-9e14-bd201bbe920c"
    }
}


问:
Hit enter to continue or skip function
I'm currently trying to write a program, and I've hit a bit of a bump. I was able to find how to do "hit enter to continue" easy, but now the function (void) that I have it in I also want to be able to skip right about where the first hit enter to continue pops up. Basically, I want to give the user the opportunity to either hit enter to continue with the rest of the function, or hit a button to skip the rest of the function. Here's an idea of what my code looks like currently:

```<code>void intro()
{
    int skip; // Not sure if I need this, was going to experiment

    cout << "Stuff being said " << endl;
    cout << "More stuff being said " << endl;
    cout << "Press 'enter' to continue...";
    cin.ignore(); // This is where I want the input to continue or skip.
</code>```

So basically, I want to keep the hit enter to continue while also giving the user the opportunity to skip the function. Is this possible, or do I have to do something else entirely?

答:
Here is something you should do, if your string is empty: </p>

```<code>#include<iostream>
#include<string>
int main()
{
std::string temp;
std::cout << "Press Enter: ";
getline(std::cin, temp); // Taking input
if (temp.empty()) // if input is empty
    std::cout << "Enter Pressed"; // You can use 'break' or 'return' here
else
    std::cout << "Enter Not Pressed";
return 0;
}
</code>```

Title: Hit enter to continue or skip function

Body:
I'm currently trying to write a program, and I've hit a bit of a bump. I was able to find how to do "hit enter to continue" easy, but now the function (void) that I have it in I also want to be able to skip right about where the first hit enter to continue pops up. Basically, I want to give the user the opportunity to either hit enter to continue with the rest of the function, or hit a button to skip the rest of the function. Here's an idea of what my code looks like currently:

void intro()
{
    int skip; // Not sure if I need this, was going to experiment

    cout << "Stuff being said " << endl;
    cout << "More stuff being said " << endl;
    cout << "Press 'enter' to continue...";
    cin.ignore(); // This is where I want the input to continue or skip.

So basically, I want to keep the hit enter to continue while also giving the user the opportunity to skip the function. Is this possible, or do I have to do something else entirely?

Body:
Here is something you should do, if your string is empty:

#include<iostream>
#include<string>
int main()
{
std::string temp;
std::cout << "Press Enter: ";
getline(std::cin, temp); // Taking input
if (temp.empty()) // if input is empty
    std::cout << "Enter Pressed"; // You can use 'break' or 'return' here
else
    std::cout << "Enter Not Pressed";
return 0;
}


问:
How to use templated struct in class c++
I am trying to use  templated struct within a class, but cant figure out how to declare it properly

```<code>template<typename var>
struct Node
{
    var value;
    Node* left;
    Node* right;
};

class Tree
{
public:
    Tree();
    ~Tree();
    template<typename var>
    void insert(var key, Node *node);
    template<typename var>
    Node* search(var key, Node *node);
    void deleteTree(Node *node);
    void inOrderTraversePrint(Node* node);
    void preOrderTraversePrint(Node* node);
    void postOrderTraversePrint(Node* node);
    Node* getRoot();
    void resetRoot();
private:

    Node* root;
};
</code>```

I keep getting couple errors " Node is not a type"  and "Invalid use of template-name Node without  an argument list".

I know how to template single class and methods within or outside the class, but this is first time I am using struct and trying to use templated struct within a class.
What is proper way to declare and use templated struct within a class.

答: Just change the Node declarations to Node<TypeName>, the compiler is complaining that Node is not a type, and it isn't, but Node<var> is a class in this case.

Body:
I am trying to use  templated struct within a class, but cant figure out how to declare it properly

template<typename var>
struct Node
{
    var value;
    Node* left;
    Node* right;
};

class Tree
{
public:
    Tree();
    ~Tree();
    template<typename var>
    void insert(var key, Node *node);
    template<typename var>
    Node* search(var key, Node *node);
    void deleteTree(Node *node);
    void inOrderTraversePrint(Node* node);
    void preOrderTraversePrint(Node* node);
    void postOrderTraversePrint(Node* node);
    Node* getRoot();
    void resetRoot();
private:

    Node* root;
};

I keep getting couple errors " Node is not a type"  and "Invalid use of template-name Node without  an argument list".

I know how to template single class and methods within or outside the class, but this is first time I am using struct and trying to use templated struct within a class.
What is proper way to declare and use templated struct within a class.


问:
I want to get customer name that ends with g but %g is not working in SQL Server
```<code>select *
from customer
where UPPER(cname) LIKE 'J%G';
</code>```

答:
If you want it to end in G then use this

```<code> select *
 from customer
 where UPPER(cname) LIKE '%G';
</code>```

If it does not seem to finish try this:

```<code> select *
 from (
   select top 1000 *
   from customer with #nolock
 ) X
 where UPPER(cname) LIKE '%G';
</code>```

Body:
If you want it to end in G then use this

 select *
 from customer
 where UPPER(cname) LIKE '%G';

If it does not seem to finish try this:

 select *
 from (
   select top 1000 *
   from customer with #nolock
 ) X
 where UPPER(cname) LIKE '%G';


问:
regex javascript to look for a string with start and end pattern
I would appreciate if someone can help me to come up with a regex that I can look for a pattern in a href. Pattern is to look for a query string hint=value& and then replace it with a new value hint=value2&. so the pattern should start with hint and end with & if there are more query strings or end of the value for hint.

I dont want to use jquery external library (purl). Any help will be much appreciated.

答:
Snippet:

```<code>function replaceValue(newValue, url) {
    const regex = /\?.*?&((hint)=(.*)?&(.*))/g;
    const matches = regex.exec(url);
    let result = '';
    matches.forEach((matchString , index) => {
        if(index === 3) {
            result += newValue;
        }
        else {
            result += matchString;
        }
    });
    return result;
}
</code>```

This would help you

Body:
Snippet:

function replaceValue(newValue, url) {
    const regex = /\?.*?&((hint)=(.*)?&(.*))/g;
    const matches = regex.exec(url);
    let result = '';
    matches.forEach((matchString , index) => {
        if(index === 3) {
            result += newValue;
        }
        else {
            result += matchString;
        }
    });
    return result;
}

This would help you


问:
Printing Out Repeated Numbers
so I'm working on a program that takes two strings. For instance [2,3,4] and [1,4,5] and outprints 1,1,4,4,4,5,5,5,5. I don't really have a working code. So, I'm just looking for tips, not a complete code.</p>

答:
I have an idea, I think there should be a repeat function. For example, it can repeat 'a' 3 times.Like a => [a, a, a]

```<code> function repeat(a, times) {
     if (times === 0) return [];
     return [a].concat(repeat(a, times - 1));
 }
</code>```

Then I using it to finish this question.

```<code> function repeatAndConcat(times, arr) {
   return arr.map(function(item, index) {
     return repeat(item, times[index]);
   }).reduce(function(a, b) {
     return a.concat(b);
   });
 }
</code>```

repeatConcat([2, 3, 4], [1, 4, 5]) with return [ 1, 1, 4, 4, 4, 5, 5, 5, 5 ].

The last reduce flat a nested array.

Title: Printing Out Repeated Numbers

Body:
I have an idea, I think there should be a repeat function. For example, it can repeat 'a' 3 times.Like a => [a, a, a]

 function repeat(a, times) {
     if (times === 0) return [];
     return [a].concat(repeat(a, times - 1));
 }

Then I using it to finish this question.

 function repeatAndConcat(times, arr) {
   return arr.map(function(item, index) {
     return repeat(item, times[index]);
   }).reduce(function(a, b) {
     return a.concat(b);
   });
 }

repeatConcat([2, 3, 4], [1, 4, 5]) with return [ 1, 1, 4, 4, 4, 5, 5, 5, 5 ].

The last reduce flat a nested array.


问:
Datetime.Now cached in a .NET compiled LINQ query
Inside a compiled LINQ query as a condition part, I was using Datetime.Now . It used to give me irrelevant results. I think it used to store same Datetime.Now value for few subsequent calls. To solve this issue I send Datetime.Now as a value parameter to the compiled query and it is working fine.

Old Code

```<code>     event.EventEnd >= Datetime.Now
</code>```

New Code

```<code>     event.EventEnd >= currentTime
</code>```

Where currentTime is a variable contains Datetime.Now value received outside from compiled query.

Please let me know if this is the default behavior of complied LINQ query or I was wrong somewhere

Platform : ASP.NET  4.0,  MVC 2.0

Irrelevant results means , say we have one record with eVent.EventEnd value is 10-10-10 02:10 PM , if I run the query at 10-10-10 02:00 PM , we get that record in the result.  If I run the query at 10-10-10 03:00 PM also we get that record in result.  Which is wrong. But after I use the variable instead on DateTime.Now , it is working fine.

Compiled LINQ Query

```<code>public static Func<DataContext, CommonParams, string, DateTime, IQueryable<EventEntity>> GetEventsByOwnerID
= CompiledQuery.Compile(
(DataContext context, CommonParams inputParams, string eventType, DateTime currentTime ) =>
   (from eVent in context.Events
    join categories in context.Categories on eVent.CategoryID equals categories.CategoryID
    where  !eVent.IsDeleted
    && eVent.OwnerID == inputParams.UserID
    && (eventType == "ALL" ||
        (eventType == "CURRENT" && eVent.EventEnd >= currentTime) ||
        (eventType == "OLD" && eVent.EventEnd < currentTime))
    orderby eVent.PostedOn descending
    select new EventEntity()
    {
        EventID = eVent.EventID,
        CategoryID = eVent.CategoryID,
        Title = eVent.Title,
        Owner = eVent.OwnerName,
        EventStart = eVent.EventStart,
        EventEnd = eVent.EventEnd,
        Host = eVent.Host,
        Location = eVent.Location,
        Description = eVent.Description,
        Email = eVent.Email,
        URL = eVent.URL,
        Phone = eVent.Phone,
        CategoryName = categories.CategoryName,
        ProgramName = eVent.ProgramName,
        IsTelevised = eVent.IsTelevised,
        ChannelName = eVent.ChannelName,
        CityID = eVent.CityID,
        CountryID = eVent.CountryID,
        IsActive = eVent.IsActive,
        OwnerID = eVent.OwnerID,
        IsEndTimePartEmpty = eVent.IsEndTimePartEmpty,
        IsStartTimePartEmpty = eVent.IsStartTimePartEmpty,
        IsDeleted = eVent.IsDeleted,
        ThumbnailURL = eVent.ThumbnailURL,
        AttendeeCount = eVent.AttendeeCount,
        CommentsCount = eVent.CommentsCount
    })
);
</code>```

答: I saw the same issue.  I verified using SQL Profiler that it had cached the value of DateTime.Now.

ContentLicense: CC BY-SA 2.5

Body:
Inside a compiled LINQ query as a condition part, I was using Datetime.Now . It used to give me irrelevant results. I think it used to store same Datetime.Now value for few subsequent calls. To solve this issue I send Datetime.Now as a value parameter to the compiled query and it is working fine.

Old Code

     event.EventEnd >= Datetime.Now

New Code

     event.EventEnd >= currentTime

Where currentTime is a variable contains Datetime.Now value received outside from compiled query.

Please let me know if this is the default behavior of complied LINQ query or I was wrong somewhere

Platform : ASP.NET  4.0,  MVC 2.0

Irrelevant results means , say we have one record with eVent.EventEnd value is 10-10-10 02:10 PM , if I run the query at 10-10-10 02:00 PM , we get that record in the result.  If I run the query at 10-10-10 03:00 PM also we get that record in result.  Which is wrong. But after I use the variable instead on DateTime.Now , it is working fine.

Compiled LINQ Query

public static Func<DataContext, CommonParams, string, DateTime, IQueryable<EventEntity>> GetEventsByOwnerID
= CompiledQuery.Compile(
(DataContext context, CommonParams inputParams, string eventType, DateTime currentTime ) =>
   (from eVent in context.Events
    join categories in context.Categories on eVent.CategoryID equals categories.CategoryID
    where  !eVent.IsDeleted
    && eVent.OwnerID == inputParams.UserID
    && (eventType == "ALL" ||
        (eventType == "CURRENT" && eVent.EventEnd >= currentTime) ||
        (eventType == "OLD" && eVent.EventEnd < currentTime))
    orderby eVent.PostedOn descending
    select new EventEntity()
    {
        EventID = eVent.EventID,
        CategoryID = eVent.CategoryID,
        Title = eVent.Title,
        Owner = eVent.OwnerName,
        EventStart = eVent.EventStart,
        EventEnd = eVent.EventEnd,
        Host = eVent.Host,
        Location = eVent.Location,
        Description = eVent.Description,
        Email = eVent.Email,
        URL = eVent.URL,
        Phone = eVent.Phone,
        CategoryName = categories.CategoryName,
        ProgramName = eVent.ProgramName,
        IsTelevised = eVent.IsTelevised,
        ChannelName = eVent.ChannelName,
        CityID = eVent.CityID,
        CountryID = eVent.CountryID,
        IsActive = eVent.IsActive,
        OwnerID = eVent.OwnerID,
        IsEndTimePartEmpty = eVent.IsEndTimePartEmpty,
        IsStartTimePartEmpty = eVent.IsStartTimePartEmpty,
        IsDeleted = eVent.IsDeleted,
        ThumbnailURL = eVent.ThumbnailURL,
        AttendeeCount = eVent.AttendeeCount,
        CommentsCount = eVent.CommentsCount
    })
);


答:
To drop dataframes using column index, simply use

df.drop(df.columns[[0, 2, 5]], axis=1)

Note: Here I am passing index as 0,2, and 5. The df.columns is zero-based pd.Index

Title: dropping columns from dataframes


问:
Ruby: Avoiding infinite loop in an array that doubles each number
So there is an infinte loop here, but I'm not seeing it.

```<code># Return an array that doubles each number
numbers = [1, 2, 3, 4]
numbers.each do |number|
  numbers << number * 2
end
puts numbers
</code>```

I understand there are shorter ways to do this, but I am learning so it's all written out more explicitly.

答:
Return an array that doubles each number

Assuming you don't want to use map, you can use Enumerable#each_with_object:

```<code>numbers = [1, 2, 3, 4]
numbers.each_with_object([]) { |n, o| o << n + n }
#=> [2, 4, 6, 8]
</code>```

Body:
So there is an infinte loop here, but I'm not seeing it.

# Return an array that doubles each number
numbers = [1, 2, 3, 4]
numbers.each do |number|
  numbers << number * 2
end
puts numbers

I understand there are shorter ways to do this, but I am learning so it's all written out more explicitly.

Body:
Return an array that doubles each number

Assuming you don't want to use map, you can use Enumerable#each_with_object:

numbers = [1, 2, 3, 4]
numbers.each_with_object([]) { |n, o| o << n + n }
#=> [2, 4, 6, 8]


问:
How to stop AsyncTaskLoader from reloading
Currently building an Android app and utilizing AsyncTaskLoader. My app contains a ListView of articles that I obtain using JSON calls. It will leave and go somewhere else (in my case the browser) when the user clicks on an item, but when I press back it reloads the Loader. How can set it up to not reload? Thank you!</p>

答:
use

```<code>     cancelLoadInBackground()
</code>```

Method of AsyncTaskLoader class.

Body:
use

     cancelLoadInBackground()

Method of AsyncTaskLoader class.


问:
How to implement a search queue
I am new in swift3.0 I am implementing a custom search box. I wish to know how can i make a search queue such that on text change in searchbox i need to perform search operation with new text and if there is an existing search operation going on cancel that. I also want to include threshold ontextchanged. So that search operation does not get fired very frequently </p>

答:
Your question is somehow general, but let me tell you how I accomplished this in Swift 3 and AFNetworking (this assumes you wish to search for the data on the server).

I hold a reference of the networking manager in the properties of the view controller:

```<code>//The network requests manager. Stored here because this view controller extensively uses AFNetworking to perform live search updates when the input box changes.
var manager = AFHTTPRequestOperationManager()
</code>```

Afterwards, using UISearchController I check to see if there is any text entered in the search box at all and, if it is, I want to make sure there aren't any other ongoing AFNetworking tasks from now by closing any of them which are still running:

```<code>//Called when the something is typed in the search bar.
func updateSearchResults (for searchController: UISearchController) {
    if !SCString.isStringValid(searchController.searchBar.text) {
        searchController.searchResultsController?.view.isHidden = false
        tableView.reloadData()
        return
    }
    data.searchText = searchController.searchBar.text!

    /**
        Highly important racing issue solution. We cancel any current request going on because we don't want to have the list updated after some time, when we already started another request for a new text. Example:

        - Request 1 started at 12:00:01
        - We clear the containers because Request 2 has to start
        - Request 2 started at 12:00:02
        - Request 1 finished at 12:00:04. We update the containers because data arrived
        - Request 2 finished at 12:00:05. We update the containers because data arrived
        - Now we have data from both 1 and 2, something really not desired.
     */
    manager.session.getTasksWithCompletionHandler { (dataTasks, uploadTasks, downloadTasks) in
        dataTasks.forEach { $0.cancel() }
    }

    /**
        Reloads the list view because we have to remove the last search results.
     */
    reloadListView()
}
</code>```

In the end, I also check in the failure closure if the code of the error is not NSURLErrorCancelled. Because, if that happened, I don't display any error message or toast.

```<code> //The operation might be cancelled by us on purpose. In this case, we don't want to interfere with the ongoing logic flow.
 if (operation?.error as! NSError).code == NSURLErrorCancelled {
    return
 }
 self.retrieveResultListFailureNetwork()
</code>```

Hope it helps!

Title: How to implement a search queue

Body:
Your question is somehow general, but let me tell you how I accomplished this in Swift 3 and AFNetworking (this assumes you wish to search for the data on the server).

I hold a reference of the networking manager in the properties of the view controller:

//The network requests manager. Stored here because this view controller extensively uses AFNetworking to perform live search updates when the input box changes.
var manager = AFHTTPRequestOperationManager()

Afterwards, using UISearchController I check to see if there is any text entered in the search box at all and, if it is, I want to make sure there aren't any other ongoing AFNetworking tasks from now by closing any of them which are still running:

//Called when the something is typed in the search bar.
func updateSearchResults (for searchController: UISearchController) {
    if !SCString.isStringValid(searchController.searchBar.text) {
        searchController.searchResultsController?.view.isHidden = false
        tableView.reloadData()
        return
    }
    data.searchText = searchController.searchBar.text!

    /**
        Highly important racing issue solution. We cancel any current request going on because we don't want to have the list updated after some time, when we already started another request for a new text. Example:

        - Request 1 started at 12:00:01
        - We clear the containers because Request 2 has to start
        - Request 2 started at 12:00:02
        - Request 1 finished at 12:00:04. We update the containers because data arrived
        - Request 2 finished at 12:00:05. We update the containers because data arrived
        - Now we have data from both 1 and 2, something really not desired.
     */
    manager.session.getTasksWithCompletionHandler { (dataTasks, uploadTasks, downloadTasks) in
        dataTasks.forEach { $0.cancel() }
    }

    /**
        Reloads the list view because we have to remove the last search results.
     */
    reloadListView()
}

In the end, I also check in the failure closure if the code of the error is not NSURLErrorCancelled. Because, if that happened, I don't display any error message or toast.

 //The operation might be cancelled by us on purpose. In this case, we don't want to interfere with the ongoing logic flow.
 if (operation?.error as! NSError).code == NSURLErrorCancelled {
    return
 }
 self.retrieveResultListFailureNetwork()

Hope it helps!


问:
How to make IPython notebook matplotlib plot inline
I am trying to use IPython notebook on MacOS X with Python 2.7.2 and IPython 1.1.0.

I cannot get matplotlib graphics to show up inline.

```<code>import matplotlib
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
</code>```

I have also tried %pylab inline and the ipython command line arguments --pylab=inline but this makes no difference.

```<code>x = np.linspace(0, 3*np.pi, 500)
plt.plot(x, np.sin(x**2))
plt.title('A simple chirp')
plt.show()
</code>```

Instead of inline graphics, I get this:

```<code><matplotlib.figure.Figure at 0x110b9c450>
</code>```

And matplotlib.get_backend() shows that I have the 'module://IPython.kernel.zmq.pylab.backend_inline' backend.

答:
You can simulate this problem with a syntax mistake, however, %matplotlib inline won't resolve the issue.

First an example of the right way to create a plot. Everything works as expected with the imports and magic that eNord9 supplied.

```<code>df_randNumbers1 = pd.DataFrame(np.random.randint(0,100,size=(100, 6)), columns=list('ABCDEF'))

df_randNumbers1.ix[:,["A","B"]].plot.kde()
</code>```

However, by leaving the () off the end of the plot type you receive a somewhat ambiguous non-error.

Erronious code:

```<code>df_randNumbers1.ix[:,["A","B"]].plot.kde
</code>```

Example error:

```<code><bound method FramePlotMethods.kde of <pandas.tools.plotting.FramePlotMethods object at 0x000001DDAF029588>>
</code>```

Other than this one line message, there is no stack trace or other obvious reason to think you made a syntax error. The plot doesn't print.

Body:
I am trying to use IPython notebook on MacOS X with Python 2.7.2 and IPython 1.1.0.

I cannot get matplotlib graphics to show up inline.

import matplotlib
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

I have also tried %pylab inline and the ipython command line arguments --pylab=inline but this makes no difference.

x = np.linspace(0, 3*np.pi, 500)
plt.plot(x, np.sin(x**2))
plt.title('A simple chirp')
plt.show()

Instead of inline graphics, I get this:

<matplotlib.figure.Figure at 0x110b9c450>

And matplotlib.get_backend() shows that I have the 'module://IPython.kernel.zmq.pylab.backend_inline' backend.

Body:
You can simulate this problem with a syntax mistake, however, %matplotlib inline won't resolve the issue.

First an example of the right way to create a plot. Everything works as expected with the imports and magic that eNord9 supplied.

df_randNumbers1 = pd.DataFrame(np.random.randint(0,100,size=(100, 6)), columns=list('ABCDEF'))

df_randNumbers1.ix[:,["A","B"]].plot.kde()

However, by leaving the () off the end of the plot type you receive a somewhat ambiguous non-error.

Erronious code:

df_randNumbers1.ix[:,["A","B"]].plot.kde

Example error:

<bound method FramePlotMethods.kde of <pandas.tools.plotting.FramePlotMethods object at 0x000001DDAF029588>>

Other than this one line message, there is no stack trace or other obvious reason to think you made a syntax error. The plot doesn't print.


问:
Is there a prewritten low-impact time drop down that allows selection of any of the 1440 minutes that there are in a day?
I will probably be writing my own.. I wanted to check if anybody already knew of one.

There will be multiple time drop downs in a single form. They will not be <select..> tags with 1440 options per select... They will have a default scrolled position, and they will look like a single drop down with 1440 items but will only display the scrolled position's items and the individual items will only be stored for the focused dropdown.

答: I ended up with an input that opens a list of 20 links showing different times. The top and bottoms had previous/next links that looked like page up and page down functions. The middle of the list was either the currently selected option or the current time.


问:
MySql Connector/J 5.1.41 not connecting
I'm using MySQL Connector/J 5.1.41 to connect to a DB, here's the code I'm using to connect:

```<code>package DB;

import java.sql.Connection;
import java.sql.DriverManager;
import javax.swing.JOptionPane;

public class ConexionMYSQL {
    public String db="floreria";
    public String url= "jdbc:mysql:/localhost"+db;
    public String user= "root";//aqui va el usuario del phpmyadmin
    public String pwd="";

public Connection conectar(){
    Connection link = null;
    try {
        Class.forName("org.gjt.mm.mysql.Driver");
        link = DriverManager.getConnection(this.url, this.user, this.pwd);
    } catch (Exception e) {

        JOptionPane.showMessageDialog(null, "ERROR: "+e);
    }
    return link;
  }
}
</code>```

I'm a newbie in Java and mysql connections, when I execute the code, It shows me the following exception:

ERROR:java.lang.ClassNotFoundException:org.gjt.mm.mysql.Driver

I've already checked that the jar file is in the classpath, I've reinstalled and replaced the jar file for MySql connector too, but stays the same. As I said, I'm new in this world, I barely know about JavaFX and mysql connections, so thats all info I think I can provide, here's an image from my classpath, maybe there's the problem:

答:
Change the code like this : public String url= "jdbc:mysql://localhost/"+db;

Make sure that MySQL Connector/J 5.1.41 jar file placed in the
class path NOT the zip file.

unzip the MySQL Connector/J 5.1.41 jar file and make sure that
this Driver ( org.gjt.mm.mysql.Driver)  is exist .

If not, check com.mysql.jdbc.Driver class is Exist and change the
Driver class as com.mysql.jdbc.Driver.

Title: MySql Connector/J 5.1.41 not connecting

Body:
I'm using MySQL Connector/J 5.1.41 to connect to a DB, here's the code I'm using to connect:

package DB;

import java.sql.Connection;
import java.sql.DriverManager;
import javax.swing.JOptionPane;

public class ConexionMYSQL {
    public String db="floreria";
    public String url= "jdbc:mysql:/localhost"+db;
    public String user= "root";//aqui va el usuario del phpmyadmin
    public String pwd="";

public Connection conectar(){
    Connection link = null;
    try {
        Class.forName("org.gjt.mm.mysql.Driver");
        link = DriverManager.getConnection(this.url, this.user, this.pwd);
    } catch (Exception e) {

        JOptionPane.showMessageDialog(null, "ERROR: "+e);
    }
    return link;
  }
}

I'm a newbie in Java and mysql connections, when I execute the code, It shows me the following exception:

ERROR:java.lang.ClassNotFoundException:org.gjt.mm.mysql.Driver

I've already checked that the jar file is in the classpath, I've reinstalled and replaced the jar file for MySql connector too, but stays the same. As I said, I'm new in this world, I barely know about JavaFX and mysql connections, so thats all info I think I can provide, here's an image from my classpath, maybe there's the problem:


问:
PHP crosstab formatting from array
Hi I have a PHP array like this

```<code>$table=array();
$subject_names=array();

$subject_names[118]="English";
$subject_names[108]="Software Engeneering";

$table['Josh'][118]['int'] =55;
$table['Josh'][118]['ext'] = 10;
$table['Josh'][108]['int'] =45;
$table['Josh'][108]['ext'] = 12;

$table['Matt'][118]['int'] =45;
$table['Matt'][118]['ext'] = 12;
$table['Matt'][108]['int'] =50;
$table['Matt'][108]['ext'] = 15;
</code>```

Here 118 and 108 are subject_id I am trying to format it like this

```<code>    student |       English           |   Software Engeneering |
            | int. mark | ext. mark   | int. mark | ext. mark  |
    ___________________________________________________________
    Josh    | 55        | 10          | 45        | 12
    Matt    | 45        | 12          | 50        | 15
</code>```

I tried

```<code>echo "Student Name\t";

foreach($subject_names as $sub_name)
{
    echo "$sub_name\t";
}
echo "<br>";

foreach($table as $sname => $subjects){

    echo "$sname\t";

    foreach($subjects as $subject_name => $types)
    {
        foreach($types as $marks)
        {
            echo "$marks\t";
        }
    }
    echo "<br>";

}
</code>```

It working fine but if I change the position of array item of table like

```<code>$table['Josh'][118]['int'] =55;
$table['Josh'][108]['int'] =45;
$table['Josh'][118]['ext'] = 10;
$table['Josh'][108]['ext'] = 12;
</code>```

It won't give a correct result. Is there anyway to assure that the result are always correct.

Thank you for your any help and suggestions

答:
Here's a solution I wrote for your request, picking the scores using the $subject_names as control rather than the students' scoresheet (I hope you get what I mean after going through the codes)...

```<code>$table=array();
$subject_names=array();

// notice that I switched subject order, just to show that subjects control the marks displayed thereby ensuring consistent score mapping
$subject_names[108]="Software Engeneering";
$subject_names[118]="English";

// and I'm using the rearranged scores (the sample use-case you specified in the question that distorts your output)
$table['Josh'][118]['int'] =55;
$table['Josh'][108]['int'] =45;
$table['Josh'][118]['ext'] = 10;
$table['Josh'][108]['ext'] = 12;

$table['Matt'][118]['int'] =45;
$table['Matt'][118]['ext'] = 12;
$table['Matt'][108]['int'] =50;
$table['Matt'][108]['ext'] = 15;

echo "Student Name\t";

foreach($subject_names as $sub_name)
{
    echo "$sub_name\t";
}
echo "\n";

// proposed solution:
foreach($table as $sname => $subjects){

    echo "$sname\t";

    foreach ($subject_names as $subject_id => $name) {

        foreach ($subjects[$subject_id] as $mark) {
            echo "$mark\t";
        }
    }
    echo "\n";

}
</code>```

Here's the output of the script above...

```<code>Student Name    Software Engeneering    English
Josh    45  12  55  10
Matt    50  15  45  12
</code>```

Running the same data through the script provided in the question, here's the output (distorted)...

```<code>Student Name    Software Engeneering    English
Josh    55  10  45  12
Matt    45  12  50  15
</code>```

P.S: 'Engeneering' should be 'Engineering'

I hope I've been helpful.
Cheers!

Title: PHP crosstab formatting from array

Body:
Hi I have a PHP array like this

$table=array();
$subject_names=array();

$subject_names[118]="English";
$subject_names[108]="Software Engeneering";

$table['Josh'][118]['int'] =55;
$table['Josh'][118]['ext'] = 10;
$table['Josh'][108]['int'] =45;
$table['Josh'][108]['ext'] = 12;

$table['Matt'][118]['int'] =45;
$table['Matt'][118]['ext'] = 12;
$table['Matt'][108]['int'] =50;
$table['Matt'][108]['ext'] = 15;

Here 118 and 108 are subject_id I am trying to format it like this

    student |       English           |   Software Engeneering |
            | int. mark | ext. mark   | int. mark | ext. mark  |
    ___________________________________________________________
    Josh    | 55        | 10          | 45        | 12
    Matt    | 45        | 12          | 50        | 15

I tried

echo "Student Name\t";

foreach($subject_names as $sub_name)
{
    echo "$sub_name\t";
}
echo "
";

foreach($table as $sname => $subjects){

    echo "$sname\t";

    foreach($subjects as $subject_name => $types)
    {
        foreach($types as $marks)
        {
            echo "$marks\t";
        }
    }
    echo "
";

}

It working fine but if I change the position of array item of table like

$table['Josh'][118]['int'] =55;
$table['Josh'][108]['int'] =45;
$table['Josh'][118]['ext'] = 10;
$table['Josh'][108]['ext'] = 12;

It won't give a correct result. Is there anyway to assure that the result are always correct.

Thank you for your any help and suggestions

Body:
Here's a solution I wrote for your request, picking the scores using the $subject_names as control rather than the students' scoresheet (I hope you get what I mean after going through the codes)...

$table=array();
$subject_names=array();

// notice that I switched subject order, just to show that subjects control the marks displayed thereby ensuring consistent score mapping
$subject_names[108]="Software Engeneering";
$subject_names[118]="English";

// and I'm using the rearranged scores (the sample use-case you specified in the question that distorts your output)
$table['Josh'][118]['int'] =55;
$table['Josh'][108]['int'] =45;
$table['Josh'][118]['ext'] = 10;
$table['Josh'][108]['ext'] = 12;

$table['Matt'][118]['int'] =45;
$table['Matt'][118]['ext'] = 12;
$table['Matt'][108]['int'] =50;
$table['Matt'][108]['ext'] = 15;

echo "Student Name\t";

foreach($subject_names as $sub_name)
{
    echo "$sub_name\t";
}
echo "\n";

// proposed solution:
foreach($table as $sname => $subjects){

    echo "$sname\t";

    foreach ($subject_names as $subject_id => $name) {

        foreach ($subjects[$subject_id] as $mark) {
            echo "$mark\t";
        }
    }
    echo "\n";

}

Here's the output of the script above...

Student Name    Software Engeneering    English
Josh    45  12  55  10
Matt    50  15  45  12

Running the same data through the script provided in the question, here's the output (distorted)...

Student Name    Software Engeneering    English
Josh    55  10  45  12
Matt    45  12  50  15

P.S: 'Engeneering' should be 'Engineering'

I hope I've been helpful.
Cheers!


问:
I need to create a list that has both colums 1 and 2 equal
I need to create a list that has both colums 1 and 2 equal</p>

```<code>  public static List<Integer> lessThanZero(List<Integer> l) {
        for(int x = 0; x < list.length; x++) {
            if(list[x] < 0){

            }
        }
    }
</code>```

答:
NOTE: The question has been heavily edited, to the point that it is now a completely different question. This answer is for the original question. The edited question makes no sense to me at this point, so I have not modified this answer to address the edited version.

This should do it:

```<code>public static List<Integer> lessThanZero(List<Integer> list) {
    List<Integer> result = new ArrayList<>();
    for (Integer val : list) {
        if (val < 0) {
            result.add(val);
        }
    }
    return result;
}
</code>```

Or, as of Java 8, you can do it with streams:

```<code>public static List<Integer> lessThanZero(List<Integer> list) {
    return list.stream().filter(v -> v < 0).collect(Collectors.toList());
}
</code>```

Body:
I need to create a list that has both colums 1 and 2 equal

  public static List<Integer> lessThanZero(List<Integer> l) {
        for(int x = 0; x < list.length; x++) {
            if(list[x] < 0){

            }
        }
    }

Body:
NOTE: The question has been heavily edited, to the point that it is now a completely different question. This answer is for the original question. The edited question makes no sense to me at this point, so I have not modified this answer to address the edited version.

This should do it:

public static List<Integer> lessThanZero(List<Integer> list) {
    List<Integer> result = new ArrayList<>();
    for (Integer val : list) {
        if (val < 0) {
            result.add(val);
        }
    }
    return result;
}

Or, as of Java 8, you can do it with streams:

public static List<Integer> lessThanZero(List<Integer> list) {
    return list.stream().filter(v -> v < 0).collect(Collectors.toList());
}


问:
dropbox api error occured in Maximum execution time of 30 seconds exceeded
Fatal error: Maximum execution time of 30 seconds exceeded in C:\xampp\htdocs\beproject\vendor\dropbox\dropbox-sdk\lib\Dropbox\Curl.php on line 71</p>

答:
Change the 'max_execution_time' to 120 or higher, this can be found on xampp\php\php.ini

Change the '$cfg['ExecTimeLimit']' to 120 or higher, this can be found on xampp\phpMyAdmin\libraries\config.default.php

Restart your XAMP to regenerate the phpinfo.

Hope this will help you.


问:
Controller not calling in AngularJS
I am facing problem in call to controller in child ui state router.

URL is changing but controller not call.

no console error*

Please check code:

HTML

```<code><a style="cursor: pointer;" class="btn btn-default btn-xs"  ui-sref="interactions.details({id:n.id})">Detail</a>
</code>```

Router

```<code>.state('interactions', {
            url: '/interactions',
            data: {
                pageTitle: 'Interaction',
                IsLoginPage: false
            },
            templateUrl: '../../modules/interaction/views/interaction.html',
            controller: 'interactionCtl'
        })
        .state('interactions.details', {
            url:'/details/:id',
            data: {
                pageTitle: 'Interaction Details',
                IsLoginPage: false
            },
            templateUrl: '../../modules/interaction/views/interactionDetail.html',
            controller:'interactionCtlDetails'
        }).run(function ($rootScope, settings, $cookies, $http, $location, AuthenticationService, $state, $stateParams) {

    $rootScope.$state = $state;
    $rootScope.$stateParams = $stateParams;

});
</code>```

Controller

```<code>    warApp.controller('interactionCtlDetails', ["$scope", '$rootScope','$stateParams', 'settings', 'categoryService', 'blockUI',
        function ($scope, interactionService, $rootScope, $stateParams ,settings, categoryService, blockUI) {

            var id = $stateParams.id;
console.log(id);

    });
</code>```

答:
```<code> warApp.controller('interactionCtlDetails', ["$scope", '$rootScope','$stateParams', 'settings', 'categoryService', 'blockUI',
        function ($scope, interactionService, $rootScope, $stateParams ,settings, categoryService, blockUI) {

      var id = $stateParams.id;
       console.log(id);
    });
</code>```

In above code you have function ($scope, interactionService, $rootScope, $stateParams ,settings, categoryService, blockUI) where you have interactionService which you have missed in  your injection section

Title: Controller not calling in AngularJS

Body:
I am facing problem in call to controller in child ui state router.

URL is changing but controller not call.

no console error*

Please check code:

HTML

Detail

Router

.state('interactions', {
            url: '/interactions',
            data: {
                pageTitle: 'Interaction',
                IsLoginPage: false
            },
            templateUrl: '../../modules/interaction/views/interaction.html',
            controller: 'interactionCtl'
        })
        .state('interactions.details', {
            url:'/details/:id',
            data: {
                pageTitle: 'Interaction Details',
                IsLoginPage: false
            },
            templateUrl: '../../modules/interaction/views/interactionDetail.html',
            controller:'interactionCtlDetails'
        }).run(function ($rootScope, settings, $cookies, $http, $location, AuthenticationService, $state, $stateParams) {

    $rootScope.$state = $state;
    $rootScope.$stateParams = $stateParams;

});

Controller

    warApp.controller('interactionCtlDetails', ["$scope", '$rootScope','$stateParams', 'settings', 'categoryService', 'blockUI',
        function ($scope, interactionService, $rootScope, $stateParams ,settings, categoryService, blockUI) {

            var id = $stateParams.id;
console.log(id);

    });

Body:
 warApp.controller('interactionCtlDetails', ["$scope", '$rootScope','$stateParams', 'settings', 'categoryService', 'blockUI',
        function ($scope, interactionService, $rootScope, $stateParams ,settings, categoryService, blockUI) {

      var id = $stateParams.id;
       console.log(id);
    });

In above code you have function ($scope, interactionService, $rootScope, $stateParams ,settings, categoryService, blockUI) where you have interactionService which you have missed in  your injection section


问:
session.save() have some mistake with "unknown entity "
I'm new to hibernate and as I researched. When i want to start my JUnit, this mistake could be occur every time. I guess something wrong with my hbm.xml file. Maybe I am missing something because I'm still new to hibernate.

This is my hbm.xml file.

```<code>    <?xml version='1.0' encoding='utf-8'?>
    <!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>

    <class name="com.test.UserEntity" table="user" schema="" catalog="junwa">
        <id name="id" column="id"/>
        <property name="username" column="username"/>
        <property name="gender" column="gender"/>
        <property name="birthday" column="birthday"/>
        <property name="addres" column="addres"/>
    </class>
</hibernate-mapping>
</code>```

And this is my UserEntity.java file

```<code>package com.test;
import javax.persistence.*;
import java.sql.Timestamp;

@Entity
@Table(name = "user", schema = "", catalog = "junwa")
public class UserEntity {
    private int id;
    private String username;
    private String gender;
    private Timestamp birthday;
    private String addres;

    @Id
    @Column(name = "id")
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    @Basic
    @Column(name = "username")
    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    @Basic
    @Column(name = "gender")
    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    @Basic
    @Column(name = "birthday")
    public Timestamp getBirthday() {
        return birthday;
    }

    public void setBirthday(Timestamp birthday) {
        this.birthday = birthday;
    }

    @Basic
    @Column(name = "addres")
    public String getAddres() {
        return addres;
    }

    public void setAddres(String addres) {
        this.addres = addres;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        UserEntity that = (UserEntity) o;

        if (id != that.id) return false;
        if (username != null ? !username.equals(that.username) : that.username != null) return false;
        if (gender != null ? !gender.equals(that.gender) : that.gender != null) return false;
        if (birthday != null ? !birthday.equals(that.birthday) : that.birthday != null) return false;
        if (addres != null ? !addres.equals(that.addres) : that.addres != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = id;
        result = 31 * result + (username != null ? username.hashCode() : 0);
        result = 31 * result + (gender != null ? gender.hashCode() : 0);
        result = 31 * result + (birthday != null ? birthday.hashCode() : 0);
        result = 31 * result + (addres != null ? addres.hashCode() : 0);
        return result;
    }
}
</code>```

This is my test file.

```<code>/**
 * Created by junwa on 2017/4/2.
 */
import com.test.Students;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.Date;

public class StudentsTest {
    private SessionFactory sessionFactory;
    private Session session;
    private Transaction transaction;
    @Before
    public void init(){
        // create a deploy object
        Configuration config = new Configuration().configure();
        // create a service licenced object
        ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
        // create a  session factory object
        sessionFactory = config.buildSessionFactory(serviceRegistry);
        // create a sessoin object
        session = sessionFactory.openSession();
        // start transaction
        transaction = session.beginTransaction();

    }

    @After
    public void destroy(){
        // commit transaction
        transaction.commit();
        // close session
        session.close();
        // close session factory
        sessionFactory.close();

    }

    @Test
    public void testSaveStudents(){
        // create a object
        Students s = new Students(1,"junwa","male",new Date(),"Anhui");
        // save object to mysql database
        session.save(s);
        session.flush();

    }
}
</code>```

This my output
enter image description here

答:
As Faraz Durrani said when you already have done the mapping in hbm.xml file, why do you need annotations for? Or the vice versa.You have to remove one of them. I would say remove hbm.xml file and use Annotations only.

One more thing I have noticed that you are not closing the transection also.

Body:
I'm new to hibernate and as I researched. When i want to start my JUnit, this mistake could be occur every time. I guess something wrong with my hbm.xml file. Maybe I am missing something because I'm still new to hibernate.

This is my hbm.xml file.

    <?xml version='1.0' encoding='utf-8'?>
    <!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>

    <class name="com.test.UserEntity" table="user" schema="" catalog="junwa">
        <id name="id" column="id"/>
        <property name="username" column="username"/>
        <property name="gender" column="gender"/>
        <property name="birthday" column="birthday"/>
        <property name="addres" column="addres"/>
    </class>
</hibernate-mapping>

And this is my UserEntity.java file

package com.test;
import javax.persistence.*;
import java.sql.Timestamp;

@Entity
@Table(name = "user", schema = "", catalog = "junwa")
public class UserEntity {
    private int id;
    private String username;
    private String gender;
    private Timestamp birthday;
    private String addres;

    @Id
    @Column(name = "id")
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    @Basic
    @Column(name = "username")
    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    @Basic
    @Column(name = "gender")
    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    @Basic
    @Column(name = "birthday")
    public Timestamp getBirthday() {
        return birthday;
    }

    public void setBirthday(Timestamp birthday) {
        this.birthday = birthday;
    }

    @Basic
    @Column(name = "addres")
    public String getAddres() {
        return addres;
    }

    public void setAddres(String addres) {
        this.addres = addres;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        UserEntity that = (UserEntity) o;

        if (id != that.id) return false;
        if (username != null ? !username.equals(that.username) : that.username != null) return false;
        if (gender != null ? !gender.equals(that.gender) : that.gender != null) return false;
        if (birthday != null ? !birthday.equals(that.birthday) : that.birthday != null) return false;
        if (addres != null ? !addres.equals(that.addres) : that.addres != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = id;
        result = 31 * result + (username != null ? username.hashCode() : 0);
        result = 31 * result + (gender != null ? gender.hashCode() : 0);
        result = 31 * result + (birthday != null ? birthday.hashCode() : 0);
        result = 31 * result + (addres != null ? addres.hashCode() : 0);
        return result;
    }
}

This is my test file.

/**
 * Created by junwa on 2017/4/2.
 */
import com.test.Students;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.Date;

public class StudentsTest {
    private SessionFactory sessionFactory;
    private Session session;
    private Transaction transaction;
    @Before
    public void init(){
        // create a deploy object
        Configuration config = new Configuration().configure();
        // create a service licenced object
        ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
        // create a  session factory object
        sessionFactory = config.buildSessionFactory(serviceRegistry);
        // create a sessoin object
        session = sessionFactory.openSession();
        // start transaction
        transaction = session.beginTransaction();

    }

    @After
    public void destroy(){
        // commit transaction
        transaction.commit();
        // close session
        session.close();
        // close session factory
        sessionFactory.close();

    }

    @Test
    public void testSaveStudents(){
        // create a object
        Students s = new Students(1,"junwa","male",new Date(),"Anhui");
        // save object to mysql database
        session.save(s);
        session.flush();

    }
}

This my output
enter image description here


问:
Find and delete empty folders recursively without "-empty" parameter
I found bunch of examples to solve my problem, BUT android find utility and busybox find utility quite old and says:

```<code>A0001:/sdcard # find . -empty -type d
find: bad arg '-empty'
</code>```

So, i can't find solution without usage "-empty" arg. Can anybody help me?

答:
Use the rmdir command which need the directory must be empty.

```<code>find . -maxdepth 3 -type d -print -exec rmdir {} 2>/dev/null \;
</code>```

Redirect the error message to null device, use maxdepth to avoid too deep to search.

Body:
I found bunch of examples to solve my problem, BUT android find utility and busybox find utility quite old and says:

A0001:/sdcard # find . -empty -type d
find: bad arg '-empty'

So, i can't find solution without usage "-empty" arg. Can anybody help me?

Body:
Use the rmdir command which need the directory must be empty.

find . -maxdepth 3 -type d -print -exec rmdir {} 2>/dev/null \;

Redirect the error message to null device, use maxdepth to avoid too deep to search.


答:
In Java 8+, you might use a Stream, a filter and a Collector. Like,

```<code>public static List<Integer> lessThanZero(List<Integer> l) {
    return l.stream().filter(x -> x < 0).collect(Collectors.toList());
}
</code>```

In earlier versions, your current approach will work - but you'll need something to hold the values as you collect them (and I would prefer a for-each loop, and it's worth noting that a List is not an array)

```<code>public static List<Integer> lessThanZero(List<Integer> l) {
    List<Integer> r = new ArrayList<>();
    for (Integer v : l) {
        if (v < 0) {
            r.add(v);
        }
    }
    return r;
}
</code>```

Title: I need to create a list that has both colums 1 and 2 equal

Body:
In Java 8+, you might use a Stream, a filter and a Collector. Like,

public static List<Integer> lessThanZero(List<Integer> l) {
    return l.stream().filter(x -> x < 0).collect(Collectors.toList());
}

In earlier versions, your current approach will work - but you'll need something to hold the values as you collect them (and I would prefer a for-each loop, and it's worth noting that a List is not an array)

public static List<Integer> lessThanZero(List<Integer> l) {
    List<Integer> r = new ArrayList<>();
    for (Integer v : l) {
        if (v < 0) {
            r.add(v);
        }
    }
    return r;
}


问:
HTML connection to MySQL
I want to create a login script on HTML page. I read that I need to use an intermediate script so that I can let my HTML use the database. So, I`ve written a PHP page that checks the username/password regarding the database.

I also read that I should use AJAX to connect to the database.

I would like to know how to write the AJAX code to return the value of the login either true or false.

答:
If I understand your question correctly, there are two ways you could handle this. The first (and most common) way is to just set the PHP script as the action of your HTML form:

```<code><form method="post" action="folder/phpfile.php">
  <input type="text" name="username" />
  <input type="password" name="password" />
</form>
</code>```

After doing this, make sure your PHP script takes in the post variables as $_POST['input_name'], where input_name is the name you used in the inputs on your HTML form (as 'username' and 'password' are used above).

Using AJAX for authentication is not always the best way to handle things in my opinion, but it is doable. I would recommend you try using JQuery behind your JavaScript if you are going to go the AJAX route. They have a really handy framework for handling AJAX queries and events.

Title: HTML connection to MySQL

Body:
If I understand your question correctly, there are two ways you could handle this. The first (and most common) way is to just set the PHP script as the action of your HTML form:

<form method="post" action="folder/phpfile.php">
  <input type="text" name="username" />
  <input type="password" name="password" />
</form>

After doing this, make sure your PHP script takes in the post variables as $_POST['input_name'], where input_name is the name you used in the inputs on your HTML form (as 'username' and 'password' are used above).

Using AJAX for authentication is not always the best way to handle things in my opinion, but it is doable. I would recommend you try using JQuery behind your JavaScript if you are going to go the AJAX route. They have a really handy framework for handling AJAX queries and events.


问:
How to install python3-devel on red hat 7
I am trying to install something in my virtual environment, which uses anaconda python 3.6. I get the gcc failed with exit status 1, hinting on the absence of the right python3-devel package, as described in error: command 'gcc' failed with exit status 1 while installing eventlet.

To fix the error, I tried to install the python3-devel package on my server running RHEL 7.3.
I did yum install python3-devel, but got a 'package not found' error. Then I found https://serverfault.com/questions/710354/repository-for-python3-devel-on-centos-7, which hints to the python34-devel package in the EPEL repository. I installed it using yum, but upon trying to install something in my virtual environment, I still get the gcc failed with exit status 1 error.

Does someone know how I can fix this? All help would be much apprechiated.

答:
Search for the package in yum , use the following command:

```<code>yum search python3 | grep devel
</code>```

It will list all the available devel packages. The result will be somewhat like this

```<code>python3-cairo-devel.x86_64 : Libraries and headers for python3-cairo
python3-devel.x86_64 : Libraries and header files needed for Python 3
                     : development
python34-devel.x86_64 : Libraries and header files needed for Python 3
                      : development
</code>```

Then you can choose the package you want to install from the list , suppose if you want to to install python3-devel , execute the following

```<code>yum install -y python3-devel.x86_64
</code>```

Body:
Search for the package in yum , use the following command:

yum search python3 | grep devel

It will list all the available devel packages. The result will be somewhat like this

python3-cairo-devel.x86_64 : Libraries and headers for python3-cairo
python3-devel.x86_64 : Libraries and header files needed for Python 3
                     : development
python34-devel.x86_64 : Libraries and header files needed for Python 3
                      : development

Then you can choose the package you want to install from the list , suppose if you want to to install python3-devel , execute the following

yum install -y python3-devel.x86_64


问:
dynamic rendering in express using loop won't work
I have bunch of static file, they are named article1, article2 and so on. So I know it worked when I do

```<code>app.get('/this-is-my-article-routes', (req, res) => {
        res.render('article1');
});
</code>```

but it's too tedious and has lots of repeated code. I tried this but it doesn't work?

```<code>const articleArr = [
    'this-is-my-article-routes'
];

for (i = 0; i<9; i++) {
    app.get(`/${articleArr[i]}`, (req, res) => {
        res.render(`article${i}`);
    });
}
</code>```

Is this even possible? or there's something wrong with my codes?

答:
Does your array articleArr contains 10 elements?

I think, the better way to do this would be:

```<code>var articleList = [ 'first', 'second', 'third']
app.get('/:article', (req, res) {
    var articleName = req.params.article
    var index       =  articleList.indexOf(articleName)
    if (index == -1) {
        // No Aricle Found
    }
    res.render(`articles$(index)`)
})
</code>```

This code will also work fine but it is not the recommended one.

```<code>var articleList = ['first', 'second']
articleList.forEach(function(value){
    app.get('/'+value, (req, res) => {
        res.status(200).json({
            value: value
        })
    })
})
</code>```

Body:
I have bunch of static file, they are named article1, article2 and so on. So I know it worked when I do

app.get('/this-is-my-article-routes', (req, res) => {
        res.render('article1');
});

but it's too tedious and has lots of repeated code. I tried this but it doesn't work?

const articleArr = [
    'this-is-my-article-routes'
];

for (i = 0; i<9; i++) {
    app.get(`/${articleArr[i]}`, (req, res) => {
        res.render(`article${i}`);
    });
}

Is this even possible? or there's something wrong with my codes?

Body:
Does your array articleArr contains 10 elements?

I think, the better way to do this would be:

var articleList = [ 'first', 'second', 'third']
app.get('/:article', (req, res) {
    var articleName = req.params.article
    var index       =  articleList.indexOf(articleName)
    if (index == -1) {
        // No Aricle Found
    }
    res.render(`articles$(index)`)
})

This code will also work fine but it is not the recommended one.

var articleList = ['first', 'second']
articleList.forEach(function(value){
    app.get('/'+value, (req, res) => {
        res.status(200).json({
            value: value
        })
    })
})


问:
Linker command failed with exit code 1 C++

My project setting is

Xcode 8.3 (8E162)

Language C++

My project structure is

```<code>├── README.md
├── TrollLanguage
│   ├── TokenParser.cpp
│   ├── TokenParser.hpp
│   └── main.cpp
</code>```

My source code is

main.cpp

```<code>#include <iostream>
#include "TokenParser.hpp"

int main(int argc, const char * argv[]) {
    // insert code here...
    std::cout << "Hello, World!\n";
    TokenParser *tokenParser = new TokenParser();
    tokenParser->TestFunc();
    return 0;
}
</code>```

TokenParser.cpp

```<code>#include "TokenParser.hpp"

void TestFunc() {
    std::cout << "can u see me?";
}
enter code here
</code>```

TokenParser.hpp

```<code>#ifndef TokenParser_hpp
#define TokenParser_hpp

#include <iostream>

class TokenParser {
public:
    void TestFunc();
};

#endif /* TokenParser_hpp */
</code>```

Expected behavior is

```<code>Hello, World!
can u see me?
</code>```

Actual behavior is

```<code>Apple Mach-O Linker (Id) Error
"TokenParser::TestFunc()", referenced from:
Linker command failed with exit code 1(use -v to see invocation
</code>```

答:
You need to prepend the class name as part of the function definition in the implementation file. As it stands, you're defining a free function called TestFunc.

```<code>#include "TokenParser.hpp"

void TokenParser::TestFunc() {
    std::cout << "can u see me?";
}
</code>```

Body:
My project setting is

Xcode 8.3 (8E162)

Language C++

My project structure is

├── README.md
├── TrollLanguage
│   ├── TokenParser.cpp
│   ├── TokenParser.hpp
│   └── main.cpp

My source code is

main.cpp

#include <iostream>
#include "TokenParser.hpp"

int main(int argc, const char * argv[]) {
    // insert code here...
    std::cout << "Hello, World!\n";
    TokenParser *tokenParser = new TokenParser();
    tokenParser->TestFunc();
    return 0;
}

TokenParser.cpp

#include "TokenParser.hpp"

void TestFunc() {
    std::cout << "can u see me?";
}
enter code here

TokenParser.hpp

#ifndef TokenParser_hpp
#define TokenParser_hpp

#include <iostream>

class TokenParser {
public:
    void TestFunc();
};

#endif /* TokenParser_hpp */

Expected behavior is

Hello, World!
can u see me?

Actual behavior is

Apple Mach-O Linker (Id) Error
"TokenParser::TestFunc()", referenced from:
Linker command failed with exit code 1(use -v to see invocation

Body:
You need to prepend the class name as part of the function definition in the implementation file. As it stands, you're defining a free function called TestFunc.

#include "TokenParser.hpp"

void TokenParser::TestFunc() {
    std::cout << "can u see me?";
}


问:
How do I send file name with file using sockets in Java?
I have the following code which transfers file via Sockets. How do I send the file name?</p>

```<code>Socket socket = new Socket("localhost", port);//machine name, port number
File file = new File(fileName);
// Get the size of the file
long length = file.length();
if (length > Integer.MAX_VALUE)
{
    System.out.println("File is too large.");
}
byte[] bytes = new byte[(int) length];
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());

int count;

while ((count = bis.read(bytes)) > 0)
{
    out.write(bytes, 0, count);
}

out.flush();
out.close();
fis.close();
bis.close();
socket.close();
</code>```

答:
I tried to wrap a buffer which cause MalfuctionUTF and putting it on try-with resource closes the underlining socket stream and cause connection reset exception
Following code worked for me

Client

```<code>DataOutputStream d = new DataOutputStream(out);
        d.writeUTF(filename);
        d.writeLong(length);
</code>```

Server

```<code>DataInputStream d = new DataInputStream(in);
filename = d.readUTF();
fileLength = d.readLong();
</code>```

Body:
I have the following code which transfers file via Sockets. How do I send the file name?

Socket socket = new Socket("localhost", port);//machine name, port number
File file = new File(fileName);
// Get the size of the file
long length = file.length();
if (length > Integer.MAX_VALUE)
{
    System.out.println("File is too large.");
}
byte[] bytes = new byte[(int) length];
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());

int count;

while ((count = bis.read(bytes)) > 0)
{
    out.write(bytes, 0, count);
}

out.flush();
out.close();
fis.close();
bis.close();
socket.close();

Body:
I tried to wrap a buffer which cause MalfuctionUTF and putting it on try-with resource closes the underlining socket stream and cause connection reset exception
Following code worked for me

Client

DataOutputStream d = new DataOutputStream(out);
        d.writeUTF(filename);
        d.writeLong(length);

Server

DataInputStream d = new DataInputStream(in);
filename = d.readUTF();
fileLength = d.readLong();


答:
Hope this helps. </p>

```<code>public static List<Integer> lessThanZero(List<Integer> list) {

        List<Integer> lessthanlist = new ArrayList<>();
        for(int x = 0; x < list.length; x++) {
              if(list[x] < 0){
                   lessthanlist.add(list[x]);
              }
        }

           return lessthanlist;
}
</code>```

Body:
Hope this helps.

public static List<Integer> lessThanZero(List<Integer> list) {

        List<Integer> lessthanlist = new ArrayList<>();
        for(int x = 0; x < list.length; x++) {
              if(list[x] < 0){
                   lessthanlist.add(list[x]);
              }
        }

           return lessthanlist;
}


问:
Use fread efficiently to read sparse data
I have a file that stores the data like the following

```<code>A1 B1 C1 ...  A2 B2 C2 ...  .... An Bn Cn ...
</code>```

Here Ai, Bi, and Ci are blocks with 16 bytes. Each chunk Ai Bi Ci ... could be >1M large, and n could be 256. I wanted to read A1, A2... An in sequence, then B1, B2 ... Bn in sequence...

If I am using fread A1, fseek to A2, fread A2, ..., I guess it wastes a lot of IO bandwidth. fread could read 4k bytes from disk at each call, after I do fseek, the cached data by the last fread could be lost. After reading all As, reading B1 needs to read from disk directly but not cache.

Is this assumption correct? I am not sure if file systems can be smart and still keep the cache with B1. If file systems do not help this case, I may have to implement myfread its a wrapper of fread but caches the 256 * 4k data in my own buffer, so the next round of reading Bs can be faster. myfread reads from the buffer until it reaches out of 4k, then it needs fread the real data. But I know fread is not a simple API, can myfread be a simple implementation? Do I need to consider any consistency of file systems? In my case I know no one writes the files when I read.

答:
It's not just the file system, it's the hdd/ssd will also cache. Also Linux will use any spare RAM to cache as much of the file system as it can, throwing it away only as programs allocate memory (I don't know how I make its selection as to what to cache).

Most things will cache blocks, and replace un-used data with data that either is being used by a program, or is close by to used data. Your sparse access is going to be hard work for a cache.

Two options to consider - either 1) read the whole file into a single block of data and do the subdividing later (256MB of data in RAM is nothing these days, just look at Web browser memory consumption, they really are memory hogs), or 2) set up a RAM drive and copy the file to it before using it.

2) is easier, nothing will be quicker then 1)

Body:
I have a file that stores the data like the following

A1 B1 C1 ...  A2 B2 C2 ...  .... An Bn Cn ...

Here Ai, Bi, and Ci are blocks with 16 bytes. Each chunk Ai Bi Ci ... could be >1M large, and n could be 256. I wanted to read A1, A2... An in sequence, then B1, B2 ... Bn in sequence...

If I am using fread A1, fseek to A2, fread A2, ..., I guess it wastes a lot of IO bandwidth. fread could read 4k bytes from disk at each call, after I do fseek, the cached data by the last fread could be lost. After reading all As, reading B1 needs to read from disk directly but not cache.

Is this assumption correct? I am not sure if file systems can be smart and still keep the cache with B1. If file systems do not help this case, I may have to implement myfread its a wrapper of fread but caches the 256 * 4k data in my own buffer, so the next round of reading Bs can be faster. myfread reads from the buffer until it reaches out of 4k, then it needs fread the real data. But I know fread is not a simple API, can myfread be a simple implementation? Do I need to consider any consistency of file systems? In my case I know no one writes the files when I read.


问:
How to get string before "words" or after "words" in PHP
I need help to get the value #4bbedd from style="background-color:#4bbedd;vertical-align:middle;" using PHP functions if there is xPath for this then thanks i needed to
and here is the HTML code for this

HTML code

```<code><!DOCTYPE html>
<html>
<head>
        <title></title>
</head>
<body>
    <div class="pickerContainer" data-reactid=".0.1.1.1.3.0.0.1.1.1.1">
        <div class="ColorPicker" data-reactid=".0.1.1.1.3.0.0.1.1.1.1.0">
            <a class="ui small interactive circular label" style="background-color:#4bbedd;vertical-align:middle;" data-reactid=".0.1.1.1.3.0.0.1.1.1.1.0.$Aquatic Blue">
                <span class="toolTip" data-reactid=".0.1.1.1.3.0.0.1.1.1.1.0.$Aquatic Blue.0">Aquatic Blue</span>
                <i class="checkmark icon" style="display:none;" data-reactid=".0.1.1.1.3.0.0.1.1.1.1.0.$Aquatic Blue.1"></i>
            </a>
            <a class="ui small interactive circular label" style="background-color:#CCCCCC;vertical-align:middle;" data-reactid=".0.1.1.1.3.0.0.1.1.1.1.0.$Ash">
                <span class="toolTip" data-reactid=".0.1.1.1.3.0.0.1.1.1.1.0.$Ash.0">Ash</span>
                <i class="checkmark icon" style="display:none;" data-reactid=".0.1.1.1.3.0.0.1.1.1.1.0.$Ash.1"></i>
            </a>
            <a class="ui small interactive circular label" style="background-color:#999999;vertical-align:middle;" data-reactid=".0.1.1.1.3.0.0.1.1.1.1.0.$Athletic Heather">
                <span class="toolTip" data-reactid=".0.1.1.1.3.0.0.1.1.1.1.0.$Athletic Heather.0">Athletic Heather</span>
                <i class="checkmark icon" style="display:none;" data-reactid=".0.1.1.1.3.0.0.1.1.1.1.0.$Athletic Heather.1"></i>
            </a>
            <a class="ui small interactive circular label" style="background-color:#F27EB2;vertical-align:middle;" data-reactid=".0.1.1.1.3.0.0.1.1.1.1.0.$Azalea">
                <span class="toolTip" data-reactid=".0.1.1.1.3.0.0.1.1.1.1.0.$Azalea.0">Azalea</span>
                <i class="checkmark icon" style="display:none;" data-reactid=".0.1.1.1.3.0.0.1.1.1.1.0.$Azalea.1"></i>
            </a>
            <a class="ui small interactive circular label" style="background-color:#000000;vertical-align:middle;" data-reactid=".0.1.1.1.3.0.0.1.1.1.1.0.$Black">
                <span class="toolTip" data-reactid=".0.1.1.1.3.0.0.1.1.1.1.0.$Black.0">Black</span>
                <i class="checkmark icon" style="display:none;" data-reactid=".0.1.1.1.3.0.0.1.1.1.1.0.$Black.1"></i>
            </a>
        </div>
    </div>
</body>
</html>
</code>```

答:
PHP code demo

```<code><?php

$object = new DOMDocument();
$object->loadHTML('<!DOCTYPE html>
<html>
<head>
        <title></title>
</head>
<body>
    <div class="pickerContainer" data-reactid=".0.1.1.1.3.0.0.1.1.1.1">
        <div class="ColorPicker" data-reactid=".0.1.1.1.3.0.0.1.1.1.1.0">
            <a class="ui small interactive circular label" style="background-color:#4bbedd;vertical-align:middle;" data-reactid=".0.1.1.1.3.0.0.1.1.1.1.0.$Aquatic Blue">
                <span class="toolTip" data-reactid=".0.1.1.1.3.0.0.1.1.1.1.0.$Aquatic Blue.0">Aquatic Blue</span>
                <i class="checkmark icon" style="display:none;" data-reactid=".0.1.1.1.3.0.0.1.1.1.1.0.$Aquatic Blue.1"></i>
            </a>
            <a class="ui small interactive circular label" style="background-color:#CCCCCC;vertical-align:middle;" data-reactid=".0.1.1.1.3.0.0.1.1.1.1.0.$Ash">
                <span class="toolTip" data-reactid=".0.1.1.1.3.0.0.1.1.1.1.0.$Ash.0">Ash</span>
                <i class="checkmark icon" style="display:none;" data-reactid=".0.1.1.1.3.0.0.1.1.1.1.0.$Ash.1"></i>
            </a>
            <a class="ui small interactive circular label" style="background-color:#999999;vertical-align:middle;" data-reactid=".0.1.1.1.3.0.0.1.1.1.1.0.$Athletic Heather">
                <span class="toolTip" data-reactid=".0.1.1.1.3.0.0.1.1.1.1.0.$Athletic Heather.0">Athletic Heather</span>
                <i class="checkmark icon" style="display:none;" data-reactid=".0.1.1.1.3.0.0.1.1.1.1.0.$Athletic Heather.1"></i>
            </a>
            <a class="ui small interactive circular label" style="background-color:#F27EB2;vertical-align:middle;" data-reactid=".0.1.1.1.3.0.0.1.1.1.1.0.$Azalea">
                <span class="toolTip" data-reactid=".0.1.1.1.3.0.0.1.1.1.1.0.$Azalea.0">Azalea</span>
                <i class="checkmark icon" style="display:none;" data-reactid=".0.1.1.1.3.0.0.1.1.1.1.0.$Azalea.1"></i>
            </a>
            <a class="ui small interactive circular label" style="background-color:#000000;vertical-align:middle;" data-reactid=".0.1.1.1.3.0.0.1.1.1.1.0.$Black">
                <span class="toolTip" data-reactid=".0.1.1.1.3.0.0.1.1.1.1.0.$Black.0">Black</span>
                <i class="checkmark icon" style="display:none;" data-reactid=".0.1.1.1.3.0.0.1.1.1.1.0.$Black.1"></i>
            </a>
        </div>
    </div>
</body>
</html>');
$xPathObject= new DOMXPath($object);
$result=$xPathObject->query("/html/body/div/div/a[1]");
$desiredResult="";
foreach($result as $data)
{
    foreach($data->attributes as $attribute)
    {
        if($attribute->name=="style")
        {
            $desiredResult= explode(";",explode(":", $attribute->value)[1])[0];
        }
    }
}
echo $desiredResult;
</code>```

Body:
I need help to get the value #4bbedd from style="background-color:#4bbedd;vertical-align:middle;" using PHP functions if there is xPath for this then thanks i needed to
and here is the HTML code for this

HTML code

<!DOCTYPE html>

        <title></title>

                Aquatic Blue

                Ash

                Athletic Heather

                Azalea

                Black

Body:
PHP code demo

<?php

$object = new DOMDocument();
$object->loadHTML('<!DOCTYPE html>
<html>
<head>
        <title></title>
</head>
<body>
    <div class="pickerContainer" data-reactid=".0.1.1.1.3.0.0.1.1.1.1">
        <div class="ColorPicker" data-reactid=".0.1.1.1.3.0.0.1.1.1.1.0">
            <a class="ui small interactive circular label" style="background-color:#4bbedd;vertical-align:middle;" data-reactid=".0.1.1.1.3.0.0.1.1.1.1.0.$Aquatic Blue">
                <span class="toolTip" data-reactid=".0.1.1.1.3.0.0.1.1.1.1.0.$Aquatic Blue.0">Aquatic Blue</span>
                <i class="checkmark icon" style="display:none;" data-reactid=".0.1.1.1.3.0.0.1.1.1.1.0.$Aquatic Blue.1"></i>
            </a>
            <a class="ui small interactive circular label" style="background-color:#CCCCCC;vertical-align:middle;" data-reactid=".0.1.1.1.3.0.0.1.1.1.1.0.$Ash">
                <span class="toolTip" data-reactid=".0.1.1.1.3.0.0.1.1.1.1.0.$Ash.0">Ash</span>
                <i class="checkmark icon" style="display:none;" data-reactid=".0.1.1.1.3.0.0.1.1.1.1.0.$Ash.1"></i>
            </a>
            <a class="ui small interactive circular label" style="background-color:#999999;vertical-align:middle;" data-reactid=".0.1.1.1.3.0.0.1.1.1.1.0.$Athletic Heather">
                <span class="toolTip" data-reactid=".0.1.1.1.3.0.0.1.1.1.1.0.$Athletic Heather.0">Athletic Heather</span>
                <i class="checkmark icon" style="display:none;" data-reactid=".0.1.1.1.3.0.0.1.1.1.1.0.$Athletic Heather.1"></i>
            </a>
            <a class="ui small interactive circular label" style="background-color:#F27EB2;vertical-align:middle;" data-reactid=".0.1.1.1.3.0.0.1.1.1.1.0.$Azalea">
                <span class="toolTip" data-reactid=".0.1.1.1.3.0.0.1.1.1.1.0.$Azalea.0">Azalea</span>
                <i class="checkmark icon" style="display:none;" data-reactid=".0.1.1.1.3.0.0.1.1.1.1.0.$Azalea.1"></i>
            </a>
            <a class="ui small interactive circular label" style="background-color:#000000;vertical-align:middle;" data-reactid=".0.1.1.1.3.0.0.1.1.1.1.0.$Black">
                <span class="toolTip" data-reactid=".0.1.1.1.3.0.0.1.1.1.1.0.$Black.0">Black</span>
                <i class="checkmark icon" style="display:none;" data-reactid=".0.1.1.1.3.0.0.1.1.1.1.0.$Black.1"></i>
            </a>
        </div>
    </div>
</body>
</html>');
$xPathObject= new DOMXPath($object);
$result=$xPathObject->query("/html/body/div/div/a[1]");
$desiredResult="";
foreach($result as $data)
{
    foreach($data->attributes as $attribute)
    {
        if($attribute->name=="style")
        {
            $desiredResult= explode(";",explode(":", $attribute->value)[1])[0];
        }
    }
}
echo $desiredResult;


问:
Regular Expression \n (new line) error
I have a text-box with regular expression. My issue is that as soon as I exit the text-box (after entering content in it),

I get a

"Contains illegal characters"  error

I deducted that this only happens after I click on the ENTER key. What's weird is that if there is no content in the text-box and I press on ENTER, I don't get an error. The error appears only when I've entered content and then pressed ENTER. (I hope I explained myself correctly...)

Here's the regular expression I have: "^[a-zA-Z0-9_א-ת?!:'\"%$;@. ,()-/\r\n*]*$"

Any Ideas?

答:
You have a minor mistake in your regex

```<code>"^[a-zA-Z0-9_א-ת?!:'\"%$;@. ,()-/\r/\n*]*$"
</code>```

You missed a forward slash before \n

Title: Regular Expression \n (new line) error

Body:
You have a minor mistake in your regex

"^[a-zA-Z0-9_א-ת?!:'\"%$;@. ,()-/\r/\n*]*$"

You missed a forward slash before \n