问:
What are some of the more efficient ways to handle queries?
At the moment, I'm handling them like this:

```<code>$query = mysql_query("...");
while ($results = mysql_fetch_array($query))
 {
    ...
 }
</code>```

What are the more practical ways to go about this?

答:
My question to you is: what's impractical about that?

It seems the ideal paradigm for processing your result set one row at a time. If that's what you need then that's what you need.

My only advice would be to ensure you only ask for the columns you need, and that you let the database do what it's best at. In other words, if you want aggregated results, that's something the database should do (rather than bringing down all records and aggregating on the client).

Regarding the need to do it all at once, there's not a lot of difference between something like (pseudo-code):

```<code>array_of_array = fetch_all()
</code>```

and

```<code>array_of_array = empty
while (array = fetch_one()):
    array_of_array.push (array);
</code>```

Certainly not enough for the language developers to think it necessary, given the possible fetch functions found here.

If you really need that functionality, you could probably code it up yourself. That's why most languages provide the ability to create user-defined functions, after all :-)

Body:
At the moment, I'm handling them like this:

$query = mysql_query("...");
while ($results = mysql_fetch_array($query))
 {
    ...
 }

What are the more practical ways to go about this?

Body:
My question to you is: what's impractical about that?

It seems the ideal paradigm for processing your result set one row at a time. If that's what you need then that's what you need.

My only advice would be to ensure you only ask for the columns you need, and that you let the database do what it's best at. In other words, if you want aggregated results, that's something the database should do (rather than bringing down all records and aggregating on the client).

Regarding the need to do it all at once, there's not a lot of difference between something like (pseudo-code):

array_of_array = fetch_all()

and

array_of_array = empty
while (array = fetch_one()):
    array_of_array.push (array);

Certainly not enough for the language developers to think it necessary, given the possible fetch functions found here.

If you really need that functionality, you could probably code it up yourself. That's why most languages provide the ability to create user-defined functions, after all :-)


来源: stackexchange

问:
streaming multiple log4net logs to elasticsearch via UDP ports
How can I stream logs from multiple log4net in elasticsearch??
For example, if I have multiple Windows servers with .net apps and log4net running on each server, each server streaming logs on a separate UDP port.  How do I setup logs on elasticsearch server to index logs from multiple ports ?</p>

答:
You can use logstash connectors for this purpose. Look at this :

Using logstash, ElasticSearch and log4net for centralized logging in Windows

ContentLicense: CC BY-SA 3.0


问:
EXCEPTION_ACCESS_VIOLATION (0xc0000005) - OpenGL Index Arrays

Problem

I am writing a JOGL program. After adding the addModels() method, it only runs for half a second, and then crashes, giving the following error:

```<code>#
# A fatal error has been detected by the Java Runtime Environment:
#
#  EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x00007ffa5567130d, pid=9684, tid=0x0000000000001c4c
#
# JRE version: Java(TM) SE Runtime Environment (8.0_121-b13) (build 1.8.0_121-b13)
# Java VM: Java HotSpot(TM) 64-Bit Server VM (25.121-b13 mixed mode windows-amd64 compressed oops)
# Problematic frame:
# C  [ig8icd64.dll+0xd130d]
#
# Core dump written. Default location: C:\Users\monke\workspace\TheGame1ByCaleb\hs_err_pid9684.mdmp
#
# An error report file with more information is saved as:
# C:\Users\monke\workspace\TheGame1ByCaleb\hs_err_pid9684.log
#
# If you would like to submit a bug report, please visit:
#   http://bugreport.java.com/bugreport/crash.jsp
# The crash happened outside the Java Virtual Machine in native code.
# See problematic frame for where to report the bug.
#
</code>```

Code

Here is the code that causes the problem:

```<code>// appends model2 onto model1 and returns the new model
public static Model addModels (Model model1, Model model2) {
    Model model;

    int model1VertLen = model1.getVertices().length;
    int model2VertLen = model2.getVertices().length;

    int model1ColorLen = model1.getColors().length;
    int model2ColorLen = model2.getColors().length;

    int model1IndexLen = model1.getIndices().length;
    int model2IndexLen = model2.getIndices().length;

    float[] model1Vertices = model1.getVertices();
    float[] model2Vertices = model2.getVertices();

    float[] model1Colors = model1.getColors();
    float[] model2Colors = model2.getColors();

    int[] model1Indices = model1.getIndices();
    int[] model2Indices = model2.getIndices();

    float[] vertices = new float[model1VertLen + model2VertLen];
    float[] colors = new float[model1ColorLen + model2ColorLen];
    int[] indices = new int[model1IndexLen + model2IndexLen];

    // put all vertex data into one array
    System.arraycopy(model1Vertices, 0, vertices, 0, model1VertLen);
    System.arraycopy(model2Vertices, 0, vertices, model1VertLen, model2VertLen);

    // put all color data into one array
    System.arraycopy(model1Colors, 0, colors, 0, model1ColorLen);
    System.arraycopy(model2Colors, 0, colors, model1ColorLen, model2ColorLen);

    // "translate" (push up) index data by model1IndexLen in second model to match new array
    for (int i=0; i<model2Indices.length; i++) {
        model2Indices[i] += model1IndexLen;
    };

    // test
    for (int i=0; i<model2IndexLen; i++) {
        //indices[model1IndexLen+i] = 0;
    }

    // put all index data into one array
    System.arraycopy(model1Indices, 0, indices, 0, model1IndexLen);
    System.arraycopy(model2Indices, 0, indices, model1IndexLen, model2IndexLen);

    model = new Model(vertices, colors, indices);
    return model;
}
</code>```

Also, here is a sample of a Model-returning method (Models hold very large arrays containing vertex, color, and index data for OpenGL; this one's small, but they usually contains large arrays):

```<code>private static float[] getVertices (Matrix4 transf) {
        float[] vertices = {
                // bottom vertices
                -1,  0, -1,
                +1,  0, -1,
                 0,  0, +1,

                 0,  0,  0  // top (origin)
        };
        for (int i=0; i<vertices.length; i+=3) {
            // get vertex data from vertices array
            float[] vertex = {vertices[i], vertices[i+1], vertices[i+2], 1};
            // transform vertex
            transf.multVec(vertex, vertex);
            // put vertex data into vertices array
            vertices[i] = vertex[0];
            vertices[i+1] = vertex[1];
            vertices[i+2] = vertex[2];
        }

        return vertices;
    }

    private static float[] getColors () {
        float[] colors = new float[3 * 3 * 4];  // 4 triangles, 3 vertices per tri, rgb for vertex
        for (int i=0; i<colors.length; i+=3) {
            colors[i+0] = 1;
            colors[i+1] = 1;
            colors[i+2] = 0;
        }

        return colors;
    }

    private static int[] getIndices () {
        return new int[] {
                // bottom
                0, 1, 2,

                // sides
                0, 1, 3,
                1, 2, 3,
                2, 0, 3
        };
    }

    public static Model getModel(Matrix4 transf) {
        return new Model(getVertices(transf), getColors(), getIndices());
    }

}
</code>```

Lastly, here is the reference to this method in my main class:

```<code>Model terrainModel = Models.Terrain.getModel(terrain);
Model sunModel = Models.Sun.getModel(transformation);
Model model = Models.addModels(terrainModel, sunModel);
</code>```

More info

hs_err_pid9684.log

I tried exporting to JAR and running that in admin terminal, but that did not stop the crash.

Conclusion

I hope the provided information was helpful, and I thank you in advance.

EDIT

I changed

```<code>for (int i=0; i<model2Indices.length; i++) {
    model2Indices[i] += modelIndexLen;
};
</code>```

to

```<code>for (int i=0; i<model2Indices.length; i++) {
    model2Indices[i] += model1VertLen;
};
</code>```

and

```<code>    model2Indices[i] += model1VertLen / 3;  // divide by numb. of items per vertex
</code>```

The problem was that I was pushing the second model's indices up by the number of vertices in the first model. That's incorrect. Add the number of vertices (in the first model) divided by three or four or how ever many items there are per vertex.
And that got it to work!

答:
I finally figured out what I did. When I "pushed up" the indices for the second model (the code snippet in my edit), I pushed them up by the how many items were in the vertex array (length of the vertex array) of the first model, not how many vertices it had. To calculate how many vertices there are, which is the correct number to push the indices up by, you must divide the length of the vertex array by three (or four).

However, though this prevented the crash report, it still isn't concatenating the models correctly (it shows up glitchy on the screen).
If anyone knows what I am doing wrong, the help would be appreciated. Thank you all.

Body:
Problem

I am writing a JOGL program. After adding the addModels() method, it only runs for half a second, and then crashes, giving the following error:

#
# A fatal error has been detected by the Java Runtime Environment:
#
#  EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x00007ffa5567130d, pid=9684, tid=0x0000000000001c4c
#
# JRE version: Java(TM) SE Runtime Environment (8.0_121-b13) (build 1.8.0_121-b13)
# Java VM: Java HotSpot(TM) 64-Bit Server VM (25.121-b13 mixed mode windows-amd64 compressed oops)
# Problematic frame:
# C  [ig8icd64.dll+0xd130d]
#
# Core dump written. Default location: C:\Users\monke\workspace\TheGame1ByCaleb\hs_err_pid9684.mdmp
#
# An error report file with more information is saved as:
# C:\Users\monke\workspace\TheGame1ByCaleb\hs_err_pid9684.log
#
# If you would like to submit a bug report, please visit:
#   http://bugreport.java.com/bugreport/crash.jsp
# The crash happened outside the Java Virtual Machine in native code.
# See problematic frame for where to report the bug.
#

Code

Here is the code that causes the problem:

// appends model2 onto model1 and returns the new model
public static Model addModels (Model model1, Model model2) {
    Model model;

    int model1VertLen = model1.getVertices().length;
    int model2VertLen = model2.getVertices().length;

    int model1ColorLen = model1.getColors().length;
    int model2ColorLen = model2.getColors().length;

    int model1IndexLen = model1.getIndices().length;
    int model2IndexLen = model2.getIndices().length;

    float[] model1Vertices = model1.getVertices();
    float[] model2Vertices = model2.getVertices();

    float[] model1Colors = model1.getColors();
    float[] model2Colors = model2.getColors();

    int[] model1Indices = model1.getIndices();
    int[] model2Indices = model2.getIndices();

    float[] vertices = new float[model1VertLen + model2VertLen];
    float[] colors = new float[model1ColorLen + model2ColorLen];
    int[] indices = new int[model1IndexLen + model2IndexLen];

    // put all vertex data into one array
    System.arraycopy(model1Vertices, 0, vertices, 0, model1VertLen);
    System.arraycopy(model2Vertices, 0, vertices, model1VertLen, model2VertLen);

    // put all color data into one array
    System.arraycopy(model1Colors, 0, colors, 0, model1ColorLen);
    System.arraycopy(model2Colors, 0, colors, model1ColorLen, model2ColorLen);

    // "translate" (push up) index data by model1IndexLen in second model to match new array
    for (int i=0; i<model2Indices.length; i++) {
        model2Indices[i] += model1IndexLen;
    };

    // test
    for (int i=0; i<model2IndexLen; i++) {
        //indices[model1IndexLen+i] = 0;
    }

    // put all index data into one array
    System.arraycopy(model1Indices, 0, indices, 0, model1IndexLen);
    System.arraycopy(model2Indices, 0, indices, model1IndexLen, model2IndexLen);

    model = new Model(vertices, colors, indices);
    return model;
}

Also, here is a sample of a Model-returning method (Models hold very large arrays containing vertex, color, and index data for OpenGL; this one's small, but they usually contains large arrays):

private static float[] getVertices (Matrix4 transf) {
        float[] vertices = {
                // bottom vertices
                -1,  0, -1,
                +1,  0, -1,
                 0,  0, +1,

                 0,  0,  0  // top (origin)
        };
        for (int i=0; i<vertices.length; i+=3) {
            // get vertex data from vertices array
            float[] vertex = {vertices[i], vertices[i+1], vertices[i+2], 1};
            // transform vertex
            transf.multVec(vertex, vertex);
            // put vertex data into vertices array
            vertices[i] = vertex[0];
            vertices[i+1] = vertex[1];
            vertices[i+2] = vertex[2];
        }

        return vertices;
    }

    private static float[] getColors () {
        float[] colors = new float[3 * 3 * 4];  // 4 triangles, 3 vertices per tri, rgb for vertex
        for (int i=0; i<colors.length; i+=3) {
            colors[i+0] = 1;
            colors[i+1] = 1;
            colors[i+2] = 0;
        }

        return colors;
    }

    private static int[] getIndices () {
        return new int[] {
                // bottom
                0, 1, 2,

                // sides
                0, 1, 3,
                1, 2, 3,
                2, 0, 3
        };
    }

    public static Model getModel(Matrix4 transf) {
        return new Model(getVertices(transf), getColors(), getIndices());
    }

}

Lastly, here is the reference to this method in my main class:

Model terrainModel = Models.Terrain.getModel(terrain);
Model sunModel = Models.Sun.getModel(transformation);
Model model = Models.addModels(terrainModel, sunModel);

More info

hs_err_pid9684.log

I tried exporting to JAR and running that in admin terminal, but that did not stop the crash.

Conclusion

I hope the provided information was helpful, and I thank you in advance.

EDIT

I changed

for (int i=0; i<model2Indices.length; i++) {
    model2Indices[i] += modelIndexLen;
};

to

for (int i=0; i<model2Indices.length; i++) {
    model2Indices[i] += model1VertLen;
};

and

    model2Indices[i] += model1VertLen / 3;  // divide by numb. of items per vertex

The problem was that I was pushing the second model's indices up by the number of vertices in the first model. That's incorrect. Add the number of vertices (in the first model) divided by three or four or how ever many items there are per vertex.
And that got it to work!


问:
AttributeError: WindowSpecification class has no 'typekeys' method
I am new to Pywinauto and trying to click "ENTER" after I login to remote desktop application. The desktop window has an usage disclaimer with "OK" button and I can either press "ENTER" or mouse move to click "OK". Below is the code snippet and the error which I am getting.

```<code>rem_app = Application(backend="uia").connect(title_re='.*Remote desktop.*')
dlg_rem = rem_app.window(title_re='.*Remote desktop.*')
dlg_rem.set_focus()
dlg_rem.typekeys('{ENTER}')
</code>```

Error:  Traceback (most recent call last):   File "", line 1, in    File
  "C:\Python27\lib\site-packages\pywinauto\application.py", line 171, in
  call
      format(self.criteria[-1]['best_match'])) AttributeError: WindowSpecification class has no 'typekeys' method

I have also used the below by looking into other related stackoverflow questions:

keyboard.sendkeys('{ENTER}')

dlg_rem.sendkeys('{ENTER}')

Here's what print_control_identifiers() describes about the "OK" button.

```<code>   |    |    |    | Pane - ''    (L403, T360, R1671, B1320)
   |    |    |    | [u'3', 'Pane4']

   |    |    |    |    |
   |    |    |    |    | Pane - 'Input Capture Window'    (L403, T360, R1671, B1320)
   |    |    |    |    | [u'Input Capture Window', u'Input Capture WindowPane', 'Pane5']
   |    |    |    |    | child_window(title="Input Capture Window", control_type="Pane")
</code>```

I would like to know on how to use sendkeys and mouse move to click "OK" for the above scenario in both cases.

答:
Correct method name is .type_keys('{ENTER}'). It sets the focus to target window before typing.

If you don't need auto-focus, just use keyboard.SendKeys('{ENTER}') without binding to any app (0.6.3. will have keyboard.send_keys alias that fits into PEP8 guidelines).

P.S. Don't recommend to automate anything by Remote Desktop (with any tool) because RDP doesn't expose UI accessibility features to local machine. Just copy the script to remote machine and run it there.

If you need several remote machines running GUI automation tasks simultaneously, check these answers for more details:

https://stackoverflow.com/a/35009605/3648361

https://stackoverflow.com/a/35969841/3648361

Body:
I am new to Pywinauto and trying to click "ENTER" after I login to remote desktop application. The desktop window has an usage disclaimer with "OK" button and I can either press "ENTER" or mouse move to click "OK". Below is the code snippet and the error which I am getting.

rem_app = Application(backend="uia").connect(title_re='.*Remote desktop.*')
dlg_rem = rem_app.window(title_re='.*Remote desktop.*')
dlg_rem.set_focus()
dlg_rem.typekeys('{ENTER}')

Error:  Traceback (most recent call last):   File "", line 1, in    File
  "C:\Python27\lib\site-packages\pywinauto\application.py", line 171, in
  call
      format(self.criteria[-1]['best_match'])) AttributeError: WindowSpecification class has no 'typekeys' method

I have also used the below by looking into other related stackoverflow questions:

keyboard.sendkeys('{ENTER}')

dlg_rem.sendkeys('{ENTER}')

Here's what print_control_identifiers() describes about the "OK" button.

   |    |    |    | Pane - ''    (L403, T360, R1671, B1320)
   |    |    |    | [u'3', 'Pane4']

   |    |    |    |    |
   |    |    |    |    | Pane - 'Input Capture Window'    (L403, T360, R1671, B1320)
   |    |    |    |    | [u'Input Capture Window', u'Input Capture WindowPane', 'Pane5']
   |    |    |    |    | child_window(title="Input Capture Window", control_type="Pane")

I would like to know on how to use sendkeys and mouse move to click "OK" for the above scenario in both cases.


问:
Getting 'activeSpreadsheet.getSheetByName()' to change dynamically
Please see the picture below

I have this GoogleSheets spreadsheet with a BUNCH of tabs (sheets) in it. The following code needs to run for EVERY sheet:

```<code>function SearchCols()
{
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1"),
    searchVal = sheet.getRange("L7").getValue(),
    searchCol = sheet.getRange('L11:L30').getValues();
    searchCol1 = sheet.getRange ('R11:R30').getValues();
    searchCol2 = sheet.getRange('Q11:Q30').getValues();
    searchCol3 = sheet.getRange('S11:S30').getValues();
    searchCol4 = sheet.getRange('T11:T30').getValues();

for (var i = 0, len = searchCol2.length; i < len; i++)
for (var j = 0, len2 = searchCol1.length; j < len2; j++)
    {
      if (searchCol2[j][0] == searchVal && searchCol1[j][0] == searchCol[i]
[0])
      {
        sheet.getRange('N11:N10').setValue;
        sheet.getRange(i + 11, 14).setValue(searchCol3[j][0])
        sheet.getRange(i + 11, 15).setValue(searchCol4[j][0])
      }
    }
}
</code>```

It just some code to loop through a column to see if any values match with another column, and if so, paste some data into adjacent cells.

The code works, BUT...

See the 3rd line of code? Where it says: ".getSheetByName("Sheet1")"???

How do I change that "Sheet1" part so it DYNAMICALLY knows what sheet I'm on in order to run the code FOR THAT SPECIFIC SHEET?

I have a 'Run' button in EVERY sheet of my file, but I ONLY want this code to run for the sheet that I press the button in. (look at the attached screenshot!)

The way it is right now, if I'm in Sheet50 and I press the button to run this code, it will produce the results in Sheet1, but I need it to produce results in Sheet50! The same applies for every sheet of my file. When I press the 'Run' button, I need the code to ONLY run for that specific sheet.

Please help, dear friends!

答:
To loop through all of your sheets:

Get all of the sheets in the spreadsheet using .getSheets() then use a for loop to iterate through all of the sheets in the spreadsheet.

This is your code modified to work as you asked:

```<code>    function SearchCols() {

    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var sheets = ss.getSheets();

    for (var i = 0; i < sheets.length; i++) {
        var sheet = ss.getSheetByName(sheets[i].getName());

        var searchVal = sheet.getRange("L7").getValue();
        var searchCol = sheet.getRange('L11:L30').getValues();
        var searchCol1 = sheet.getRange('R11:R30').getValues();
        var searchCol2 = sheet.getRange('Q11:Q30').getValues();
        var searchCol3 = sheet.getRange('S11:S30').getValues();
        var searchCol4 = sheet.getRange('T11:T30').getValues();

        for (var x = 0, len = searchCol2.length; x < len; x++) {
            for (var j = 0, len2 = searchCol1.length; j < len2; j++) {

                if (searchCol2[j][0] == searchVal && searchCol1[j][0] == searchCol[x][0]) {
                    sheet.getRange('N11:N10').setValue;
                    sheet.getRange(x + 11, 14).setValue(searchCol3[j][0])
                    sheet.getRange(x + 11, 15).setValue(searchCol4[j][0])
                }
            }
        }
    }
}
</code>```

Body:
Please see the picture below

I have this GoogleSheets spreadsheet with a BUNCH of tabs (sheets) in it. The following code needs to run for EVERY sheet:

function SearchCols()
{
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1"),
    searchVal = sheet.getRange("L7").getValue(),
    searchCol = sheet.getRange('L11:L30').getValues();
    searchCol1 = sheet.getRange ('R11:R30').getValues();
    searchCol2 = sheet.getRange('Q11:Q30').getValues();
    searchCol3 = sheet.getRange('S11:S30').getValues();
    searchCol4 = sheet.getRange('T11:T30').getValues();

for (var i = 0, len = searchCol2.length; i < len; i++)
for (var j = 0, len2 = searchCol1.length; j < len2; j++)
    {
      if (searchCol2[j][0] == searchVal && searchCol1[j][0] == searchCol[i]
[0])
      {
        sheet.getRange('N11:N10').setValue;
        sheet.getRange(i + 11, 14).setValue(searchCol3[j][0])
        sheet.getRange(i + 11, 15).setValue(searchCol4[j][0])
      }
    }
}

It just some code to loop through a column to see if any values match with another column, and if so, paste some data into adjacent cells.

The code works, BUT...

See the 3rd line of code? Where it says: ".getSheetByName("Sheet1")"???

How do I change that "Sheet1" part so it DYNAMICALLY knows what sheet I'm on in order to run the code FOR THAT SPECIFIC SHEET?

I have a 'Run' button in EVERY sheet of my file, but I ONLY want this code to run for the sheet that I press the button in. (look at the attached screenshot!)

The way it is right now, if I'm in Sheet50 and I press the button to run this code, it will produce the results in Sheet1, but I need it to produce results in Sheet50! The same applies for every sheet of my file. When I press the 'Run' button, I need the code to ONLY run for that specific sheet.

Please help, dear friends!

Body:
To loop through all of your sheets:

Get all of the sheets in the spreadsheet using .getSheets() then use a for loop to iterate through all of the sheets in the spreadsheet.

This is your code modified to work as you asked:

    function SearchCols() {

    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var sheets = ss.getSheets();

    for (var i = 0; i < sheets.length; i++) {
        var sheet = ss.getSheetByName(sheets[i].getName());

        var searchVal = sheet.getRange("L7").getValue();
        var searchCol = sheet.getRange('L11:L30').getValues();
        var searchCol1 = sheet.getRange('R11:R30').getValues();
        var searchCol2 = sheet.getRange('Q11:Q30').getValues();
        var searchCol3 = sheet.getRange('S11:S30').getValues();
        var searchCol4 = sheet.getRange('T11:T30').getValues();

        for (var x = 0, len = searchCol2.length; x < len; x++) {
            for (var j = 0, len2 = searchCol1.length; j < len2; j++) {

                if (searchCol2[j][0] == searchVal && searchCol1[j][0] == searchCol[x][0]) {
                    sheet.getRange('N11:N10').setValue;
                    sheet.getRange(x + 11, 14).setValue(searchCol3[j][0])
                    sheet.getRange(x + 11, 15).setValue(searchCol4[j][0])
                }
            }
        }
    }
}


问:
Generating all permutations of a given string
What is an elegant way to find all the permutations of a string. E.g. permutation for ba, would be ba and ab, but what about longer string such as abcdefgh? Is there any Java implementation example?

答:
This is a faster solution as it doesn't suffer for string concatenation computation complexity O(n^2). On the other hand its loop free, fully recursive </p>

```<code>public static void main(String[] args) {
    permutation("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
}

private static void permutation(String str) {
    char[] stringArray = str.toCharArray();
    printPermutation(stringArray, 0, stringArray.length, 0, 1);
}

private static void printPermutation(char[] string, int loopCounter, int length, int indexFrom, int indexTo) {
    // Stop condition
    if (loopCounter == length)
        return;

    /*
     When reaching the end of the array:
     1- Reset loop indices.
     2- Increase length counter.
    */
    if (indexTo == length) {
        indexFrom = 0;
        indexTo = 1;
        ++loopCounter;
    }

    // Print.
    System.out.println(string);

    // Swap from / to indices.
    char temp = string[indexFrom];
    string[indexFrom] = string[indexTo];
    string[indexTo] = temp;

    // Go for next iteration.
    printPermutation(string, loopCounter, length, ++indexFrom, ++indexTo);
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
This is a faster solution as it doesn't suffer for string concatenation computation complexity O(n^2). On the other hand its loop free, fully recursive

public static void main(String[] args) {
    permutation("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
}

private static void permutation(String str) {
    char[] stringArray = str.toCharArray();
    printPermutation(stringArray, 0, stringArray.length, 0, 1);
}

private static void printPermutation(char[] string, int loopCounter, int length, int indexFrom, int indexTo) {
    // Stop condition
    if (loopCounter == length)
        return;

    /*
     When reaching the end of the array:
     1- Reset loop indices.
     2- Increase length counter.
    */
    if (indexTo == length) {
        indexFrom = 0;
        indexTo = 1;
        ++loopCounter;
    }

    // Print.
    System.out.println(string);

    // Swap from / to indices.
    char temp = string[indexFrom];
    string[indexFrom] = string[indexTo];
    string[indexTo] = temp;

    // Go for next iteration.
    printPermutation(string, loopCounter, length, ++indexFrom, ++indexTo);
}


问:
Custom configuration section defined in executable
I have defined custom configuration section class in the same executable assembly (IVITerminal.exe) as this section for. In App.config I have:

```<code><configSections>
....
<section name="myconfig" type="IVITermital.Configuration.Section, IVITerminal"/>
....
</configSections>
....
<myconfig>....</myconfig>
</code>```

But when I want to read section:

```<code>static void Main(string[] args)
{
    var s = ConfigurationManager.GetSection("myconfig") as Section;
</code>```

I got exception Could not load type 'IVITermital.Configuration.Section' from assembly 'IVITerminal'. of type System.Configuration.ConfigurationErrorsException.

Is it possible to define configuration sections in same exe?

答:
That error usually means that there was some sort of syntax error in your file. I.e. the placement was wrong, the spelling was incorrect, or an unclosed section.

Was there an inner exception?

The MSDN documentation describes the format as this:

```<code><configuration>
    <!-- Configuration section-handler declaration area. -->
      <configSections>
    <sectionGroup name="pageAppearanceGroup">
      <section
        name="pageAppearance"
        type="Samples.AspNet.PageAppearanceSection"
        allowLocation="true"
        allowDefinition="Everywhere"
      />
    </sectionGroup>
      <!-- Other <section> and <sectionGroup> elements. -->
  </configSections>

  <!-- Configuration section settings area. -->

</configuration>
</code>```

More here: https://msdn.microsoft.com/en-us/library/2tw134k3.aspx

Body:
I have defined custom configuration section class in the same executable assembly (IVITerminal.exe) as this section for. In App.config I have:

<configSections>
....

....
</configSections>
....
<myconfig>....</myconfig>

But when I want to read section:

static void Main(string[] args)
{
    var s = ConfigurationManager.GetSection("myconfig") as Section;

I got exception Could not load type 'IVITermital.Configuration.Section' from assembly 'IVITerminal'. of type System.Configuration.ConfigurationErrorsException.

Is it possible to define configuration sections in same exe?

Body:
That error usually means that there was some sort of syntax error in your file. I.e. the placement was wrong, the spelling was incorrect, or an unclosed section.

Was there an inner exception?

The MSDN documentation describes the format as this:

<configuration>
    <!-- Configuration section-handler declaration area. -->
      <configSections>
    <sectionGroup name="pageAppearanceGroup">
      <section
        name="pageAppearance"
        type="Samples.AspNet.PageAppearanceSection"
        allowLocation="true"
        allowDefinition="Everywhere"
      />
    </sectionGroup>
      <!-- Other <section> and <sectionGroup> elements. -->
  </configSections>

  <!-- Configuration section settings area. -->

</configuration>

More here: https://msdn.microsoft.com/en-us/library/2tw134k3.aspx


问:
Why does my application stop working?
So, I am trying to do an application which gets a random number between 1 and 4 ( 1 inclusive and 4 exclusive ) and after, getting that number, it would change the background color of my Main Activity to the related number:

If it gets the number 1: Change to Blue
If number 2: Change to Black
If 3: Change to Yellow

Here's the code:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button button = (Button) findViewById(R.id.button);
    Button button2 = (Button) findViewById(R.id.button2);

    button.setOnClickListener( new  View.OnClickListener() {

            public void onClick(View v) {

            LinearLayout layout = (LinearLayout) findViewById(R.id.layout);
            Random rnd = new Random();
            int random = rnd.nextInt(1 - 4);

                if (random == 1) {

                layout.setBackgroundColor(Color.BLUE);

                } else if (random == 2) {

                layout.setBackgroundColor(Color.BLACK);

                } else {

                layout.setBackgroundColor(Color.YELLOW);

                }

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

The code seems fine to me and Android Studio doesn't report any errors ( only a warning because of the button2 ), but everytime I tap the button, the app just closes and says "Unfortunatly, Exercise has stopped."

My question is: Why does the application stop working after I tap the button?

( If any more information is needed, tell. I never asked and I am quite a novice in asking and Android Development )

答:
```<code>int random = rnd.nextInt(1 - 4);
</code>```

the problem is with above line, because it can throw an Exception.

Try to catch this Exception with try {} catch {} blocks and you will see.

Also you can change your algorithm for example use list with colors

```<code>List<Color> colors = Arrays.asList(Color.BLUE, Color.RED, Color.YELLOW);
layout.setBackgroundColor(colors.get(rand.nextInt(colors.size() - 1));
</code>```

Title: Why does my application stop working?

Body:
So, I am trying to do an application which gets a random number between 1 and 4 ( 1 inclusive and 4 exclusive ) and after, getting that number, it would change the background color of my Main Activity to the related number:

If it gets the number 1: Change to Blue
If number 2: Change to Black
If 3: Change to Yellow

Here's the code:

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

    Button button = (Button) findViewById(R.id.button);
    Button button2 = (Button) findViewById(R.id.button2);

    button.setOnClickListener( new  View.OnClickListener() {

            public void onClick(View v) {

            LinearLayout layout = (LinearLayout) findViewById(R.id.layout);
            Random rnd = new Random();
            int random = rnd.nextInt(1 - 4);

                if (random == 1) {

                layout.setBackgroundColor(Color.BLUE);

                } else if (random == 2) {

                layout.setBackgroundColor(Color.BLACK);

                } else {

                layout.setBackgroundColor(Color.YELLOW);

                }

            }
        }
    );
}

The code seems fine to me and Android Studio doesn't report any errors ( only a warning because of the button2 ), but everytime I tap the button, the app just closes and says "Unfortunatly, Exercise has stopped."

My question is: Why does the application stop working after I tap the button?

( If any more information is needed, tell. I never asked and I am quite a novice in asking and Android Development )

Body:
int random = rnd.nextInt(1 - 4);

the problem is with above line, because it can throw an Exception.

Try to catch this Exception with try {} catch {} blocks and you will see.

Also you can change your algorithm for example use list with colors

List<Color> colors = Arrays.asList(Color.BLUE, Color.RED, Color.YELLOW);
layout.setBackgroundColor(colors.get(rand.nextInt(colors.size() - 1));


问:
Jquery autocomplete _renderItem is not working
_renderItem is not executing at all, tried with console.log too no messages printed. Tried with 'autocomplete', 'ui-autocomplete', 'Autocomplete' attributes no hope.

In addition I could not understand the purpose of "response with map functions", so disabled it.

```<code>$(document).ready(function () {

myVars.shId = $('#dataVar').attr('sh-data');

///// search ////// http://jsbin.com/xavatajiku/edit?js,output
console.log(myVars.shId);
$('#name-list').autocomplete({

        source: function (request, response) {
            $.ajax({
                url: myVars.czbUrl,
                data: { searchText: request.term, maxResults: 10, shopId: myVars.shId },
                dataType: "json",
                success: function (data) {
                    console.log(data);
                    /*response($.map(data, function (item) {
                        console.log(data);
                        return {

                            value: item.product_name,
                            avatar: item.pfimage_thumb,
                            rep: item.product_name,
                            selectedId: item.url
                        };
                    }))*/
                }
            })
        },
        select: function (event, ui) {

                             alert(ui.item ? ("You picked '" + ui.item.label)
                                                      : "Nothing selected, input was " + this.value);

            return false;
        }
    }).autocomplete( "instance" )._renderItem = function (ul, item) {
        console.log('test');
        /*var inner_html = '<a><div class="list_item_container"><div class="image"><img src="' + item.pfimage_thumb + '"></div><div class="label"><h3> Reputation:  ' + item.volume + '</h3></div><div class="description">' + item.product_name + '</div></div></a><hr/>';
        return $("<li></li>")
                .data("ui-autocomplete-item", item)
                .append(inner_html)
                .appendTo(ul);*/
    };
</code>```

HTML:

```<code> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

<h4>search:<input type="text" id="name-list" /></h4>
</code>```

答:
A few small corrections and you should be on your way:

Example: https://jsfiddle.net/Twisty/3gm3sfem/

JavaScript

```<code>$(function() {
  var myData = [{
    product_name: "Name 1",
    pfimage_thumb: "thumb1.jpg",
    url: "url1"
  }, {
    product_name: "Name 2",
    pfimage_thumb: "thumb2.jpg",
    url: "url2"
  }, {
    product_name: "Name 3",
    pfimage_thumb: "thumb3.jpg",
    url: "url3"
  }];
  $('#name-list').autocomplete({
    source: function(request, response) {
      $.ajax({
        url: "/echo/json/",
        data: {
          json: JSON.stringify(myData)
        },
        dataType: "json",
        type: "POST",
        success: function(data) {
          console.log(data);
          response(data);
        }
      })
    },
    select: function(event, ui) {
      alert(ui.item ? ("You picked '" + ui.item.label) : "Nothing selected, input was " + this.value);
      return false;
    }
  }).autocomplete("instance")._renderItem = function(ul, item) {
    console.log('test');
    var item = $('<div class="list_item_container"><div class="image"><img src="' + item.pfimage_thumb + '"></div><div class="label"><h3> Reputation:  ' + item.volume + '</h3></div><div class="description">' + item.product_name + '</div></div>')
    return $("<li>").append(item).appendTo(ul);
  };
});
</code>```

If your data is coming back, pass it to response() to ensure that the menmu get rendered. You do not need  since select will be fired either way.

Body:
_renderItem is not executing at all, tried with console.log too no messages printed. Tried with 'autocomplete', 'ui-autocomplete', 'Autocomplete' attributes no hope.

In addition I could not understand the purpose of "response with map functions", so disabled it.

$(document).ready(function () {

myVars.shId = $('#dataVar').attr('sh-data');

///// search ////// http://jsbin.com/xavatajiku/edit?js,output
console.log(myVars.shId);
$('#name-list').autocomplete({

        source: function (request, response) {
            $.ajax({
                url: myVars.czbUrl,
                data: { searchText: request.term, maxResults: 10, shopId: myVars.shId },
                dataType: "json",
                success: function (data) {
                    console.log(data);
                    /*response($.map(data, function (item) {
                        console.log(data);
                        return {

                            value: item.product_name,
                            avatar: item.pfimage_thumb,
                            rep: item.product_name,
                            selectedId: item.url
                        };
                    }))*/
                }
            })
        },
        select: function (event, ui) {

                             alert(ui.item ? ("You picked '" + ui.item.label)
                                                      : "Nothing selected, input was " + this.value);

            return false;
        }
    }).autocomplete( "instance" )._renderItem = function (ul, item) {
        console.log('test');
        /*var inner_html = '

 Reputation:  ' + item.volume + '

' + item.product_name + '

';
        return $("

")
                .data("ui-autocomplete-item", item)
                .append(inner_html)
                .appendTo(ul);*/
    };

HTML:

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

search:<input type="text" id="name-list" />

Body:
A few small corrections and you should be on your way:

Example: https://jsfiddle.net/Twisty/3gm3sfem/

JavaScript

$(function() {
  var myData = [{
    product_name: "Name 1",
    pfimage_thumb: "thumb1.jpg",
    url: "url1"
  }, {
    product_name: "Name 2",
    pfimage_thumb: "thumb2.jpg",
    url: "url2"
  }, {
    product_name: "Name 3",
    pfimage_thumb: "thumb3.jpg",
    url: "url3"
  }];
  $('#name-list').autocomplete({
    source: function(request, response) {
      $.ajax({
        url: "/echo/json/",
        data: {
          json: JSON.stringify(myData)
        },
        dataType: "json",
        type: "POST",
        success: function(data) {
          console.log(data);
          response(data);
        }
      })
    },
    select: function(event, ui) {
      alert(ui.item ? ("You picked '" + ui.item.label) : "Nothing selected, input was " + this.value);
      return false;
    }
  }).autocomplete("instance")._renderItem = function(ul, item) {
    console.log('test');
    var item = $('<div class="list_item_container"><div class="image"><img src="' + item.pfimage_thumb + '"></div><div class="label"><h3> Reputation:  ' + item.volume + '</h3></div><div class="description">' + item.product_name + '</div></div>')
    return $("<li>").append(item).appendTo(ul);
  };
});

If your data is coming back, pass it to response() to ensure that the menmu get rendered. You do not need <a> since select will be fired either way.


问:
Getting 500 internal server error while Deploying Flask App on AWS EBS
I'm trying to deploy my working flask app to AWS, but it is giving internal server error 500. I did attached the error log in the end also. I have python 2.7 environment for beanstalk and the same for my virtual environment. I have all the needed packages in pip list and requirements.txt.

```<code>from flask import Flask, flash, render_template, request, session
from flaskext.mysql import MySQL
import os

application = Flask(__name__)

mysql = MySQL()
application.config['MYSQL_DATABASE_USER'] = 'user'
application.config['MYSQL_DATABASE_PASSWORD'] = 'password'
application.config['MYSQL_DATABASE_DB'] = 'nilesh'
application.config['MYSQL_DATABASE_HOST'] = 'nilesh-practice.us-west-2.rds.amazonaws.com'
mysql.init_app(application)

conn = mysql.connect()
cursor = conn.cursor()

cursor.execute("SELECT first_name from nilesh123.login_user")
first = cursor.fetchall()

cursor.execute("SELECT last_name from nilesh123.login_user")
last = cursor.fetchall()

@application.route('/')
def home():
    if not session.get('logged_in'):
        return render_template('login.html')
    else:
        return render_template('search.html', first=first, last=last)

@application.route('/login', methods=['POST'])
def do_admin_login():
    if request.form['password'] == 'password' and request.form['username'] == 'admin':
        session['logged_in'] = True
    else:
        flash('Wrong Password!')
    return home()

@application.route("/logout")
def logout():
    session['logged_in'] = False
    return home()

@application.route('/search', methods=['POST'])
def search():
    if request.form['firstname'] != '' and request.form['lastname'] == '':
        sql = "SELECT * from nilesh123.login_user WHERE first_name = %s"
        cursor.execute(sql, request.form['firstname'])
        result = cursor.fetchall()
        return render_template('display.html', result=result)

    elif request.form['firstname'] == '' and request.form['lastname'] != '':
        last1 = request.form['lastname']
        sql = "SELECT * from nilesh123.login_user WHERE last_name = %s "
        cursor.execute(sql, request.form['lastname'])
        result = cursor.fetchall()
        return render_template('display.html', result=result)

    elif request.form['firstname'] != '' and request.form['lastname'] != '':
        cursor.execute("SELECT * from nilesh123.login_user WHERE last_name like 'request.form['lastname']' AND \
                  first_name like 'request.form['firstname']'")
        result = cursor.fetchall()
        return render_template('display.html', result=result)

    return render_template('search.html')

if __name__ == "__main__":
    application.secret_key = os.urandom(12)
    application.run(debug=True, host='0.0.0.0', port=4500)
</code>```

Error Log:

```<code>[Mon Jun 05 02:48:07.210177 2017] [:warn] [pid 3253] mod_wsgi: Compiled for Python/2.7.10.
[Mon Jun 05 02:48:07.210181 2017] [:warn] [pid 3253] mod_wsgi: Runtime using Python/2.7.12.
[Mon Jun 05 02:48:07.211976 2017] [mpm_prefork:notice] [pid 3253] AH00163: Apache/2.4.25 (Amazon) mod_wsgi/3.5 Python/2.7.12 configured -- resuming normal operations
[Mon Jun 05 02:48:07.211988 2017] [core:notice] [pid 3253] AH00094: Command line: '/usr/sbin/httpd -D FOREGROUND'
[Mon Jun 05 02:48:19.956456 2017] [:error] [pid 3258] [remote 127.0.0.1:27151] mod_wsgi (pid=3258): Target WSGI script '/opt/python/current/app/application.py' cannot be loaded as Python module.
[Mon Jun 05 02:48:19.956485 2017] [:error] [pid 3258] [remote 127.0.0.1:27151] mod_wsgi (pid=3258): Exception occurred processing WSGI script '/opt/python/current/app/application.py'.
[Mon Jun 05 02:48:19.956506 2017] [:error] [pid 3258] [remote 127.0.0.1:27151] Traceback (most recent call last):
[Mon Jun 05 02:48:19.956518 2017] [:error] [pid 3258] [remote 127.0.0.1:27151]   File "/opt/python/current/app/application.py", line 14, in <module>
[Mon Jun 05 02:48:19.956572 2017] [:error] [pid 3258] [remote 127.0.0.1:27151]     conn = mysql.connect()
[Mon Jun 05 02:48:19.956582 2017] [:error] [pid 3258] [remote 127.0.0.1:27151]   File "/opt/python/run/venv/lib/python2.7/site-packages/flaskext/mysql.py", line 53, in connect
[Mon Jun 05 02:48:19.956622 2017] [:error] [pid 3258] [remote 127.0.0.1:27151]     return pymysql.connect(**self.connect_args)
[Mon Jun 05 02:48:19.956630 2017] [:error] [pid 3258] [remote 127.0.0.1:27151]   File "/opt/python/run/venv/lib/python2.7/site-packages/pymysql/__init__.py", line 90, in Connect
[Mon Jun 05 02:48:19.956675 2017] [:error] [pid 3258] [remote 127.0.0.1:27151]     return Connection(*args, **kwargs)
[Mon Jun 05 02:48:19.956683 2017] [:error] [pid 3258] [remote 127.0.0.1:27151]   File "/opt/python/run/venv/lib/python2.7/site-packages/pymysql/connections.py", line 706, in __init__
[Mon Jun 05 02:48:19.956706 2017] [:error] [pid 3258] [remote 127.0.0.1:27151]     self.connect()
[Mon Jun 05 02:48:19.956711 2017] [:error] [pid 3258] [remote 127.0.0.1:27151]   File "/opt/python/run/venv/lib/python2.7/site-packages/pymysql/connections.py", line 963, in connect
[Mon Jun 05 02:48:19.956732 2017] [:error] [pid 3258] [remote 127.0.0.1:27151]     raise exc
[Mon Jun 05 02:48:19.956748 2017] [:error] [pid 3258] [remote 127.0.0.1:27151] OperationalError: (2003, "Can't connect to MySQL server on 'nilesh-practice.ccajuffzgfk9.us-west-2.rds.amazonaws.com' (timed out)")
[Mon Jun 05 02:48:30.066771 2017] [:error] [pid 3258] [remote 127.0.0.1:27151] mod_wsgi (pid=3258): Target WSGI script '/opt/python/current/app/application.py' cannot be loaded as Python module.
[Mon Jun 05 02:48:30.066828 2017] [:error] [pid 3258] [remote 127.0.0.1:27151] mod_wsgi (pid=3258): Exception occurred processing WSGI script '/opt/python/current/app/application.py'.
[Mon Jun 05 02:48:30.066850 2017] [:error] [pid 3258] [remote 127.0.0.1:27151] Traceback (most recent call last):
[Mon Jun 05 02:48:30.066863 2017] [:error] [pid 3258] [remote 127.0.0.1:27151]   File "/opt/python/current/app/application.py", line 14, in <module>
[Mon Jun 05 02:48:30.066881 2017] [:error] [pid 3258] [remote 127.0.0.1:27151]     conn = mysql.connect()
[Mon Jun 05 02:48:30.066888 2017] [:error] [pid 3258] [remote 127.0.0.1:27151]   File "/opt/python/run/venv/lib/python2.7/site-packages/flaskext/mysql.py", line 53, in connect
[Mon Jun 05 02:48:30.066898 2017] [:error] [pid 3258] [remote 127.0.0.1:27151]     return pymysql.connect(**self.connect_args)
[Mon Jun 05 02:48:30.066906 2017] [:error] [pid 3258] [remote 127.0.0.1:27151]   File "/opt/python/run/venv/lib/python2.7/site-packages/pymysql/__init__.py", line 90, in Connect
[Mon Jun 05 02:48:30.066915 2017] [:error] [pid 3258] [remote 127.0.0.1:27151]     return Connection(*args, **kwargs)
[Mon Jun 05 02:48:30.066920 2017] [:error] [pid 3258] [remote 127.0.0.1:27151]   File "/opt/python/run/venv/lib/python2.7/site-packages/pymysql/connections.py", line 706, in __init__
[Mon Jun 05 02:48:30.066928 2017] [:error] [pid 3258] [remote 127.0.0.1:27151]     self.connect()
[Mon Jun 05 02:48:30.066932 2017] [:error] [pid 3258] [remote 127.0.0.1:27151]   File "/opt/python/run/venv/lib/python2.7/site-packages/pymysql/connections.py", line 963, in connect
[Mon Jun 05 02:48:30.066939 2017] [:error] [pid 3258] [remote 127.0.0.1:27151]     raise exc
[Mon Jun 05 02:48:30.066953 2017] [:error] [pid 3258] [remote 127.0.0.1:27151] OperationalError: (2003, "Can't connect to MySQL server on 'nilesh-practice.ccajuffzgfk9.us-west-2.rds.amazonaws.com' (timed out)")
</code>```

答:
About MySQL,

Can you try:

telnet nilesh-practice.ccajuffzgfk9.us-west-2.rds.amazonaws.com 3306

Connect from the EC2 instance to your RDS MySql.

If both have problems, you must check:

Security groups if you have permissions to connect to RDS from EC2.

If RDS is in a different region you must enable it to be public available.

Hope it helps you.

Body:
I'm trying to deploy my working flask app to AWS, but it is giving internal server error 500. I did attached the error log in the end also. I have python 2.7 environment for beanstalk and the same for my virtual environment. I have all the needed packages in pip list and requirements.txt.

from flask import Flask, flash, render_template, request, session
from flaskext.mysql import MySQL
import os

application = Flask(__name__)

mysql = MySQL()
application.config['MYSQL_DATABASE_USER'] = 'user'
application.config['MYSQL_DATABASE_PASSWORD'] = 'password'
application.config['MYSQL_DATABASE_DB'] = 'nilesh'
application.config['MYSQL_DATABASE_HOST'] = 'nilesh-practice.us-west-2.rds.amazonaws.com'
mysql.init_app(application)

conn = mysql.connect()
cursor = conn.cursor()

cursor.execute("SELECT first_name from nilesh123.login_user")
first = cursor.fetchall()

cursor.execute("SELECT last_name from nilesh123.login_user")
last = cursor.fetchall()

@application.route('/')
def home():
    if not session.get('logged_in'):
        return render_template('login.html')
    else:
        return render_template('search.html', first=first, last=last)

@application.route('/login', methods=['POST'])
def do_admin_login():
    if request.form['password'] == 'password' and request.form['username'] == 'admin':
        session['logged_in'] = True
    else:
        flash('Wrong Password!')
    return home()

@application.route("/logout")
def logout():
    session['logged_in'] = False
    return home()

@application.route('/search', methods=['POST'])
def search():
    if request.form['firstname'] != '' and request.form['lastname'] == '':
        sql = "SELECT * from nilesh123.login_user WHERE first_name = %s"
        cursor.execute(sql, request.form['firstname'])
        result = cursor.fetchall()
        return render_template('display.html', result=result)

    elif request.form['firstname'] == '' and request.form['lastname'] != '':
        last1 = request.form['lastname']
        sql = "SELECT * from nilesh123.login_user WHERE last_name = %s "
        cursor.execute(sql, request.form['lastname'])
        result = cursor.fetchall()
        return render_template('display.html', result=result)

    elif request.form['firstname'] != '' and request.form['lastname'] != '':
        cursor.execute("SELECT * from nilesh123.login_user WHERE last_name like 'request.form['lastname']' AND \
                  first_name like 'request.form['firstname']'")
        result = cursor.fetchall()
        return render_template('display.html', result=result)

    return render_template('search.html')

if __name__ == "__main__":
    application.secret_key = os.urandom(12)
    application.run(debug=True, host='0.0.0.0', port=4500)

Error Log:

[Mon Jun 05 02:48:07.210177 2017] [:warn] [pid 3253] mod_wsgi: Compiled for Python/2.7.10.
[Mon Jun 05 02:48:07.210181 2017] [:warn] [pid 3253] mod_wsgi: Runtime using Python/2.7.12.
[Mon Jun 05 02:48:07.211976 2017] [mpm_prefork:notice] [pid 3253] AH00163: Apache/2.4.25 (Amazon) mod_wsgi/3.5 Python/2.7.12 configured -- resuming normal operations
[Mon Jun 05 02:48:07.211988 2017] [core:notice] [pid 3253] AH00094: Command line: '/usr/sbin/httpd -D FOREGROUND'
[Mon Jun 05 02:48:19.956456 2017] [:error] [pid 3258] [remote 127.0.0.1:27151] mod_wsgi (pid=3258): Target WSGI script '/opt/python/current/app/application.py' cannot be loaded as Python module.
[Mon Jun 05 02:48:19.956485 2017] [:error] [pid 3258] [remote 127.0.0.1:27151] mod_wsgi (pid=3258): Exception occurred processing WSGI script '/opt/python/current/app/application.py'.
[Mon Jun 05 02:48:19.956506 2017] [:error] [pid 3258] [remote 127.0.0.1:27151] Traceback (most recent call last):
[Mon Jun 05 02:48:19.956518 2017] [:error] [pid 3258] [remote 127.0.0.1:27151]   File "/opt/python/current/app/application.py", line 14, in <module>
[Mon Jun 05 02:48:19.956572 2017] [:error] [pid 3258] [remote 127.0.0.1:27151]     conn = mysql.connect()
[Mon Jun 05 02:48:19.956582 2017] [:error] [pid 3258] [remote 127.0.0.1:27151]   File "/opt/python/run/venv/lib/python2.7/site-packages/flaskext/mysql.py", line 53, in connect
[Mon Jun 05 02:48:19.956622 2017] [:error] [pid 3258] [remote 127.0.0.1:27151]     return pymysql.connect(**self.connect_args)
[Mon Jun 05 02:48:19.956630 2017] [:error] [pid 3258] [remote 127.0.0.1:27151]   File "/opt/python/run/venv/lib/python2.7/site-packages/pymysql/__init__.py", line 90, in Connect
[Mon Jun 05 02:48:19.956675 2017] [:error] [pid 3258] [remote 127.0.0.1:27151]     return Connection(*args, **kwargs)
[Mon Jun 05 02:48:19.956683 2017] [:error] [pid 3258] [remote 127.0.0.1:27151]   File "/opt/python/run/venv/lib/python2.7/site-packages/pymysql/connections.py", line 706, in __init__
[Mon Jun 05 02:48:19.956706 2017] [:error] [pid 3258] [remote 127.0.0.1:27151]     self.connect()
[Mon Jun 05 02:48:19.956711 2017] [:error] [pid 3258] [remote 127.0.0.1:27151]   File "/opt/python/run/venv/lib/python2.7/site-packages/pymysql/connections.py", line 963, in connect
[Mon Jun 05 02:48:19.956732 2017] [:error] [pid 3258] [remote 127.0.0.1:27151]     raise exc
[Mon Jun 05 02:48:19.956748 2017] [:error] [pid 3258] [remote 127.0.0.1:27151] OperationalError: (2003, "Can't connect to MySQL server on 'nilesh-practice.ccajuffzgfk9.us-west-2.rds.amazonaws.com' (timed out)")
[Mon Jun 05 02:48:30.066771 2017] [:error] [pid 3258] [remote 127.0.0.1:27151] mod_wsgi (pid=3258): Target WSGI script '/opt/python/current/app/application.py' cannot be loaded as Python module.
[Mon Jun 05 02:48:30.066828 2017] [:error] [pid 3258] [remote 127.0.0.1:27151] mod_wsgi (pid=3258): Exception occurred processing WSGI script '/opt/python/current/app/application.py'.
[Mon Jun 05 02:48:30.066850 2017] [:error] [pid 3258] [remote 127.0.0.1:27151] Traceback (most recent call last):
[Mon Jun 05 02:48:30.066863 2017] [:error] [pid 3258] [remote 127.0.0.1:27151]   File "/opt/python/current/app/application.py", line 14, in <module>
[Mon Jun 05 02:48:30.066881 2017] [:error] [pid 3258] [remote 127.0.0.1:27151]     conn = mysql.connect()
[Mon Jun 05 02:48:30.066888 2017] [:error] [pid 3258] [remote 127.0.0.1:27151]   File "/opt/python/run/venv/lib/python2.7/site-packages/flaskext/mysql.py", line 53, in connect
[Mon Jun 05 02:48:30.066898 2017] [:error] [pid 3258] [remote 127.0.0.1:27151]     return pymysql.connect(**self.connect_args)
[Mon Jun 05 02:48:30.066906 2017] [:error] [pid 3258] [remote 127.0.0.1:27151]   File "/opt/python/run/venv/lib/python2.7/site-packages/pymysql/__init__.py", line 90, in Connect
[Mon Jun 05 02:48:30.066915 2017] [:error] [pid 3258] [remote 127.0.0.1:27151]     return Connection(*args, **kwargs)
[Mon Jun 05 02:48:30.066920 2017] [:error] [pid 3258] [remote 127.0.0.1:27151]   File "/opt/python/run/venv/lib/python2.7/site-packages/pymysql/connections.py", line 706, in __init__
[Mon Jun 05 02:48:30.066928 2017] [:error] [pid 3258] [remote 127.0.0.1:27151]     self.connect()
[Mon Jun 05 02:48:30.066932 2017] [:error] [pid 3258] [remote 127.0.0.1:27151]   File "/opt/python/run/venv/lib/python2.7/site-packages/pymysql/connections.py", line 963, in connect
[Mon Jun 05 02:48:30.066939 2017] [:error] [pid 3258] [remote 127.0.0.1:27151]     raise exc
[Mon Jun 05 02:48:30.066953 2017] [:error] [pid 3258] [remote 127.0.0.1:27151] OperationalError: (2003, "Can't connect to MySQL server on 'nilesh-practice.ccajuffzgfk9.us-west-2.rds.amazonaws.com' (timed out)")


答:
```<code>int random = rnd.nextInt(4);
</code>```

OR

```<code>int random = rnd.nextInt(3);
</code>```

Title: Why does my application stop working?

Body:
int random = rnd.nextInt(4);

OR

int random = rnd.nextInt(3);


问:
Cut JS string present in an array at every occurrance of a particular substring and append to same array
Note:
At this point in time, I'm unable to word the question title better. If someone is able to put it accross better, please go right ahead!

What I have:

```<code>var array = ["authentication.$.order", "difference.$.user.$.otherinformation", ... , ...]
</code>```

What I need:

```<code>["authentication", "authentication.$", "authentication.$.order",
"difference", "difference.$", "difference.$.user", "difference.$.user.$",
"difference.$.user.$.otherinformation"]
</code>```

Basically, wherevever I see .$., I need to preserve it, then append everything before the occourrence of .$. along with everything before the occourrence of .$

Example:

difference.$.user.$.otherinformation should be parsed to contain:

```<code>difference
difference.$
difference.$.user
difference.$.user.$
difference.$.user.$.otherinformation
</code>```

I'm strongly feeling that some sort of recursion is to be involved here, but have not progressed in that direction yet.

Below is my implementation for the same, but unfortunately, my when my substring matches the first occourrence of .$., it stops and does not proceed to further check for other occurrences of .$. in the same string.

How best can I take this to closure?

Current flawed implementation:

```<code>for(var i=0; i<array.length; i++){
    //  next, replace all array field references with $ as that is what autoform's pick() requires
    //  /\.\d+\./g,".$." ==> replace globally .[number]. with .$.
    array[i] = array[i].replace(/\.\d+\./g,".$.");
        if(array[i].substring(0, array[i].lastIndexOf('.$.'))){
            console.log("Substring without .$.  " + array[i].substring(0, array[i].indexOf('.$.')));
            console.log("Substring with .$ " + array[i].substring(0, array[i].indexOf('.$.')).concat(".$"));
            array.push(array[i].substring(0, array[i].indexOf('.$.')).concat(".$"));
            array.push(array[i].substring(0, array[i].indexOf('.$.')));
            }
        }
    // finally remove any duplicates if any
    array = _.uniq(array);
</code>```

答:
Actually recursion is unnecessary for this problem. You can use regular loop with subloop instead.

All you need is:

split each occurence in the array into substrings;

build a series of accumulated values from these substrings;

replace the current element of the array with this series.

Moreover, in order to make replacement to work properly you have to iterate the array in reverse order. BTW in this case you don't need to remove duplicates in the array.

So the code should look like this:

var array = ["authentication.$.order", "difference.$.user.$.otherinformation"];

var SEP = '.$.';
for (var i = array.length-1; i >= 0; i--){
    var v = array[i];
    var subs = v.replace(/\.\d+\./g, SEP).split(SEP)
    if (subs.length <= 1) continue;
    var acc = subs[0], elems = [acc];
    for (var n = subs.length-1, j = 0; j < n; j++) {
        elems[j * 2 + 1] = (acc += SEP);
        elems[j * 2 + 2] = (acc += subs[j]);
    }
    array.splice.apply(array, [i, 1].concat(elems));
}
console.log(array);```

Body:
Note:
At this point in time, I'm unable to word the question title better. If someone is able to put it accross better, please go right ahead!

What I have:

var array = ["authentication.$.order", "difference.$.user.$.otherinformation", ... , ...]

What I need:

["authentication", "authentication.$", "authentication.$.order",
"difference", "difference.$", "difference.$.user", "difference.$.user.$",
"difference.$.user.$.otherinformation"]

Basically, wherevever I see .$., I need to preserve it, then append everything before the occourrence of .$. along with everything before the occourrence of .$

Example:

difference.$.user.$.otherinformation should be parsed to contain:

difference
difference.$
difference.$.user
difference.$.user.$
difference.$.user.$.otherinformation

I'm strongly feeling that some sort of recursion is to be involved here, but have not progressed in that direction yet.

Below is my implementation for the same, but unfortunately, my when my substring matches the first occourrence of .$., it stops and does not proceed to further check for other occurrences of .$. in the same string.

How best can I take this to closure?

Current flawed implementation:

for(var i=0; i<array.length; i++){
    //  next, replace all array field references with $ as that is what autoform's pick() requires
    //  /\.\d+\./g,".$." ==> replace globally .[number]. with .$.
    array[i] = array[i].replace(/\.\d+\./g,".$.");
        if(array[i].substring(0, array[i].lastIndexOf('.$.'))){
            console.log("Substring without .$.  " + array[i].substring(0, array[i].indexOf('.$.')));
            console.log("Substring with .$ " + array[i].substring(0, array[i].indexOf('.$.')).concat(".$"));
            array.push(array[i].substring(0, array[i].indexOf('.$.')).concat(".$"));
            array.push(array[i].substring(0, array[i].indexOf('.$.')));
            }
        }
    // finally remove any duplicates if any
    array = _.uniq(array);


问:
serve nginx cached content to browser based on backend response
Can I make request to tomcat or Apache server from Nginx, then after getting response from this request, i will decide either i have to serve from Nginx cache or forward to back end server(i.e Apache)</p>

答:
Using proxy_cache_use_stale in your servers will help.
You can use it like this

location / {
    ...
    proxy_cache_use_stale error timeout http_500 http_502 http_503 http_504;
}

read more here


问:
ZonedDateTime round trip via Jackson produces unequal ZonedDateTime
Given the following Unit tests:

```<code>@Test
public void zonedDateTimeCorrectlyRestoresItself() {

    // construct a new instance of ZonedDateTime
    ZonedDateTime now = ZonedDateTime.now(ZoneId.of("Z"));
    // offset = {ZoneOffset@3820} "Z"
    // zone   = {ZoneOffset@3820} "Z"

    String converted = now.toString();

    // restore an instance of ZonedDateTime from String
    ZonedDateTime restored = ZonedDateTime.parse(converted);
    // offset = {ZoneOffset@3820} "Z"
    // zone   = {ZoneOffset@3820} "Z"

    assertThat(now).isEqualTo(restored); // ALWAYS succeeds
}

@Test
public void jacksonIncorrectlyRestoresZonedDateTime()  {

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.findAndRegisterModules();
    objectMapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);

    // construct a new instance of ZonedDateTime
    ZonedDateTime now = ZonedDateTime.now(ZoneId.of("Z"));
    // offset = {ZoneOffset@3820} "Z"
    // zone   = {ZoneOffset@3820} "Z"

    String converted = objectMapper.writeValueAsString(now);

    // restore an instance of ZonedDateTime from String
    ZonedDateTime restored = objectMapper.readValue(converted, ZonedDateTime.class);
    // offset = {ZoneOffset@3820} "Z"
    // zone   = {ZoneOffset@3821} "UTC"

    assertThat(now).isEqualTo(restored); // NEVER succeeds
}
</code>```

And this workaround:

```<code>@Test
public void usingDifferentComparisonStrategySucceeds() throws Exception  {

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.findAndRegisterModules();
    objectMapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);

    // construct a new instance of ZonedDateTime
    ZonedDateTime now = ZonedDateTime.now(ZoneId.of("Z"));
    // offset = {ZoneOffset@3820} "Z"
    // zone   = {ZoneOffset@3820} "Z"

    String converted = objectMapper.writeValueAsString(now);

    // restore an instance of ZonedDateTime from String
    ZonedDateTime restored = objectMapper.readValue(converted, ZonedDateTime.class);
    // offset = {ZoneOffset@3820} "Z"
    // zone   = {ZoneOffset@3821} "UTC"

    // the comparison succeeds when a different comparison strategy is used
    // checks whether the instants in time are equal, not the java objects
    assertThat(now.isEqual(restored)).isTrue();
}
</code>```

I guess I'm trying to figure out why internally Jackson just doesn't call ZonedDateTime.parse()? Personally I think this is a bug with Jackson but I'm not confident enough to open an issue for it just yet without some feedback.

答:
Quoting Wikipedia for ISO 8601:

If the time is in UTC, add a Z directly after the time without a space. Z is the zone designator for the zero UTC offset. "09:30 UTC" is therefore represented as "09:30Z" or "0930Z". "14:45:15 UTC" would be "14:45:15Z" or "144515Z".

UTC time is also known as Zulu time, since Zulu is the NATO phonetic alphabet word for Z.

Z is not a Zone. UTC is the Zone, which is then represented using Z in a formatted string.

Don't ever use ZoneId.of("Z"). It's wrong.

Body:
Given the following Unit tests:

@Test
public void zonedDateTimeCorrectlyRestoresItself() {

    // construct a new instance of ZonedDateTime
    ZonedDateTime now = ZonedDateTime.now(ZoneId.of("Z"));
    // offset = {ZoneOffset@3820} "Z"
    // zone   = {ZoneOffset@3820} "Z"

    String converted = now.toString();

    // restore an instance of ZonedDateTime from String
    ZonedDateTime restored = ZonedDateTime.parse(converted);
    // offset = {ZoneOffset@3820} "Z"
    // zone   = {ZoneOffset@3820} "Z"

    assertThat(now).isEqualTo(restored); // ALWAYS succeeds
}

@Test
public void jacksonIncorrectlyRestoresZonedDateTime()  {

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.findAndRegisterModules();
    objectMapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);

    // construct a new instance of ZonedDateTime
    ZonedDateTime now = ZonedDateTime.now(ZoneId.of("Z"));
    // offset = {ZoneOffset@3820} "Z"
    // zone   = {ZoneOffset@3820} "Z"

    String converted = objectMapper.writeValueAsString(now);

    // restore an instance of ZonedDateTime from String
    ZonedDateTime restored = objectMapper.readValue(converted, ZonedDateTime.class);
    // offset = {ZoneOffset@3820} "Z"
    // zone   = {ZoneOffset@3821} "UTC"

    assertThat(now).isEqualTo(restored); // NEVER succeeds
}

And this workaround:

@Test
public void usingDifferentComparisonStrategySucceeds() throws Exception  {

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.findAndRegisterModules();
    objectMapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);

    // construct a new instance of ZonedDateTime
    ZonedDateTime now = ZonedDateTime.now(ZoneId.of("Z"));
    // offset = {ZoneOffset@3820} "Z"
    // zone   = {ZoneOffset@3820} "Z"

    String converted = objectMapper.writeValueAsString(now);

    // restore an instance of ZonedDateTime from String
    ZonedDateTime restored = objectMapper.readValue(converted, ZonedDateTime.class);
    // offset = {ZoneOffset@3820} "Z"
    // zone   = {ZoneOffset@3821} "UTC"

    // the comparison succeeds when a different comparison strategy is used
    // checks whether the instants in time are equal, not the java objects
    assertThat(now.isEqual(restored)).isTrue();
}

I guess I'm trying to figure out why internally Jackson just doesn't call ZonedDateTime.parse()? Personally I think this is a bug with Jackson but I'm not confident enough to open an issue for it just yet without some feedback.


问:
VBA to run only if filename = "xx"
I would like the below to run only if a filename in the filepath location equals "xx". As it is currently it still opens files <> "xx". What am I missing here?</p>

```<code>Sub UpdateMasterLog()
Dim MyFile As String
Dim LastRow As Long
Dim erow1
Dim Filepath1

If FileName = "XX" Then

Filepath1 = "Z:\test folder"
MyFile = Dir(Filepath1)

    Workbooks.Open (Filepath1 & MyFile)
    ActiveWorkbook.Worksheets("sheet1").Activate
    LastRow = Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
    Range("A2:P" & LastRow).Copy
    ActiveWorkbook.Close

    ActiveSheet.Paste Destination:=Worksheets("Sheet1").Range("C" & Rows.Count).End(xlUp).Offset(1, -2)

End If

End Sub
</code>```

答:
Try this:

```<code>Filepath1 = "Z:\test folder"
Do While fileName <> ""

     If filename = "xx" then
           Workbooks.Open (Filepath1 & MyFile)
           ActiveWorkbook.Worksheets("sheet1").Activate
           LastRow = Cells.Find("*", SearchOrder:=xlByRows,
           SearchDirection:=xlPrevious).Row
           Range("A2:P" & LastRow).Copy
           ActiveWorkbook.Close
           ActiveSheet.Paste Destination:=Worksheets("Sheet1").Range("C" & Rows.Count).End(xlUp).Offset(1, -2)
     End If

     Filepath1 = Dir()
Loop
</code>```

Tell me what happens / use  this for now. Best!

Title: VBA to run only if filename = "xx"

Body:
I would like the below to run only if a filename in the filepath location equals "xx". As it is currently it still opens files <> "xx". What am I missing here?

Sub UpdateMasterLog()
Dim MyFile As String
Dim LastRow As Long
Dim erow1
Dim Filepath1

If FileName = "XX" Then

Filepath1 = "Z:\test folder"
MyFile = Dir(Filepath1)

    Workbooks.Open (Filepath1 & MyFile)
    ActiveWorkbook.Worksheets("sheet1").Activate
    LastRow = Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
    Range("A2:P" & LastRow).Copy
    ActiveWorkbook.Close

    ActiveSheet.Paste Destination:=Worksheets("Sheet1").Range("C" & Rows.Count).End(xlUp).Offset(1, -2)

End If

End Sub

Body:
Try this:

Filepath1 = "Z:\test folder"
Do While fileName <> ""

     If filename = "xx" then
           Workbooks.Open (Filepath1 & MyFile)
           ActiveWorkbook.Worksheets("sheet1").Activate
           LastRow = Cells.Find("*", SearchOrder:=xlByRows,
           SearchDirection:=xlPrevious).Row
           Range("A2:P" & LastRow).Copy
           ActiveWorkbook.Close
           ActiveSheet.Paste Destination:=Worksheets("Sheet1").Range("C" & Rows.Count).End(xlUp).Offset(1, -2)
     End If

     Filepath1 = Dir()
Loop

Tell me what happens / use  this for now. Best!


问:
Convert a number into a Roman numeral in JavaScript
How can I convert integers into roman numerals?

```<code>function romanNumeralGenerator (int) {

}
</code>```

For example, see the following sample inputs and outputs:

```<code>1 = "I"
5 = "V"
10 = "X"
20 = "XX"
3999 = "MMMCMXCIX"
</code>```

Caveat: Only support numbers between 1 and 3999

答:
If it is just for display purpose, use the standard HTML with a bit of JS for the value (if needed) and CSS to make it inline:

ol.roman-lowercase,
ol.roman-uppercase {
  display: inline-flex;
  margin: 0;
  padding: 0;
}

ol.roman-lowercase {
  list-style: lower-roman inside;
}

ol.roman-uppercase {
  list-style: upper-roman inside;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ol class="roman-lowercase"><li value="4"></li></ol> <!-- iv. -->
<ol class="roman-uppercase"><li value="142"></li></ol> <!-- CXLII. --></code>```

Body:
How can I convert integers into roman numerals?

function romanNumeralGenerator (int) {

}

For example, see the following sample inputs and outputs:

1 = "I"
5 = "V"
10 = "X"
20 = "XX"
3999 = "MMMCMXCIX"

Caveat: Only support numbers between 1 and 3999

Body:
If it is just for display purpose, use the standard HTML with a bit of JS for the value (if needed) and CSS to make it inline:

ol.roman-lowercase,
ol.roman-uppercase {
  display: inline-flex;
  margin: 0;
  padding: 0;
}

ol.roman-lowercase {
  list-style: lower-roman inside;
}

ol.roman-uppercase {
  list-style: upper-roman inside;
}

<ol class="roman-lowercase"><li value="4"></li></ol> <!-- iv. -->
<ol class="roman-uppercase"><li value="142"></li></ol> <!-- CXLII. -->


问:
Convert array to WrappedArray
I have tried to use WrappedArray and initialize it by null

```<code>var classes:WrappedArray [String]= null
 var classe = ENTEleveClasses.apply(0)
         if(!classe.isEmpty()) {
           var cls = classe.split(",")
           for(c <- cls){
             classes =   classes :+ c  //  the error
           }
           classes
         }else ENTEleveClasses
</code>```

Error :

```<code>Caused by: java.lang.NullPointerException
    at comptesInvites.EleveENT$$anonfun$1.apply(EleveENT.scala:19)
    at comptesInvites.EleveENT$$anonfun$1.apply(EleveENT.scala:16)
    ... 16 more
</code>```

when I add an element a WrappedArray an Error occurred

Thanks

答:
when I add an element a WrappedArray an Error occurred

You're not adding an element to a WrappedArray, you're adding an element to the null value, which is indeed impossible, and generates a NPE.

To add an element to a WrappedArray, you have to actually provide one, so instead of var classes:WrappedArray [String]= null, use var classes:WrappedArray [String]= new WrappedArray() (I'm not actually sure what are the constructors for WrappedArray, you may have to change this !)

Title: Convert array to WrappedArray

Body:
I have tried to use WrappedArray and initialize it by null

var classes:WrappedArray [String]= null
 var classe = ENTEleveClasses.apply(0)
         if(!classe.isEmpty()) {
           var cls = classe.split(",")
           for(c <- cls){
             classes =   classes :+ c  //  the error
           }
           classes
         }else ENTEleveClasses

Error :

Caused by: java.lang.NullPointerException
    at comptesInvites.EleveENT$$anonfun$1.apply(EleveENT.scala:19)
    at comptesInvites.EleveENT$$anonfun$1.apply(EleveENT.scala:16)
    ... 16 more

when I add an element a WrappedArray an Error occurred

Thanks


问:
How to replace strings which match a regex pattern?
i have list with numbers. I want to extract all the numbers with consecutive digits like 444,888,1111 etc.. My following python code with regex is working exactly the way I wanted.

```<code>import re
numbers = ['44444', '123', '444', '454', '76587', '888', '9090', '1111', '321', '4321', '4563', '3333', '543', '765', '4567', '555', '99999', '11211','11']
conList = []

for num in numbers:
  if re.search(r'^(\d)\1+$',num):
    conList.append(num)

print('conList :',conList)
</code>```

Result:

conList : ['44444', '444', '888', '1111', '3333', '555', '99999', '11']
```

Now I am trying to achieve the same result without using a regex pattern. How can I replace that regex pattern with some python code? (I am trying this only for educational purpose. I will post my answer if I got one.)

答:
Use a pythonic and fast approach of list comprehension:</p>

```<code>[i for i in numbers if len(set(i)) == 1]
</code>```

Body:
i have list with numbers. I want to extract all the numbers with consecutive digits like 444,888,1111 etc.. My following python code with regex is working exactly the way I wanted.

import re
numbers = ['44444', '123', '444', '454', '76587', '888', '9090', '1111', '321', '4321', '4563', '3333', '543', '765', '4567', '555', '99999', '11211','11']
conList = []

for num in numbers:
  if re.search(r'^(\d)\1+$',num):
    conList.append(num)

print('conList :',conList)

Result:

conList : ['44444', '444', '888', '1111', '3333', '555', '99999', '11']

Now I am trying to achieve the same result without using a regex pattern. How can I replace that regex pattern with some python code? (I am trying this only for educational purpose. I will post my answer if I got one.)

Body:
Use a pythonic and fast approach of list comprehension:

[i for i in numbers if len(set(i)) == 1]


答:
As stated by Bathsheba, your logic for the nextInt function is incorrect.

As detailed in the Oracle documentation for Random and nextInt(int n), the nextInt function "Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive)".

Therefore, you are trying to generate a number between 0 and -3, which causes an "IllegalArgumentException error", since 'n' is not positive.

One correct way to generate a random number between 1 (inclusive) and 4 (exclusive) is the following...

```<code>int random = rnd.nextInt(3) + 1
</code>```

'rnd.nextInt(2)' will generate either 0, 1, or 2

adding 1 to these options gives you the desired outputs of 1, 2, or 3

Title: Why does my application stop working?

Body:
As stated by Bathsheba, your logic for the nextInt function is incorrect.

As detailed in the Oracle documentation for Random and nextInt(int n), the nextInt function "Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive)".

Therefore, you are trying to generate a number between 0 and -3, which causes an "IllegalArgumentException error", since 'n' is not positive.

One correct way to generate a random number between 1 (inclusive) and 4 (exclusive) is the following...

int random = rnd.nextInt(3) + 1

'rnd.nextInt(2)' will generate either 0, 1, or 2

adding 1 to these options gives you the desired outputs of 1, 2, or 3


问:
Override open variable for class in Swift and SpriteKit for use in XCode's ActionEditor
I'm trying to make small platformer game, just in learning purposes. I've tried to animate character with array of SKTextures like this:

```<code>let animation: SKAction = SKAction.animate(
    with: frames.map {
        let texture : SKTexture = SKTexture(imageNamed: $0)
        texture.filteringMode = SKTextureFilteringMode.nearest

        return texture
    },
    timePerFrame: 0.15
)
</code>```

frames variable is array of SKTextures. I've used map to set filtering mode for each texture. This works fine and dandy, but than i've discovered that i can create animations (actions) in ActionEditor in XCode with AnimateWithTextures action. And here lies my problem. This is much more efficient, but i can't change filtering mode for textures in animation in ActionEditor. I've looked into SKTexture class and saw this:

```<code>open class SKTexture : NSObject, NSCopying, NSCoding {
    ...
    /**
    The filtering mode the texture should use when not drawn at native size. Defaults to SKTextureFilteringLinear.
    */
    open var filteringMode: SKTextureFilteringMode
    ...
}
</code>```

If i'm not mistaken open means that i can override variable, but i don't know how. I want to set default value of filteringMode to SKTextureFilteringMode.nearest for all SKTextures so ActionEditor will use textures with texture filtering set to nearest neighbor.

Also if you know how to set filtering mode for textures in specific action – i would like to know how to do it too. Thanks

答: ActionEditor is still very limited in features, you are going to have to write some kind of code behind to allow for texture filtering.  If you do not plan on scaling your sprites (Note I said sprite, not scene, these are two different behaviors), then I would not even worry about texture filtering, the time difference would be negligible.</p>

Body:
I'm trying to make small platformer game, just in learning purposes. I've tried to animate character with array of SKTextures like this:

let animation: SKAction = SKAction.animate(
    with: frames.map {
        let texture : SKTexture = SKTexture(imageNamed: $0)
        texture.filteringMode = SKTextureFilteringMode.nearest

        return texture
    },
    timePerFrame: 0.15
)

frames variable is array of SKTextures. I've used map to set filtering mode for each texture. This works fine and dandy, but than i've discovered that i can create animations (actions) in ActionEditor in XCode with AnimateWithTextures action. And here lies my problem. This is much more efficient, but i can't change filtering mode for textures in animation in ActionEditor. I've looked into SKTexture class and saw this:

open class SKTexture : NSObject, NSCopying, NSCoding {
    ...
    /**
    The filtering mode the texture should use when not drawn at native size. Defaults to SKTextureFilteringLinear.
    */
    open var filteringMode: SKTextureFilteringMode
    ...
}

If i'm not mistaken open means that i can override variable, but i don't know how. I want to set default value of filteringMode to SKTextureFilteringMode.nearest for all SKTextures so ActionEditor will use textures with texture filtering set to nearest neighbor.

Also if you know how to set filtering mode for textures in specific action – i would like to know how to do it too. Thanks


问:
Nib view differs from Simulator
My nib

My Simulator. I can't understand why constraints don't work

I think code does not have influence, however see it below:

```<code>func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

    if let headeView = Bundle.main.loadNibNamed("HeaderViewCell", owner: self, options: nil)?.first as? HeaderViewCell {

        //headeView.categoryLabel.text = "FFF"
        return headeView
    }

    return UIView()
}
</code>```

答:
When I start to make custom header, I saw video tutorial (https://youtu.be/gEoiiZZE6cw) where header based on UITableViewCell class. And you see result above.

I solved to try usual view and I got right result as below. Thanks all for answers

Title: Nib view differs from Simulator

Body:
My nib

My Simulator. I can't understand why constraints don't work

I think code does not have influence, however see it below:

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

    if let headeView = Bundle.main.loadNibNamed("HeaderViewCell", owner: self, options: nil)?.first as? HeaderViewCell {

        //headeView.categoryLabel.text = "FFF"
        return headeView
    }

    return UIView()
}


问:
How to apply security permissions to static files with ASP.NET MVC?
I'm trying to use ASP.NET MVC to have a web app that will take details about a parent item and allow uploads and sharing of files which are associated with and stored under the name of the parent item.

The files I want to protect are stored in this way:
~/Files/{Item-GUID}/{Filename}.{ext}

The Item-Guid can be used to query the db for security permissions for the item. (users are logged as AD SIDs)

I need to know how to have ASP.Net respond to file requests for these files in the path ~/Files/ and use the /Item-GUID/ to check security permissions before serving the file to the user, and throw authentication errors if the user is not logged in or does not have access to the parent item.

I would appreciate any links or advice on where should I start here.
Thanks In Advance.

答:
I use often create a custom permission class that derives from the  AuthorizeAttribute class. This is one way you can  create a custom permissions filter on any controller action.

```<code>public MyPermissionsFilter : AuthorizeAttribute
{
    private readonly string _permissionName;

    public PermissionsFilter(string permissionName)
    {
        _permissionName = permissionName;
    }
}
</code>```

Override the OnAuthorization method.

```<code>public override void OnAuthorization(AuthorizationContext filterContext)
{
    //Perform Check with _permissionName
   //Redirect to error / unauthorised
}
</code>```

Then decorate your controller action.

```<code>[HttpPost]
[PermissionsFilter("PermissionName")]
public void SaveFile(HttpPostedFileBase file)
{
  //Do file stuff
}
</code>```

I hope that's what you want and is of some help.

Addition : I've renamed GetFile to SaveFile.. and this is what is should have been.

I've also been thinking about this again and it may not be the best solution for you. If you need to check a users permissions to access a single file based upon it's GUID, you might be better having the security check called in the SaveFile method that receives the file base parameter. You can get the guid from the file name then to pass to the permissions check. If it fails then simply redirect to the appropriate view.

Body:
I use often create a custom permission class that derives from the  AuthorizeAttribute class. This is one way you can  create a custom permissions filter on any controller action.

public MyPermissionsFilter : AuthorizeAttribute
{
    private readonly string _permissionName;

    public PermissionsFilter(string permissionName)
    {
        _permissionName = permissionName;
    }
}

Override the OnAuthorization method.

public override void OnAuthorization(AuthorizationContext filterContext)
{
    //Perform Check with _permissionName
   //Redirect to error / unauthorised
}

Then decorate your controller action.

[HttpPost]
[PermissionsFilter("PermissionName")]
public void SaveFile(HttpPostedFileBase file)
{
  //Do file stuff
}

I hope that's what you want and is of some help.

Addition : I've renamed GetFile to SaveFile.. and this is what is should have been.

I've also been thinking about this again and it may not be the best solution for you. If you need to check a users permissions to access a single file based upon it's GUID, you might be better having the security check called in the SaveFile method that receives the file base parameter. You can get the guid from the file name then to pass to the permissions check. If it fails then simply redirect to the appropriate view.


Title: How to replace strings which match a regex pattern?

Body:
You can do this in one line using list comprehensions as the following:

numbers = ['44444', '123', '444', '454', '76587', '888', '9090', '1111', '321', '4321', '4563', '3333', '543', '765', '4567',
     '555', '99999', '11211', '11']
conList = [x for x in numbers if x.count(x[0]) == len(x)]
print conList

output:

['44444', '444', '888', '1111', '3333', '555', '99999', '11']


问:
synchronized method not working as synchronized
I have to create multiple client threads and each one has to login .and i have implemented user_login function as synchronized but when i am calling it in run method of thread ,multiple threads are accessing it same time.I want that only one client should do login first then second and so on...

```<code>import java.io.*;
import java.rmi.NotBoundException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.Scanner;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

class Login {

    private String username = "";                                                        //username of server manager
    private String password = "";                                                        //password of server manager
    private String record = "";
    private boolean flag = false;

    public synchronized String user_login() {

        Logger logger;                                                                //Reference to Logger class is generated
        Handler fileHandler;
        SimpleFormatter plainText;
        Scanner s;
        int thread_name = 0;
        try {//login details fetched from login.txt file
            BufferedReader br = new BufferedReader(new FileReader("D:/JAVA/assignment1/Login.txt"));
            s = new Scanner(System.in);
            System.out.println("Enter your username: ");
            username = s.nextLine();
            System.out.println("Enter your password: ");
            password = s.nextLine();

            Scanner scan;

            while ((record = br.readLine()) != null) {                    //records fetched line by line

                String[] split = record.split(" ");

                if (username.equals(split[0]) && password.equals(split[1])) //username and password compared with data fetched
                {
                    System.out.println(" LOGIN SUCCESSFULL for" + thread_name);
                    flag = true;
                    logger = Logger.getLogger(Logger.class.getName());
                    logger.setUseParentHandlers(false);
                    File f = new File("D:/JAVA/assignment1/" + username + ".txt");
                    if (!f.exists())
                        f.createNewFile();

                    fileHandler = new FileHandler("D:/JAVA/assignment1/" + username + ".txt", true);//File for writting log is opened in append mode
                    plainText = new SimpleFormatter();
                    fileHandler.setFormatter(plainText);
                    logger.addHandler(fileHandler);
                    logger.info("User " + username + "logged in");

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (flag == false) {
            System.out.println("LOGIN UNSUCCESSFULL!!!! ");
            System.out.println("Try again: ");
            user_login();                                                    //if login fails,user reenter his details
        }
        return username;
    }

}
public class Client_Thread extends Thread {
    static String username = "";                                             //username of server manager
                                                         //password of server manager
    String record = "";
    static String locationname;
    static boolean flag = false;
    Logger logger;                                                                //Reference to Logger class is generated

    int thread_name = 0;

    Client_Thread(int x) {
        thread_name = x;
    }

    @Override
    public void run()                                                //client thread statrs execution
    {
        System.out.println(this.thread_name);
            try {
            Login l = new Login();
            synchronized(l)
            {
                username = l.user_login();
            }
            locationname = username.substring(0, 3);
            if (locationname.equals("MTL"))                                //checks which server's manager logged in
            {
                Registry reg;
                reg = LocateRegistry.getRegistry(2964);
                ServerInterface ms = (ServerInterface) reg.lookup("Mtl");  //looks for reference Mtl in registry for montreal server

                Operations m = new Operations();
                m.Operations1(ms,username);                                    //performs the required function
                //logger.info(Logger.class.getName());
            } else if (locationname.equals("LVL")) {
                Registry reg = LocateRegistry.getRegistry(2965);
                ServerInterface ls = (ServerInterface) reg.lookup("Lvl"); //looks for reference Lvl in registry for laval server
                Operations m = new Operations();
                m.Operations1(ls,username);//performs the required function
            } else if (locationname.equals("DDO")) {
                Registry reg = LocateRegistry.getRegistry(2966);
                ServerInterface ds = (ServerInterface) reg.lookup("Ddo");    //looks for reference Ddo in registry for DDO server
                Operations m = new Operations();
                m.Operations1(ds,username);                           //performs the required function
            }
        } catch (IOException | NotBoundException e1) {
            e1.printStackTrace();
        }
    }
}

public class Client {
    static void test_case1()
    {
        for(int i=0;i<2;i++)
        {
            Client_Thread c = new Client_Thread(i);            //run the new client thread
            c.start();
        }
    }

    public static void main(String arg[]) throws RemoteException, NotBoundException {
    test_case1();
    }

}
</code>```

output is like this:-
0
1
Enter your username:
Enter your username:

but i should be like:-
Enter your username:
Enter your password:

答:
Each one of your threads creates its own Login object.

Therefore, synchronization has no effect, because each thread synchronizes on a different instance of your Login object.

In order to achieve the desired behavior you have to instantiate only one Login object and pass it to all your threads to use.

Body:
I have to create multiple client threads and each one has to login .and i have implemented user_login function as synchronized but when i am calling it in run method of thread ,multiple threads are accessing it same time.I want that only one client should do login first then second and so on...

import java.io.*;
import java.rmi.NotBoundException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.Scanner;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

class Login {

    private String username = "";                                                        //username of server manager
    private String password = "";                                                        //password of server manager
    private String record = "";
    private boolean flag = false;

    public synchronized String user_login() {

        Logger logger;                                                                //Reference to Logger class is generated
        Handler fileHandler;
        SimpleFormatter plainText;
        Scanner s;
        int thread_name = 0;
        try {//login details fetched from login.txt file
            BufferedReader br = new BufferedReader(new FileReader("D:/JAVA/assignment1/Login.txt"));
            s = new Scanner(System.in);
            System.out.println("Enter your username: ");
            username = s.nextLine();
            System.out.println("Enter your password: ");
            password = s.nextLine();

            Scanner scan;

            while ((record = br.readLine()) != null) {                    //records fetched line by line

                String[] split = record.split(" ");

                if (username.equals(split[0]) && password.equals(split[1])) //username and password compared with data fetched
                {
                    System.out.println(" LOGIN SUCCESSFULL for" + thread_name);
                    flag = true;
                    logger = Logger.getLogger(Logger.class.getName());
                    logger.setUseParentHandlers(false);
                    File f = new File("D:/JAVA/assignment1/" + username + ".txt");
                    if (!f.exists())
                        f.createNewFile();

                    fileHandler = new FileHandler("D:/JAVA/assignment1/" + username + ".txt", true);//File for writting log is opened in append mode
                    plainText = new SimpleFormatter();
                    fileHandler.setFormatter(plainText);
                    logger.addHandler(fileHandler);
                    logger.info("User " + username + "logged in");

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (flag == false) {
            System.out.println("LOGIN UNSUCCESSFULL!!!! ");
            System.out.println("Try again: ");
            user_login();                                                    //if login fails,user reenter his details
        }
        return username;
    }

}
public class Client_Thread extends Thread {
    static String username = "";                                             //username of server manager
                                                         //password of server manager
    String record = "";
    static String locationname;
    static boolean flag = false;
    Logger logger;                                                                //Reference to Logger class is generated

    int thread_name = 0;

    Client_Thread(int x) {
        thread_name = x;
    }

    @Override
    public void run()                                                //client thread statrs execution
    {
        System.out.println(this.thread_name);
            try {
            Login l = new Login();
            synchronized(l)
            {
                username = l.user_login();
            }
            locationname = username.substring(0, 3);
            if (locationname.equals("MTL"))                                //checks which server's manager logged in
            {
                Registry reg;
                reg = LocateRegistry.getRegistry(2964);
                ServerInterface ms = (ServerInterface) reg.lookup("Mtl");  //looks for reference Mtl in registry for montreal server

                Operations m = new Operations();
                m.Operations1(ms,username);                                    //performs the required function
                //logger.info(Logger.class.getName());
            } else if (locationname.equals("LVL")) {
                Registry reg = LocateRegistry.getRegistry(2965);
                ServerInterface ls = (ServerInterface) reg.lookup("Lvl"); //looks for reference Lvl in registry for laval server
                Operations m = new Operations();
                m.Operations1(ls,username);//performs the required function
            } else if (locationname.equals("DDO")) {
                Registry reg = LocateRegistry.getRegistry(2966);
                ServerInterface ds = (ServerInterface) reg.lookup("Ddo");    //looks for reference Ddo in registry for DDO server
                Operations m = new Operations();
                m.Operations1(ds,username);                           //performs the required function
            }
        } catch (IOException | NotBoundException e1) {
            e1.printStackTrace();
        }
    }
}

public class Client {
    static void test_case1()
    {
        for(int i=0;i<2;i++)
        {
            Client_Thread c = new Client_Thread(i);            //run the new client thread
            c.start();
        }
    }

    public static void main(String arg[]) throws RemoteException, NotBoundException {
    test_case1();
    }

}

output is like this:-
0
1
Enter your username:
Enter your username:

but i should be like:-
Enter your username:
Enter your password: