问:
Creating confusion matrix from multiple .csv files
I have a lot of .csv files with the following format.

```<code>338,800
338,550
339,670
340,600
327,500
301,430
299,350
284,339
284,338
283,335
283,330
283,310
282,310
282,300
282,300
283,290
</code>```

From column 1, I wanted to read current row and compare it with the value of the previous row. If it is greater OR equal, continue comparing and if the value of the current cell is smaller than the previous row - then i divide the current value with the previous value and proceed. For example in the table given above: the smaller value we will get depending on my requirement from Column 1 is 327 (because 327 is smaller than the previous value 340) - and then we divide 327 by 340 and we get the value 0.96. My python script should exit right after we print the criteria (A) as given below.

```<code>from __future__ import division
import csv

def category(val):
    if 0.8 < val <= 0.9:
        return "A"
    if abs(val - 0.7) < 1e-10:
        return "B"
    if 0.5 < val < 0.7:
        return "C"
    if abs(val - 0.5) < 1e-10:
        return "E"
    return "D"

    with open("test.csv", "r") as csvfile:
    ff = csv.reader(csvfile)

    results = []
    previous_value = 0
    for col1, col2 in ff:
        if not col1.isdigit():
            continue
        value = int(col1)
        if value >= previous_value:
            previous_value = value
            continue
        else:
            result =  int(col1)/ int(previous_value)
            results.append(result)
            print category(result)
            previous_value = value
    print (results)
    print (sum(results))
    print (category(sum(results) / len(results)))
</code>```

Finally, i want to run my scrip for all the .csv files i have in the current directory and build a confusion matrix like the following. Let's say A1.csv, A2.csv, A3.csv are supposed (or predicted) to print A, B1.csv, B2.csv, B3.csv are supposed (or predicted) to print B and C1.csv, C2.csv and C3.csv are supposed (or predicted) to print C, ... etc. How can we automatically create a confusion matrix from multiple .csv files for example like the following using Python?

As it is shown below, the colored blocks of the matrix (row-labels) will show us the number of counts of A (count of true values for A), B (count of true values for b) and C (count of true values for C), ..etc from the control logic of our function category()- given above. The column labels from the control logic we have inside the if-else statement (A, B, C, D and E).

答:
Using Scikit-Learn is the best option to go for in your case as it provides a confusion_matrix function. Here is an approach you can easily extend.

```<code>from sklearn.metrics import confusion_matrix

# Read your csv files
with open('A1.csv', 'r') as readFile:
    true_values = [int(ff) for ff in readFile]
with open('B1.csv', 'r') as readFile:
    predictions = [int(ff) for ff in readFile]

# Produce the confusion matrix
confusionMatrix = confusion_matrix(true_values, predictions)

print(confusionMatrix)
</code>```

This is the output you would expect.

```<code>[[0 2]
 [0 2]]
</code>```

For more hint - check out the following link:

How to write a confusion matrix in Python?

Body:
I have a lot of .csv files with the following format.

338,800
338,550
339,670
340,600
327,500
301,430
299,350
284,339
284,338
283,335
283,330
283,310
282,310
282,300
282,300
283,290

From column 1, I wanted to read current row and compare it with the value of the previous row. If it is greater OR equal, continue comparing and if the value of the current cell is smaller than the previous row - then i divide the current value with the previous value and proceed. For example in the table given above: the smaller value we will get depending on my requirement from Column 1 is 327 (because 327 is smaller than the previous value 340) - and then we divide 327 by 340 and we get the value 0.96. My python script should exit right after we print the criteria (A) as given below.

from __future__ import division
import csv

def category(val):
    if 0.8 < val <= 0.9:
        return "A"
    if abs(val - 0.7) < 1e-10:
        return "B"
    if 0.5 < val < 0.7:
        return "C"
    if abs(val - 0.5) < 1e-10:
        return "E"
    return "D"

    with open("test.csv", "r") as csvfile:
    ff = csv.reader(csvfile)

    results = []
    previous_value = 0
    for col1, col2 in ff:
        if not col1.isdigit():
            continue
        value = int(col1)
        if value >= previous_value:
            previous_value = value
            continue
        else:
            result =  int(col1)/ int(previous_value)
            results.append(result)
            print category(result)
            previous_value = value
    print (results)
    print (sum(results))
    print (category(sum(results) / len(results)))

Finally, i want to run my scrip for all the .csv files i have in the current directory and build a confusion matrix like the following. Let's say A1.csv, A2.csv, A3.csv are supposed (or predicted) to print A, B1.csv, B2.csv, B3.csv are supposed (or predicted) to print B and C1.csv, C2.csv and C3.csv are supposed (or predicted) to print C, ... etc. How can we automatically create a confusion matrix from multiple .csv files for example like the following using Python?

As it is shown below, the colored blocks of the matrix (row-labels) will show us the number of counts of A (count of true values for A), B (count of true values for b) and C (count of true values for C), ..etc from the control logic of our function category()- given above. The column labels from the control logic we have inside the if-else statement (A, B, C, D and E).

Body:
Using Scikit-Learn is the best option to go for in your case as it provides a confusion_matrix function. Here is an approach you can easily extend.

from sklearn.metrics import confusion_matrix

# Read your csv files
with open('A1.csv', 'r') as readFile:
    true_values = [int(ff) for ff in readFile]
with open('B1.csv', 'r') as readFile:
    predictions = [int(ff) for ff in readFile]

# Produce the confusion matrix
confusionMatrix = confusion_matrix(true_values, predictions)

print(confusionMatrix)

This is the output you would expect.

[[0 2]
 [0 2]]

For more hint - check out the following link:

How to write a confusion matrix in Python?


来源: stackexchange

问:
How can i keep two values in c++
I have few pairs of elements : (3 1),(2 0),(3 0),(1 2),(4 1),(0 4),(0 1)
How or where can i keep them? In multidimensional array?
I thought about array but not sure

答:
If you have pairs you can use std:pair:

```<code>std::vector<std::pair<int, int>> pairs = {{3, 1},{2, 0}};
</code>```

If you know in advance how many pairs you will have then you can use std::array:

```<code>std::array<std::pair<int, int>, 2> pairs = {{{3, 1},{2, 0}}};
</code>```

ContentLicense: CC BY-SA 3.0

Title: How can i keep two values in c++

Body:
If you have pairs you can use std:pair:

std::vector<std::pair<int, int>> pairs = {{3, 1},{2, 0}};

If you know in advance how many pairs you will have then you can use std::array:

std::array<std::pair<int, int>, 2> pairs = {{{3, 1},{2, 0}}};


问:
Taking Date input into a query in MS Access VBA from TextBox
I am trying to take input from a form, and I want to execute a insert query (append query) when a button is clicked.

Here is my Code:

```<code>Private Sub Command103_Click()
    Dim enrollment As String
    enrollment = Form_Form1!tbEnrollment

    Dim amount As String
    amount = Form_Form1!tbAmount

    Dim year As Integer
    year = Form_Form1!tbYear

    Dim date1 As Date
    date1 = Form_Form1!tbDate

    Dim month As Integer
    month = Form_Form1!cbMonth

    Dim sqlqry As String

    Dim db As DAO.Database
    Set db = CurrentDb
    sqlqry = "INSERT INTO StudentFeeMonthly( StudentID, FeeMonth, FeeYear, Amount, DateOfPayment, ReceiptNo ) SELECT TOP 1 (SELECT DISTINCT StudentDetails.StudentID FROM StudentDetails WHERE StudentDetails.EnrollmentNo = '" & enrollment & "') AS Expr1, '" & month & "' AS Expr2, '" & year & "' AS Expr3, '" & amount & "' AS Expr4, '" & date1 & "' AS Expr5, ""Hello"" AS Expr6 FROM StudentFeeMonthly;"
    MsgBox (sqlqry)

    db.Execute sqlqry

    MsgBox ("done")

End Sub
</code>```

Everything works fine, except the column with the date value remains blank after addition of the record.

The textbox format is set to "General Date", and it uses a date picker to select the date.

答:
a) You need to wrap date values with #.

b) Year and Month are reserved keywords, consider changing them.

c) Year, Month and Amount should be numeric fields (?), but wrapping them in ' quotes, you pass them as strings.

d) Use a query with parameters.

Query SQL:

```<code>PARAMETERS
    [prmEnrollmentNo] Long,
    [prmFeeMonth] Long,
    [prmFeeYear] Long,
    [prmAmount] IEEESingle,
    [prmDateOfPayment] DateTime;

INSERT INTO StudentFeeMonthly (StudentID, FeeMonth, FeeYear, Amount, DateOfPayment, ReceiptNo)
SELECT (SELECT DISTINCT StudentDetails.StudentID
        FROM StudentDetails
        WHERE StudentDetails.EnrollmentNo=[prmEnrollmentNo]),
        [prmFeeMonth],
        [prmFeeYear],
        [prmAmount],
        [prmDateOfPayment],
        "Hello";
</code>```

Calling the query in code:

```<code>With CurrentDb().QueryDefs("YourInsertQueryName")
    .Parameters("[prmEnrollmentNo]").Value = enrollment
    .Parameters("[prmFeeMonth]").Value = Month 'change it
    .Parameters("[prmFeeYear]").Value = Year   'change it
    .Parameters("[prmAmount]").Value = amount
    .Parameters("[prmDateOfPayment]").Value = date1
    .Execute dbFailOnError
End With
</code>```

Note:

I've assumed fields ending with '...No' e.g. EnrollmentNo are numeric.

Body:
I am trying to take input from a form, and I want to execute a insert query (append query) when a button is clicked.

Here is my Code:

Private Sub Command103_Click()
    Dim enrollment As String
    enrollment = Form_Form1!tbEnrollment

    Dim amount As String
    amount = Form_Form1!tbAmount

    Dim year As Integer
    year = Form_Form1!tbYear

    Dim date1 As Date
    date1 = Form_Form1!tbDate

    Dim month As Integer
    month = Form_Form1!cbMonth

    Dim sqlqry As String

    Dim db As DAO.Database
    Set db = CurrentDb
    sqlqry = "INSERT INTO StudentFeeMonthly( StudentID, FeeMonth, FeeYear, Amount, DateOfPayment, ReceiptNo ) SELECT TOP 1 (SELECT DISTINCT StudentDetails.StudentID FROM StudentDetails WHERE StudentDetails.EnrollmentNo = '" & enrollment & "') AS Expr1, '" & month & "' AS Expr2, '" & year & "' AS Expr3, '" & amount & "' AS Expr4, '" & date1 & "' AS Expr5, ""Hello"" AS Expr6 FROM StudentFeeMonthly;"
    MsgBox (sqlqry)

    db.Execute sqlqry

    MsgBox ("done")

End Sub

Everything works fine, except the column with the date value remains blank after addition of the record.

The textbox format is set to "General Date", and it uses a date picker to select the date.

Body:
a) You need to wrap date values with #.

b) Year and Month are reserved keywords, consider changing them.

c) Year, Month and Amount should be numeric fields (?), but wrapping them in ' quotes, you pass them as strings.

d) Use a query with parameters.

Query SQL:

PARAMETERS
    [prmEnrollmentNo] Long,
    [prmFeeMonth] Long,
    [prmFeeYear] Long,
    [prmAmount] IEEESingle,
    [prmDateOfPayment] DateTime;

INSERT INTO StudentFeeMonthly (StudentID, FeeMonth, FeeYear, Amount, DateOfPayment, ReceiptNo)
SELECT (SELECT DISTINCT StudentDetails.StudentID
        FROM StudentDetails
        WHERE StudentDetails.EnrollmentNo=[prmEnrollmentNo]),
        [prmFeeMonth],
        [prmFeeYear],
        [prmAmount],
        [prmDateOfPayment],
        "Hello";

Calling the query in code:

With CurrentDb().QueryDefs("YourInsertQueryName")
    .Parameters("[prmEnrollmentNo]").Value = enrollment
    .Parameters("[prmFeeMonth]").Value = Month 'change it
    .Parameters("[prmFeeYear]").Value = Year   'change it
    .Parameters("[prmAmount]").Value = amount
    .Parameters("[prmDateOfPayment]").Value = date1
    .Execute dbFailOnError
End With

Note:

I've assumed fields ending with '...No' e.g. EnrollmentNo are numeric.


问:
Search filter in listview for array of strings with android SearchView
I need to filter my list items via getFilter method, In my Model class, I have an array variable named genre.

This genre sometimes is one word, and sometimes more than one separated with , . For example like:

android, iPhone, blackberry.

Now in my code when I try to search in my list for an item, it will only search for the first word(android). In another word, if I try to search for iPhone, this item will not be shown in my new filtered list.

In below code I know I'm doing it wrong, but can you help me correct it, please?

```<code>@Override
public Filter getFilter() {
    Filter filter = new Filter() {
        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            dataList = (List<ProductLocal>) results.values;
            notifyDataSetChanged();
        }
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            FilterResults results = new FilterResults();
            List<ProductLocal> filteredList = new ArrayList<>();
            constraint = constraint.toString().toLowerCase();
            for (int i = 0; i < dataListFilter.size(); i++) {
                ProductLocal dataNames = dataListFilter.get(i);
                String genreStr = "";
                for (String str : dataNames.getGenre()) {
                    genreStr += str;
                }
                genreStr = genreStr.length() > 0 ? genreStr.substring(0,genreStr.length() - 2) : genreStr;
                if (genreStr.toLowerCase().startsWith(constraint.toString()) ) {
                    filteredList.add(dataNames);
                }
            }
            results.count = filteredList.size();
            results.values = filteredList;
            return results;
        }
    };
    return filter;
}
</code>```

And my another question is:

How can I search for items with more than one genre seperatted with , ?

For example query = android,blackberry

And result comes up with all items that have this two genres

答:
For comparing the strings partially you can use the indexOf function like below.

```<code>if(dataNames.getGenre().toLowerCase().indexOf(constraint)>-1){
 //add to your list
 filteredList.add(dataNames);
} else{
  //doesn't satisfy the filter condition.
}
</code>```

Another thing noticed is that if your getGenre() is a List you don't need to add all the string together and check the filter condition you can do it like below.
You can split the comma separated value to a list string and loop through it and check filter.

```<code>List<String> filterList = Arrays.asList(constraint.split(","))
bool hasAdded;
for (String str : dataNames.getGenre())
{
  for (String filter : filterList) {
    if(str.toLowerCase().indexOf(filter.trim().toLowerCase())>-1){
    //add to your list
    filteredList.add(dataNames);
    hasAdded = true;
    break;
   }
   if(hasAdded) break;
  }
}
</code>```

Also you can change the for loop with foreach for looping dataListFilter.

Body:
I need to filter my list items via getFilter method, In my Model class, I have an array variable named genre.

This genre sometimes is one word, and sometimes more than one separated with , . For example like:

android, iPhone, blackberry.

Now in my code when I try to search in my list for an item, it will only search for the first word(android). In another word, if I try to search for iPhone, this item will not be shown in my new filtered list.

In below code I know I'm doing it wrong, but can you help me correct it, please?

@Override
public Filter getFilter() {
    Filter filter = new Filter() {
        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            dataList = (List<ProductLocal>) results.values;
            notifyDataSetChanged();
        }
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            FilterResults results = new FilterResults();
            List<ProductLocal> filteredList = new ArrayList<>();
            constraint = constraint.toString().toLowerCase();
            for (int i = 0; i < dataListFilter.size(); i++) {
                ProductLocal dataNames = dataListFilter.get(i);
                String genreStr = "";
                for (String str : dataNames.getGenre()) {
                    genreStr += str;
                }
                genreStr = genreStr.length() > 0 ? genreStr.substring(0,genreStr.length() - 2) : genreStr;
                if (genreStr.toLowerCase().startsWith(constraint.toString()) ) {
                    filteredList.add(dataNames);
                }
            }
            results.count = filteredList.size();
            results.values = filteredList;
            return results;
        }
    };
    return filter;
}

And my another question is:

How can I search for items with more than one genre seperatted with , ?

For example query = android,blackberry

And result comes up with all items that have this two genres

Body:
For comparing the strings partially you can use the indexOf function like below.

if(dataNames.getGenre().toLowerCase().indexOf(constraint)>-1){
 //add to your list
 filteredList.add(dataNames);
} else{
  //doesn't satisfy the filter condition.
}

Another thing noticed is that if your getGenre() is a List you don't need to add all the string together and check the filter condition you can do it like below.
You can split the comma separated value to a list string and loop through it and check filter.

List<String> filterList = Arrays.asList(constraint.split(","))
bool hasAdded;
for (String str : dataNames.getGenre())
{
  for (String filter : filterList) {
    if(str.toLowerCase().indexOf(filter.trim().toLowerCase())>-1){
    //add to your list
    filteredList.add(dataNames);
    hasAdded = true;
    break;
   }
   if(hasAdded) break;
  }
}

Also you can change the for loop with foreach for looping dataListFilter.


问:
Has anyone successfully used signature timestamps in a java applet?
Java 1.5 added an enhancement to support signature timestamps.  The idea, as far as I can tell, is that signed jar files should not become invalid just because the code signing certificate has expired, as long as the files were signed while the certificate was valid.  In theory, this means we do not have to re-sign and redeploy our applications every year when the certificate expires.  Unfortunately, there seem to be problems in the implementation, based on these two forum threads:

http://forums.sun.com/thread.jspa?threadID=744677

http://forums.sun.com/thread.jspa?threadID=5309004

I'm about to begin testing this, but I was wondering if anyone has successfully done this, without having to import the timestamping certificate on the client (which would defeat the whole purpose)?

答:
Unfortunately, this feature appears to be completely worthless at this time.  It is easy to add a timestamp when signing a jar file, just add this parameter to the jarsigner command:

```<code>-tsa https://timestamp.geotrust.com/tsa
</code>```

This is the URL to Thawte's timestamping server.  Unfortunately, the Thawte timestamping CA cert is not included in the Java runtime's list of trusted CA certs, so it is effectively meaningless.  That is, if you load the applet after the code signing certificate has expired, you get the "untrusted" warning dialog instead of the "trusted" one.

There is a "workaround", of sorts, posted here, but it works by embedding the Thawte timestamping CA cert in the applet itself, and running keytool on the client to import the cert.  I can't see how this would work though, since the user will already have seen the signed code dialog before this code can run.

I'll keep looking for a solution, but I'm not hopeful.  I can't imagine why a usable timestamping CA cert has not been included with the Java runtime after all this time.

OwnerDisplayName: Jason Day

ContentLicense: CC BY-SA 2.5

Body:
Unfortunately, this feature appears to be completely worthless at this time.  It is easy to add a timestamp when signing a jar file, just add this parameter to the jarsigner command:

-tsa https://timestamp.geotrust.com/tsa

This is the URL to Thawte's timestamping server.  Unfortunately, the Thawte timestamping CA cert is not included in the Java runtime's list of trusted CA certs, so it is effectively meaningless.  That is, if you load the applet after the code signing certificate has expired, you get the "untrusted" warning dialog instead of the "trusted" one.

There is a "workaround", of sorts, posted here, but it works by embedding the Thawte timestamping CA cert in the applet itself, and running keytool on the client to import the cert.  I can't see how this would work though, since the user will already have seen the signed code dialog before this code can run.

I'll keep looking for a solution, but I'm not hopeful.  I can't imagine why a usable timestamping CA cert has not been included with the Java runtime after all this time.


答: You can keep them in, more or less, any container you want. A std::vector<std::pair<int, int>> would seem the most natural to me.

Title: How can i keep two values in c++

Body:
I have few pairs of elements : (3 1),(2 0),(3 0),(1 2),(4 1),(0 4),(0 1)
How or where can i keep them? In multidimensional array?
I thought about array but not sure


问:
jQuery mouse event blocks default propagation
I have an issue with a full-body-overlay effect when clicking on any link.

The wanted effect is:

when any link of the page is "pushed" (mousedown or touchstart), an image overlay appears on the top of the whole body (hiding the complete content of the page)

when the link is (or should be) "released" (mouseup or touchend), the overlay should disappear and the original clicked link target should happen (the "href" attribute must be followed for instance).

The first part is OK: I added an event handler listening the "mousedown touchstart" events on every links. The second part is more complicated as the overlay does not trigger the "release" action of the link (the overlay is over the content with the link). So I attached a "mousedown touchend" event handler on the whole document, which works, but the default behavior of the clicked link (go to its "href" attribute for instance) is never fired :(

Here is my JS:

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

    // the full-page overlay selector
    var $overlay = $('.body-overlay');

    // a flag to keep a trace of clicked element
    var overlay_triggered = false;

    // the "mousedown" event handler
    function show_overlay(evt)
    {
        var $target = $(evt.target);
        if (overlay_triggered === false) {
            $overlay.show();
            overlay_triggered = $target;
            $(document).on('mouseup touchend', hide_overlay);
        }
        return true;
    }

    // the "mouseup" event handler
    function hide_overlay(evt)
    {
        if (overlay_triggered !== false) {
            $(document).off('mouseup touchend', hide_overlay);
            $overlay.hide();

            // !!! - here I try to trigger a classic click but it never works
            $(overlay_triggered).click();

            overlay_triggered = false;
        }
        return true;
    }

    // attachment of the mousedown handler on all links
    $(document).on('mousedown touchstart', 'a', show_overlay);

});
</code>```

I made a JS Fiddle to show it more clearly.

Does someone know about any mistake here ? Is my logic wrong ?

答:
I have slightly modified the JS part of yours, and all is okay now
The thing i did is holding the target's href value in a variable ( I stored the target's href value in 'href' vaiable in the code below ), and after that "window.location = href;" in  'hide_overlay' function does the trick.</p>

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

        // the full-page overlay selector
        var $overlay = $('.body-overlay');

        // a flag to keep a trace of clicked element
        var overlay_triggered = false;
        var href = false;

        // the "mousedown" event handler
        function show_overlay(evt)
        {
            var $target = $(evt.target);
            href = evt.target.href;

            if (overlay_triggered === false) {
                $overlay.show();
                overlay_triggered = $target;
                $(document).on('mouseup touchend', hide_overlay);
            }
            return true;
        }

        // the "mouseup" event handler
        function hide_overlay(evt)
        {
            if (overlay_triggered !== false) {
                $(document).off('mouseup touchend', hide_overlay);
                $overlay.hide();

                // !!! - here I try to trigger a classic click but it never works
                if( href ) {
                    window.location = href;
                }
                overlay_triggered = false;
            }
            return true;
        }

        // attachment of the mousedown handler on all links
        $(document).on('mousedown touchstart', 'a', show_overlay);

    });

</script>
</code>```

Body:
I have an issue with a full-body-overlay effect when clicking on any link.

The wanted effect is:

when any link of the page is "pushed" (mousedown or touchstart), an image overlay appears on the top of the whole body (hiding the complete content of the page)

when the link is (or should be) "released" (mouseup or touchend), the overlay should disappear and the original clicked link target should happen (the "href" attribute must be followed for instance).

The first part is OK: I added an event handler listening the "mousedown touchstart" events on every links. The second part is more complicated as the overlay does not trigger the "release" action of the link (the overlay is over the content with the link). So I attached a "mousedown touchend" event handler on the whole document, which works, but the default behavior of the clicked link (go to its "href" attribute for instance) is never fired :(

Here is my JS:

$(document).ready(function(){

    // the full-page overlay selector
    var $overlay = $('.body-overlay');

    // a flag to keep a trace of clicked element
    var overlay_triggered = false;

    // the "mousedown" event handler
    function show_overlay(evt)
    {
        var $target = $(evt.target);
        if (overlay_triggered === false) {
            $overlay.show();
            overlay_triggered = $target;
            $(document).on('mouseup touchend', hide_overlay);
        }
        return true;
    }

    // the "mouseup" event handler
    function hide_overlay(evt)
    {
        if (overlay_triggered !== false) {
            $(document).off('mouseup touchend', hide_overlay);
            $overlay.hide();

            // !!! - here I try to trigger a classic click but it never works
            $(overlay_triggered).click();

            overlay_triggered = false;
        }
        return true;
    }

    // attachment of the mousedown handler on all links
    $(document).on('mousedown touchstart', 'a', show_overlay);

});

I made a JS Fiddle to show it more clearly.

Does someone know about any mistake here ? Is my logic wrong ?

Body:
I have slightly modified the JS part of yours, and all is okay now
The thing i did is holding the target's href value in a variable ( I stored the target's href value in 'href' vaiable in the code below ), and after that "window.location = href;" in  'hide_overlay' function does the trick.

<script>
    $(document).ready(function(){

        // the full-page overlay selector
        var $overlay = $('.body-overlay');

        // a flag to keep a trace of clicked element
        var overlay_triggered = false;
        var href = false;

        // the "mousedown" event handler
        function show_overlay(evt)
        {
            var $target = $(evt.target);
            href = evt.target.href;

            if (overlay_triggered === false) {
                $overlay.show();
                overlay_triggered = $target;
                $(document).on('mouseup touchend', hide_overlay);
            }
            return true;
        }

        // the "mouseup" event handler
        function hide_overlay(evt)
        {
            if (overlay_triggered !== false) {
                $(document).off('mouseup touchend', hide_overlay);
                $overlay.hide();

                // !!! - here I try to trigger a classic click but it never works
                if( href ) {
                    window.location = href;
                }
                overlay_triggered = false;
            }
            return true;
        }

        // attachment of the mousedown handler on all links
        $(document).on('mousedown touchstart', 'a', show_overlay);

    });

</script>


问:
How to kill a child process after a given timeout in Bash?
I have a bash script that launches a child process that crashes (actually, hangs) from time to time and with no apparent reason (closed source, so there isn't much I can do about it). As a result, I would like to be able to launch this process for a given amount of time, and kill it if it did not return successfully after a given amount of time.

Is there a simple and robust way to achieve that using bash?

答:
Here's the third answer I've submitted here.  This one handles signal interrupts and cleans up background processes when SIGINT is received. It uses the $BASHPID and exec trick used in the top answer to get the PID of a process (in this case $$ in a sh invocation). It uses a FIFO to communicate with a subshell that is responsible for killing and cleanup.  (This is like the pipe in my second answer, but having a named pipe means that the signal handler can write into it too.)

```<code>run_with_timeout ()
{
  t=$1 ; shift

  trap cleanup 2

  F=$$.fifo ; rm -f $F ; mkfifo $F

  # first, run main process in background
  "$@" & pid=$!

  # sleeper process to time out
  ( sh -c "echo \$\$ >$F ; exec sleep $t" ; echo timeout >$F ) &
  read sleeper <$F

  # control shell. read from fifo.
  # final input is "finished".  after that
  # we clean up.  we can get a timeout or a
  # signal first.
  ( exec 0<$F
    while : ; do
      read input
      case $input in
        finished)
          test $sleeper != 0 && kill $sleeper
          rm -f $F
          exit 0
          ;;
        timeout)
          test $pid != 0 && kill $pid
          sleeper=0
          ;;
        signal)
          test $pid != 0 && kill $pid
          ;;
      esac
    done
  ) &

  # wait for process to end
  wait $pid
  status=$?
  echo finished >$F
  return $status
}

cleanup ()
{
  echo signal >$$.fifo
}
</code>```

I've tried to avoid race conditions as far as I can. However, one source of error I couldn't remove is when the process ends near the same time as the timeout. For example, run_with_timeout 2 sleep 2 or run_with_timeout 0 sleep 0.  For me, the latter gives an error:

```<code>timeout.sh: line 250: kill: (23248) - No such process
</code>```

as it is trying to kill a process that has already exited by itself.

ContentLicense: CC BY-SA 4.0

Body:
Here's the third answer I've submitted here.  This one handles signal interrupts and cleans up background processes when SIGINT is received. It uses the $BASHPID and exec trick used in the top answer to get the PID of a process (in this case $$ in a sh invocation). It uses a FIFO to communicate with a subshell that is responsible for killing and cleanup.  (This is like the pipe in my second answer, but having a named pipe means that the signal handler can write into it too.)

run_with_timeout ()
{
  t=$1 ; shift

  trap cleanup 2

  F=$$.fifo ; rm -f $F ; mkfifo $F

  # first, run main process in background
  "$@" & pid=$!

  # sleeper process to time out
  ( sh -c "echo \$\$ >$F ; exec sleep $t" ; echo timeout >$F ) &
  read sleeper <$F

  # control shell. read from fifo.
  # final input is "finished".  after that
  # we clean up.  we can get a timeout or a
  # signal first.
  ( exec 0<$F
    while : ; do
      read input
      case $input in
        finished)
          test $sleeper != 0 && kill $sleeper
          rm -f $F
          exit 0
          ;;
        timeout)
          test $pid != 0 && kill $pid
          sleeper=0
          ;;
        signal)
          test $pid != 0 && kill $pid
          ;;
      esac
    done
  ) &

  # wait for process to end
  wait $pid
  status=$?
  echo finished >$F
  return $status
}

cleanup ()
{
  echo signal >$$.fifo
}

I've tried to avoid race conditions as far as I can. However, one source of error I couldn't remove is when the process ends near the same time as the timeout. For example, run_with_timeout 2 sleep 2 or run_with_timeout 0 sleep 0.  For me, the latter gives an error:

timeout.sh: line 250: kill: (23248) - No such process

as it is trying to kill a process that has already exited by itself.


问:
Fade out at specific scroll position
I can now fade in a  at a specific scroll height. But now I also want to fade out a  at specific scroll height. My code for the fade out:

```<code><script type="text/javascript">
    window.onscroll = function()
    {
    if( window.XMLHttpRequest ) {
        if (document.documentElement.scrollTop > 25 || self.pageYOffset > 25) {
            $('.pulse').css('display','block');
        } else if (document.documentElement.scrollTop < 25 || self.pageYOffset < 25) {
            $('.pulse').css('display','none');
    }
}
</code>```

And  in css:

```<code>display: none;
</code>```

How can I fade out a  at specific height?

Thanks for the help

答:
You can use fadeIn() and fadeOut() functions provided by jQuery:

```<code>//to show
$('.pulse').fadeIn(1000);
//to hide
$('.pulse').fadeOut(1000);
</code>```

Docs of these functions:

http://api.jquery.com/fadeout/
http://api.jquery.com/fadein/

Title: Fade out at specific scroll position

Body:
You can use fadeIn() and fadeOut() functions provided by jQuery:

//to show
$('.pulse').fadeIn(1000);
//to hide
$('.pulse').fadeOut(1000);

Docs of these functions:

http://api.jquery.com/fadeout/
http://api.jquery.com/fadein/


问:
CStatusBarCtrl automatic resize
In MFC shouldn't a status bar resize automatically when the parent window updates?Is there a missing setting I need to use to make this happen?</p>

```<code>class Mainwindow {
public:
    MainWindow() {
        Create(NULL, _T("Main Window"));
}
afx_msg int OnCreate(LPCREATESTRUCT lp) {
        // Status bar
        CRect rc;
        this->GetClientRect(&rc);
        std::array<int, 3> sb = { rc.right / 3,rc.right / 3 * 2,-1 };
        status_bar.Create(WS_CHILD | WS_VISIBLE | CCS_BOTTOM | SBARS_SIZEGRIP, CRect(0, 0, 0, 0), this, IDS_STATUSBARCTRL);
        status_bar.SetParts(3, sb.data());
        status_bar.SetTipText(1, _T("Tooltip text"));
        status_bar.SetText(_T("Left"), 0, SBT_POPOUT);
        status_bar.SetText(_T("Middle"), 1, 0);
        status_bar.SetText(_T("Right"), 2, 0);
        return TRUE;
    }

// This resizes the status bar fine, but shouldn't MFC handle it?
       afx_msg void OnSize(UINT, int cx, int cy) {
        status_bar.SendMessage(WM_SIZE, 0, 0);
    }

    DECLARE_MESSAGE_MAP()

private:
    CStatusBarCtrl status_bar;
};

BEGIN_MESSAGE_MAP(MainWindow,CFrameWnd)
    ON_WM_CREATE()
    ON_WM_SIZE()
END_MESSAGE_MAP()
</code>```

答:
Just scanning the MFC code... (can't get my debugger to step through at the moment, argh)

Inside the CFrameWnd class, there's a function called RecalcLayout. MSDN says:

Called by the framework when the standard control bars are toggled on or off or when the frame window is resized.

RecalcLayout makes a call to CWnd::RepositionBars. Inside the function is a comment:

```<code>// walk kids in order, control bars get the resize notification
//   which allow them to shrink the client area
</code>```

It looks like the notification is done via the WM_SIZEPARENT message:

a) The CControlBar class has a message handler for WM_SIZEPARENT

b) CStatusBarCtrl is derived from CWnd, not CControlBar, and therefore won't get the message

Solution: I would just do it the way the app wizard does it - make your status bar member variable a CStatusBar. (derived from CControlBar) From there you can call GetStatusBarCtrl().

```<code>// .h
CStatusBar status_bar;

// .cpp
if (!status_bar.Create(this))
{
    TRACE0("Failed to create status bar\n");
    return -1;
}

auto& statusBarCtrl = status_bar.GetStatusBarCtrl();
statusBarCtrl.SetParts(3, sb);
// etc.
</code>```

Title: CStatusBarCtrl automatic resize

Body:
In MFC shouldn't a status bar resize automatically when the parent window updates?Is there a missing setting I need to use to make this happen?

class Mainwindow {
public:
    MainWindow() {
        Create(NULL, _T("Main Window"));
}
afx_msg int OnCreate(LPCREATESTRUCT lp) {
        // Status bar
        CRect rc;
        this->GetClientRect(&rc);
        std::array<int, 3> sb = { rc.right / 3,rc.right / 3 * 2,-1 };
        status_bar.Create(WS_CHILD | WS_VISIBLE | CCS_BOTTOM | SBARS_SIZEGRIP, CRect(0, 0, 0, 0), this, IDS_STATUSBARCTRL);
        status_bar.SetParts(3, sb.data());
        status_bar.SetTipText(1, _T("Tooltip text"));
        status_bar.SetText(_T("Left"), 0, SBT_POPOUT);
        status_bar.SetText(_T("Middle"), 1, 0);
        status_bar.SetText(_T("Right"), 2, 0);
        return TRUE;
    }

// This resizes the status bar fine, but shouldn't MFC handle it?
       afx_msg void OnSize(UINT, int cx, int cy) {
        status_bar.SendMessage(WM_SIZE, 0, 0);
    }

    DECLARE_MESSAGE_MAP()

private:
    CStatusBarCtrl status_bar;
};

BEGIN_MESSAGE_MAP(MainWindow,CFrameWnd)
    ON_WM_CREATE()
    ON_WM_SIZE()
END_MESSAGE_MAP()

Body:
Just scanning the MFC code... (can't get my debugger to step through at the moment, argh)

Inside the CFrameWnd class, there's a function called RecalcLayout. MSDN says:

Called by the framework when the standard control bars are toggled on or off or when the frame window is resized.

RecalcLayout makes a call to CWnd::RepositionBars. Inside the function is a comment:

// walk kids in order, control bars get the resize notification
//   which allow them to shrink the client area

It looks like the notification is done via the WM_SIZEPARENT message:

a) The CControlBar class has a message handler for WM_SIZEPARENT

b) CStatusBarCtrl is derived from CWnd, not CControlBar, and therefore won't get the message

Solution: I would just do it the way the app wizard does it - make your status bar member variable a CStatusBar. (derived from CControlBar) From there you can call GetStatusBarCtrl().

// .h
CStatusBar status_bar;

// .cpp
if (!status_bar.Create(this))
{
    TRACE0("Failed to create status bar\n");
    return -1;
}

auto& statusBarCtrl = status_bar.GetStatusBarCtrl();
statusBarCtrl.SetParts(3, sb);
// etc.


问:
Checking XML Document befor upload to server via php
I am creating a script to upload XML-files to a server, where you enter how often specific tags occur in the file. Now I wanted to automate this, so that i check the XML-file befor uploading, so that the previous manually entered fields are filled automaticly.

I just dont get the point how i can get the content of the file befor actually uploading it - i want to use Javascript for the check and auto-fillment.

The upload is completly realized in php.

Someone have an idea for me?

Edit:

```<code>var fileInput;

window.onload = function() {
    fileInput = document.getElementById('file_input');
};

function getNodes() {
    var anzNodes = fileInput.getElementsByTagName("node").length;
    return anzNodes;
}

function getEdges() {
    var anzEdges = fileInput.getElementsByTagName("edge").length;
    return anzEdges;
}

function fillForm() {
    document.getElementById("nodes").value = getNodes();
    document.getElementById("edges").value = getEdges();
}
</code>```

So I have a html-form with the ID file_input. I try to grab that file (which is XML) befor uploading, search it for the amount of "node" and "edge" tags, and autofill these information into the html form. This should happen when the file is chosen. Is this better?

答: Use the FileReader functionality in JavaScript to grab the document before uploading it. Then you can read the text of the file and pre-process it before sending it to the server.</p>

Body:
I am creating a script to upload XML-files to a server, where you enter how often specific tags occur in the file. Now I wanted to automate this, so that i check the XML-file befor uploading, so that the previous manually entered fields are filled automaticly.

I just dont get the point how i can get the content of the file befor actually uploading it - i want to use Javascript for the check and auto-fillment.

The upload is completly realized in php.

Someone have an idea for me?

Edit:

var fileInput;

window.onload = function() {
    fileInput = document.getElementById('file_input');
};

function getNodes() {
    var anzNodes = fileInput.getElementsByTagName("node").length;
    return anzNodes;
}

function getEdges() {
    var anzEdges = fileInput.getElementsByTagName("edge").length;
    return anzEdges;
}

function fillForm() {
    document.getElementById("nodes").value = getNodes();
    document.getElementById("edges").value = getEdges();
}

So I have a html-form with the ID file_input. I try to grab that file (which is XML) befor uploading, search it for the amount of "node" and "edge" tags, and autofill these information into the html form. This should happen when the file is chosen. Is this better?


问:
How to select rows above #
I'm currently trying to setup a query that only selects from a row number and upwards from it. I've tried to use the LIMIT method in this way:

```<code>SELECT name FROM names LIMIT 1500, *
</code>```

Which I expected to select from row number 1500 till the table's rows ended, but got a MySQL error instead.

I then tried to use a conditional for the ID of the rows like so:

```<code>SELECT name FROM names WHERE id >= 1500
</code>```

Which gave unpredictable behavior since there are rows that get deleted, so it's not taking the real row numbers.

答:
you could use a subquery  </p>

```<code>select name
from names
where id > (
    select max(id)
    from names
    order by names
    limit 1500
)
</code>```

Title: How to select rows above #

Body:
I'm currently trying to setup a query that only selects from a row number and upwards from it. I've tried to use the LIMIT method in this way:

SELECT name FROM names LIMIT 1500, *

Which I expected to select from row number 1500 till the table's rows ended, but got a MySQL error instead.

I then tried to use a conditional for the ID of the rows like so:

SELECT name FROM names WHERE id >= 1500

Which gave unpredictable behavior since there are rows that get deleted, so it's not taking the real row numbers.

Body:
you could use a subquery

select name
from names
where id > (
    select max(id)
    from names
    order by names
    limit 1500
)


问:
Random number generator with no duplicates
Basically I'm creating a program to randomly generate 6 unique lottery numbers so there is no duplicates in the same line, here is the code I have so far...

```<code>        //Generate 6 random numbers using the randomiser object

        int randomNumber1 = random.Next(1, 49);
        int randomNumber2 = random.Next(1, 49);
        int randomNumber3 = random.Next(1, 49);
        int randomNumber4 = random.Next(1, 49);
        int randomNumber5 = random.Next(1, 49);
        int randomNumber6 = random.Next(1, 49);

        textBox1.Text = randomNumber1.ToString();
        textBox2.Text = randomNumber2.ToString();
        textBox3.Text = randomNumber3.ToString();
        textBox4.Text = randomNumber4.ToString();
        textBox5.Text = randomNumber5.ToString();
        textBox6.Text = randomNumber6.ToString();

    }
</code>```

I'm getting random numbers but sometimes there is the same number on the same line, how do I make each number unique????

Thanks in advance

答:
```<code>   List<int> aux = new List<int>();
   while(aux.Count < 6)
   {
      int rnd = random.Next(1,49);
      if(!aux.Contains(rnd))aux.add(rnd);
   }
</code>```

if you put all Texbox in the same panel you can do that

```<code>  int j = 0;
  foreach(Control x in MyPanel.Controls)
  {
     if(x is TexBox)
     {
        x.Text = aux[j].toString();
        j++;
     }
  }
</code>```

Body:
Basically I'm creating a program to randomly generate 6 unique lottery numbers so there is no duplicates in the same line, here is the code I have so far...

        //Generate 6 random numbers using the randomiser object

        int randomNumber1 = random.Next(1, 49);
        int randomNumber2 = random.Next(1, 49);
        int randomNumber3 = random.Next(1, 49);
        int randomNumber4 = random.Next(1, 49);
        int randomNumber5 = random.Next(1, 49);
        int randomNumber6 = random.Next(1, 49);

        textBox1.Text = randomNumber1.ToString();
        textBox2.Text = randomNumber2.ToString();
        textBox3.Text = randomNumber3.ToString();
        textBox4.Text = randomNumber4.ToString();
        textBox5.Text = randomNumber5.ToString();
        textBox6.Text = randomNumber6.ToString();

    }

I'm getting random numbers but sometimes there is the same number on the same line, how do I make each number unique????

Thanks in advance

Body:
   List<int> aux = new List<int>();
   while(aux.Count < 6)
   {
      int rnd = random.Next(1,49);
      if(!aux.Contains(rnd))aux.add(rnd);
   }

if you put all Texbox in the same panel you can do that

  int j = 0;
  foreach(Control x in MyPanel.Controls)
  {
     if(x is TexBox)
     {
        x.Text = aux[j].toString();
        j++;
     }
  }


问:
Can I add additional field (metadata) to thrift message?
I have generated client and server.
I need to add one more field to message in client and read it in server.
I think about to decorate TProtocol on client side and TProcessor on server side. E.g.:

```<code>// Client:
TTransport transport = new TSocket("localhost", 8888);
transport.open();
TProtocol protocol = new DecoratedProtocol(new TBinaryProtocol(transport));

// Server:
 TServerTransport transport = new TServerSocket(8888);
 TServer server = new TSimpleServer(new Args(transport).processor(new DecoratedProcessor(...)));
</code>```

But I'm not sure what to do inside DecoratedProtocol and DecoratedProcessor?

答:
There is a solution to add message meta data called the THeaderProtocol, but AFAIK right now this is only implemented for C++. That could be a starting point to implement the same for Java.

EDIT: I just noticed that fbthrift seems to implement THeaderProtocol for Java already.

Body:
I have generated client and server.
I need to add one more field to message in client and read it in server.
I think about to decorate TProtocol on client side and TProcessor on server side. E.g.:

// Client:
TTransport transport = new TSocket("localhost", 8888);
transport.open();
TProtocol protocol = new DecoratedProtocol(new TBinaryProtocol(transport));

// Server:
 TServerTransport transport = new TServerSocket(8888);
 TServer server = new TSimpleServer(new Args(transport).processor(new DecoratedProcessor(...)));

But I'm not sure what to do inside DecoratedProtocol and DecoratedProcessor?


问:
Add value to specific Class property from List
This solution seems to me as a very lazy and cheap way to do this and I was wondering if there was any better or more future proof way to do this with as minimal change needed if I wish to add new 'Skills' in the future so to speak.

All I have to do here is specific add levels to the properties in the list, I know what list index belongs to which level. Example: Index 0 contains strength, and defense is index 2. But this might change in the future.

```<code>public class SkillLogic
{
    RpgRepository _skillRpgRepository = new RpgRepository(new DatabaseSkillContext());

    public List<Skill> ProcessSkills(int strength, int constitution, int defense, int dexterity, int intelligence, int charisma, int willpower, int perception, int luck)
    {
        List<Skill> skills = _skillPotionSmashersRepository.GetSkills();

        skills[0].Level = strength;
        skills[1].Level = constitution;
        skills[2].Level = defense;
        skills[3].Level = dexterity;
        skills[4].Level = intelligence;
        skills[5].Level = charisma;
        skills[6].Level = willpower;
        skills[7].Level = perception;
        skills[8].Level = luck;

        return skills;
    }
}
</code>```

答:
I would suggest creating an Enum (StatsType perhaps?) with entries for strength, constitution etc. Then your code could be more self documenting.

Even better, change GetSkills to return a Dictionary rather than a List - with the dictionary Key being of type StatsType.

Body:
This solution seems to me as a very lazy and cheap way to do this and I was wondering if there was any better or more future proof way to do this with as minimal change needed if I wish to add new 'Skills' in the future so to speak.

All I have to do here is specific add levels to the properties in the list, I know what list index belongs to which level. Example: Index 0 contains strength, and defense is index 2. But this might change in the future.

public class SkillLogic
{
    RpgRepository _skillRpgRepository = new RpgRepository(new DatabaseSkillContext());

    public List<Skill> ProcessSkills(int strength, int constitution, int defense, int dexterity, int intelligence, int charisma, int willpower, int perception, int luck)
    {
        List<Skill> skills = _skillPotionSmashersRepository.GetSkills();

        skills[0].Level = strength;
        skills[1].Level = constitution;
        skills[2].Level = defense;
        skills[3].Level = dexterity;
        skills[4].Level = intelligence;
        skills[5].Level = charisma;
        skills[6].Level = willpower;
        skills[7].Level = perception;
        skills[8].Level = luck;

        return skills;
    }
}


问:
selectize drop item to get in front always
hello all i am using selectize plugin to create tags to my site everything is good except that the drop down item gets overlapped by my other divs.

i want them to behave like select items which are absolute and always in frnt.

i have tried positioning with absolute and z-index but no help
if you could suggest me something about the plugin it would be great.

```<code>     <script src="tags/selectize.js"></script>
    <link rel="stylesheet" href="tags/selectize.default.css"/>
 <div class="control-group">
                <select id="<?=$getid_i?>" multiple name="dept[]" class="demo-default" >
                    <option value=""><?=$placehol?></option>
                    <?php if ($tagwhats =='depts'){
                 // something to get ....
                } else if($tagwhats =='skills'){
                 // something here ...
                } ?>
                </select>
            </div>
 <script>
                var eventHandler = function(name) {
                return function() {
                    console.log(name, arguments);
                    $('#log').append('<div><span class="name">' + name + '</span></div>');
                };
            };
            var $select = $('#'+"<?=$getid_i?>").selectize({
                create          : true,
                onChange        : eventHandler('onChange'),
                onItemAdd       : eventHandler('onItemAdd'),
                onItemRemove    : eventHandler('onItemRemove'),
                onOptionAdd     : eventHandler('onOptionAdd'),
                onOptionRemove  : eventHandler('onOptionRemove'),
                onDropdownOpen  : eventHandler('onDropdownOpen'),
                onDropdownClose : eventHandler('onDropdownClose'),
                onFocus         : eventHandler('onFocus'),
                onBlur          : eventHandler('onBlur'),
                onInitialize    : eventHandler('onInitialize'),
                });
                </script>
</code>```

答:
I am using UIKit 3.x and this works for me</p>

```<code>.selectize-dropdown-content {
    z-index: 999;
    background: white;
    border: 1px solid #e5e5e5; // this is optional
}
</code>```

Body:
hello all i am using selectize plugin to create tags to my site everything is good except that the drop down item gets overlapped by my other divs.

i want them to behave like select items which are absolute and always in frnt.

i have tried positioning with absolute and z-index but no help
if you could suggest me something about the plugin it would be great.

    <link rel="stylesheet" href="tags/selectize.default.css"/>

                <select id="<?=$getid_i?>" multiple name="dept[]" class="demo-default" >
                    <option value=""><?=$placehol?></option>
                    <?php if ($tagwhats =='depts'){
                 // something to get ....
                } else if($tagwhats =='skills'){
                 // something here ...
                } ?>
                </select>

Body:
I am using UIKit 3.x and this works for me

.selectize-dropdown-content {
    z-index: 999;
    background: white;
    border: 1px solid #e5e5e5; // this is optional
}


问:
When should I use RequestFactory vs GWT-RPC?
I am trying to figure out if I should migrate my gwt-rpc calls to the new GWT2.1 RequestFactory cals.

Google documentation vaguely mentions that RequestFactory is a better client-server communication method for "data-oriented services"

What I can distill from the documentation is that there is a new Proxy class that simplifies the communication (you don't pass back and forth the actual entity but just the proxy, so it is lighter weight and easier to manage)

Is that the whole point or am I missing something else in the big picture?

答:
I find the idea of creating Proxy classes for all my entities quite annoying. My Hibernate/JPA pojos are auto-generated from the database model. Why do I now need to create a second mirror of those for RPC? We have a nice "estivation" framework that takes care of "de-hibernating" the pojos. </p>

<p>Also, the idea of defining service interfaces that don't quite implement the server side service as a java contract but do implement the methods - sounds very J2EE 1.x/2.x to me. </p>

Body:
I find the idea of creating Proxy classes for all my entities quite annoying. My Hibernate/JPA pojos are auto-generated from the database model. Why do I now need to create a second mirror of those for RPC? We have a nice "estivation" framework that takes care of "de-hibernating" the pojos.

Also, the idea of defining service interfaces that don't quite implement the server side service as a java contract but do implement the methods - sounds very J2EE 1.x/2.x to me.


答:
Your Form_Form1!tbDate value is string, so convert to date.
And When your field type is datetime, then make  #date1#  as Expr5 ".</p>

```<code>Private Sub Command103_Click()
        Dim enrollment As String
        enrollment = Form_Form1!tbEnrollment

        Dim amount As String
        amount = Form_Form1!tbAmount

        Dim year As Integer
        year = Form_Form1!tbYear

        Dim date1 As Date
        date1 = DateValue(Form_Form1!tbDate)

        Dim month As Integer
        month = Form_Form1!cbMonth

        Dim sqlqry As String

        Dim db As DAO.Database
        Set db = CurrentDb
        sqlqry = "INSERT INTO StudentFeeMonthly( StudentID, FeeMonth, FeeYear, Amount, DateOfPayment, ReceiptNo ) SELECT TOP 1 (SELECT DISTINCT StudentDetails.StudentID FROM StudentDetails WHERE StudentDetails.EnrollmentNo = '" & enrollment & "') AS Expr1, '" & month & "' AS Expr2, '" & year & "' AS Expr3, '" & amount & "' AS Expr4, #" & date1 & "# AS Expr5, ""Hello"" AS Expr6 FROM StudentFeeMonthly;"
        MsgBox (sqlqry)

        db.Execute sqlqry

        MsgBox ("done")

    End Sub
</code>```

Title: Taking Date input into a query in MS Access VBA from TextBox

Body:
I am trying to take input from a form, and I want to execute a insert query (append query) when a button is clicked.

Here is my Code:

Private Sub Command103_Click()
    Dim enrollment As String
    enrollment = Form_Form1!tbEnrollment

    Dim amount As String
    amount = Form_Form1!tbAmount

    Dim year As Integer
    year = Form_Form1!tbYear

    Dim date1 As Date
    date1 = Form_Form1!tbDate

    Dim month As Integer
    month = Form_Form1!cbMonth

    Dim sqlqry As String

    Dim db As DAO.Database
    Set db = CurrentDb
    sqlqry = "INSERT INTO StudentFeeMonthly( StudentID, FeeMonth, FeeYear, Amount, DateOfPayment, ReceiptNo ) SELECT TOP 1 (SELECT DISTINCT StudentDetails.StudentID FROM StudentDetails WHERE StudentDetails.EnrollmentNo = '" & enrollment & "') AS Expr1, '" & month & "' AS Expr2, '" & year & "' AS Expr3, '" & amount & "' AS Expr4, '" & date1 & "' AS Expr5, ""Hello"" AS Expr6 FROM StudentFeeMonthly;"
    MsgBox (sqlqry)

    db.Execute sqlqry

    MsgBox ("done")

End Sub

Everything works fine, except the column with the date value remains blank after addition of the record.

The textbox format is set to "General Date", and it uses a date picker to select the date.

Body:
Your Form_Form1!tbDate value is string, so convert to date.
And When your field type is datetime, then make  #date1#  as Expr5 ".

Private Sub Command103_Click()
        Dim enrollment As String
        enrollment = Form_Form1!tbEnrollment

        Dim amount As String
        amount = Form_Form1!tbAmount

        Dim year As Integer
        year = Form_Form1!tbYear

        Dim date1 As Date
        date1 = DateValue(Form_Form1!tbDate)

        Dim month As Integer
        month = Form_Form1!cbMonth

        Dim sqlqry As String

        Dim db As DAO.Database
        Set db = CurrentDb
        sqlqry = "INSERT INTO StudentFeeMonthly( StudentID, FeeMonth, FeeYear, Amount, DateOfPayment, ReceiptNo ) SELECT TOP 1 (SELECT DISTINCT StudentDetails.StudentID FROM StudentDetails WHERE StudentDetails.EnrollmentNo = '" & enrollment & "') AS Expr1, '" & month & "' AS Expr2, '" & year & "' AS Expr3, '" & amount & "' AS Expr4, #" & date1 & "# AS Expr5, ""Hello"" AS Expr6 FROM StudentFeeMonthly;"
        MsgBox (sqlqry)

        db.Execute sqlqry

        MsgBox ("done")

    End Sub


问:
Angular 2 - Cannot read property of undefined error using Array.filter
folks, I am working on a project that needs to filter JSON but in developer tools of Chrome, it shows me an error of undefined property.

```<code> chart: JsonChart[] = [];
 charts: JsonCharts[] = [];

 getCharts() {
    this.iChartHttp.getCharts()
        .subscribe(
        charts => this.charts = charts, //return json object
        error => this.errorMessage = <any>error
        );
}

 if (this.chart_id != null) {
        this.getCharts();
         this.chart = this.charts.filter(charts => charts.id === this.chart_id)[0].series; // this like error occur.
    }
</code>```

Updated Question

It's not getting JSON Array from Service. but it works in another component

iChartHttpService:

```<code> getCharts(): Observable<JsonCharts[]> {
return this.http.get('assets/datas.json')
  .map((res: Response) => res.json())
  .do(data => console.log('server data:', data))  // debug
  .catch(this.handleError);
}

/**
* Handle HTTP error
*/
private handleError(error: any) {
// In a real world app, we might use a remote logging infrastructure
// We'd also dig deeper into the error to get a better message
const errMsg = (error.message) ? error.message :
  error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg); // log to console instead
return Observable.throw(errMsg);
</code>```

}

答:
It occurs when charts is null, try to place your filter logic after the results,</p>

```<code>  getCharts() {
        this.iChartHttp.getCharts()
            .subscribe((charts: any) => {
            this.charts = charts, //return json object
            this.chart = this.charts.filter(charts => charts.id === this.chart_id)[0].series;
            }, error => {
                error => this.errorMessage = <any>error
            });
    }
</code>```

Body:
folks, I am working on a project that needs to filter JSON but in developer tools of Chrome, it shows me an error of undefined property.

 chart: JsonChart[] = [];
 charts: JsonCharts[] = [];

 getCharts() {
    this.iChartHttp.getCharts()
        .subscribe(
        charts => this.charts = charts, //return json object
        error => this.errorMessage = <any>error
        );
}

 if (this.chart_id != null) {
        this.getCharts();
         this.chart = this.charts.filter(charts => charts.id === this.chart_id)[0].series; // this like error occur.
    }

Updated Question

It's not getting JSON Array from Service. but it works in another component

iChartHttpService:

 getCharts(): Observable<JsonCharts[]> {
return this.http.get('assets/datas.json')
  .map((res: Response) => res.json())
  .do(data => console.log('server data:', data))  // debug
  .catch(this.handleError);
}

/**
* Handle HTTP error
*/
private handleError(error: any) {
// In a real world app, we might use a remote logging infrastructure
// We'd also dig deeper into the error to get a better message
const errMsg = (error.message) ? error.message :
  error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg); // log to console instead
return Observable.throw(errMsg);

}

Body:
It occurs when charts is null, try to place your filter logic after the results,

  getCharts() {
        this.iChartHttp.getCharts()
            .subscribe((charts: any) => {
            this.charts = charts, //return json object
            this.chart = this.charts.filter(charts => charts.id === this.chart_id)[0].series;
            }, error => {
                error => this.errorMessage = <any>error
            });
    }


问:
In Angular for which arrtributes we have to use parentheses and for which we have to use bracket
I am a bit confused about using parentheses and brackets on attributes in Angular.</p>

```<code><form [formGroup]="vform" (ngSubmit)="onSubmit(vform.value)">
  <input type="text" name="uname" placeholder="User Name" formControlName="uname">
  <input type="text" name="fname" placeholder="Full Name" formControlName="fname">
  <input type="submit" [disabled]="!vform.valid" value="Submit">
</form>
</code>```

答:
Where ever you are passing a property down to the component/element, you'd use brackets like :

Say I'm passing size="20" to the div element

```<code><div size="20"></div> // passing a value , not a VARIABLE

<div [size]="sizeVariable"></div> // passing a variable to be bound to
</code>```

To give you a broader view, imagine when using normal style tag, you're passing some properties ( in this case styles like colour and ... ) to the element :

```<code><div style="color:red">
</code>```

Where as when using parantesese , you're subscribing to the event that is coming up from the element :

```<code><div (click)="doSomething()">
</code>```

is similar to :

```<code><div onClick="doSomething">
</code>```

and is somewhat similar to

```<code> $('#yourElement').on('click',doSomething)
</code>```

Body:
I am a bit confused about using parentheses and brackets on attributes in Angular.

<form [formGroup]="vform" (ngSubmit)="onSubmit(vform.value)">
  <input type="text" name="uname" placeholder="User Name" formControlName="uname">
  <input type="text" name="fname" placeholder="Full Name" formControlName="fname">
  <input type="submit" [disabled]="!vform.valid" value="Submit">
</form>

Body:
Where ever you are passing a property down to the component/element, you'd use brackets like :

Say I'm passing size="20" to the div element

<div size="20"></div> // passing a value , not a VARIABLE

<div [size]="sizeVariable"></div> // passing a variable to be bound to

To give you a broader view, imagine when using normal style tag, you're passing some properties ( in this case styles like colour and ... ) to the element :

<div style="color:red">

Where as when using parantesese , you're subscribing to the event that is coming up from the element :

<div (click)="doSomething()">

is similar to :

<div onClick="doSomething">

and is somewhat similar to

 $('#yourElement').on('click',doSomething)


问:
How to create a redis cloud connection url with an auth password
I'm switching over from a heroku addon to a direct redis cloud account and am a bit puzzled on how to generate the redis url with the auth info.

The old heroku add-on url was in the format of redis://rediscloud:mypassword@redis...

However in the dashboard and documentation I don't see any mention of a username to go along with the password.  Do I still set rediscloud as the username in my new account and connection string.  Does it even matter what I set as the username there?

答:
At the moment (up to and including v4), Redis doesn't support users and only provides authentication against a global password. In order to be compliant with the URI RFC (https://www.rfc-editor.org/rfc/rfc3986) and based on the provisional RFC for Redis URIs (https://www.iana.org/assignments/uri-schemes/prov/redis), you can pass anything as a username, including the empty string, and it will be okay (i.e. ignored).

P.S. thanks for bringing up this obscurity in our docs, I'll see that it is amended.


问:
A* Search Algorithm gets stuck
I am trying to implement an A* Search algorithm. For now I am just trying to find a good path through an environment littered with walls. The walls are randomly generated, and in some cases my path gets "stuck". If the search encounters a wall in front of it, and to all of its sides (except the one that led it into this mess), it stops.
Is there something I can do to prevent this? I am using a "as the crow flies" point system for my H value, which ignores the walls and just estimates how far it will take to get to the destination. This sometimes leads it into this trap.

Thanks.

答:
Thinking of the state space like a Directed Acyclic Graph, if A* encounters a leaf node that isn't a terminal node, it shouldn't be a problem, since that node will simply have been already moved to the closed list.

If your implementation of A* immediately stops after encountering a non-terminal (goal) leaf node, and there are other nodes still on the open list, then your implementation of A* is incorrect.

Title: A* Search Algorithm gets stuck


问:
Trying to understand why validates_presence_of test fails
I'm just starting to have a play with Rails (using Rspec and Shoulda Matchers) to build a demo blog.

I've literally just started and my first test is failing but I can't understand why.

I think I've set up everything correctly, but when I try to validate that a title is present on my Article model but it returns a failure

```<code>Shoulda::Matchers::ActiveModel::AllowValueMatcher::AttributeDoesNotExistError:
   The matcher attempted to set :title on the Article to nil, but that
   attribute does not exist.
</code>```

My model looks like this...

```<code>class Article < ApplicationRecord
  # attr_accessor :title
  validates_presence_of :title
end
</code>```

and my test...

```<code>require 'rails_helper'

RSpec.describe Article do
  it { should validate_presence_of :title }
end
</code>```

If I uncomment out the attr_accessor then the test passes but I understand that it's not required with Rails.

What am I doing wrong?

答:
The attr_accessor is not required, as long as your articles database table has a title column.

You can check that in db/schema.rb.

Body:
I'm just starting to have a play with Rails (using Rspec and Shoulda Matchers) to build a demo blog.

I've literally just started and my first test is failing but I can't understand why.

I think I've set up everything correctly, but when I try to validate that a title is present on my Article model but it returns a failure

Shoulda::Matchers::ActiveModel::AllowValueMatcher::AttributeDoesNotExistError:
   The matcher attempted to set :title on the Article to nil, but that
   attribute does not exist.

My model looks like this...

class Article < ApplicationRecord
  # attr_accessor :title
  validates_presence_of :title
end

and my test...

require 'rails_helper'

RSpec.describe Article do
  it { should validate_presence_of :title }
end

If I uncomment out the attr_accessor then the test passes but I understand that it's not required with Rails.

What am I doing wrong?


问:
How to get even spacing between TextView in ConstraintLayout?
I got this issue here, which is easily fixed if I would use nested linearlayout like this:

```<code><LinearLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <LinearLayout android:layout_marginTop="32dp" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content">
        <ImageView/>
        <TexView/>
    </LinearLayout>

    <LinearLayout android:layout_marginTop="32dp" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content">
        <ImageView/>
        <TexView/>
    </LinearLayout>

    <LinearLayout android:layout_marginTop="32dp" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content">
        <ImageView/>
        <TexView/>
    </LinearLayout>
</LinearLayout>
</code>```

But is there a way to solve this in constraints layout?
In the image, the square represents a fixed size imageview, the rectangle is a textview which can 1 line (smaller height than imageview) or multiline (height is larger than imageview)

I tried constraints spacing each imageview with xDp, it is ok if ALL textviews are not higher than the imageview, but if a textview is higher than a imageview, it will overlap.
I also tried to do spacing from ImageView to TextView, but then if the TextView is smaller than the ImageView, the spacing will be wrong again.

Is there a way to solve this in ConstraintLayout?

This is how it looks in Editor

and its layout xml

```<code>  <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ImageView
            android:id="@+id/imageView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_timer_black_24dp"
            app:layout_constraintEnd_toEndOf="@+id/imageView3"
            android:layout_marginTop="24dp"
            app:layout_constraintTop_toBottomOf="@+id/imageView3" />

        <ImageView
            android:id="@+id/imageView4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_timer_black_24dp"
            app:layout_constraintEnd_toEndOf="@+id/imageView"
            android:layout_marginTop="24dp"
            app:layout_constraintTop_toBottomOf="@+id/imageView" />

        <ImageView
            android:id="@+id/imageView3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_timer_black_24dp"
            tools:layout_editor_absoluteX="40dp"
            tools:layout_editor_absoluteY="32dp" />

        <TextView
            android:id="@+id/textView2"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:fontFamily="@font/source_sans"
            android:text="This text is a lot longer and overlaps the one below which is bad."
            android:textColor="@color/primary_text"
            android:textSize="24sp"
            android:typeface="normal"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toEndOf="@+id/imageView"
            app:layout_constraintTop_toTopOf="@+id/imageView" />

        <TextView
            android:id="@+id/textView4"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:fontFamily="@font/source_sans"
            android:text="This is a normal length text and that makes it."
            android:textColor="@color/primary_text"
            android:textSize="24sp"
            android:typeface="normal"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toEndOf="@+id/imageView4"
            app:layout_constraintTop_toTopOf="@+id/imageView4"
            app:layout_constraintHorizontal_bias="0.0" />

        <TextView
            android:id="@+id/textView8"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:fontFamily="@font/source_sans"
            android:text="Small Text"
            android:textColor="@color/primary_text"
            android:textSize="24sp"
            android:typeface="normal"
            app:layout_constraintTop_toTopOf="@+id/imageView3"
            app:layout_constraintStart_toEndOf="@+id/imageView3"
            android:layout_marginStart="16dp" />

    </android.support.constraint.ConstraintLayout>
</code>```

答:
I can do that if you will change android:layout_width and android:layout_height in your ImageView to constant dimensions e.g. 48dp instead wrap_content then in your TextView add android:minHeight="48dp". Below adds an working example and xml:

```<code><android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="20dp">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="48dp"
        android:layout_height="48dp"
        app:srcCompat="@mipmap/ic_launcher"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginLeft="0dp"
        android:layout_marginTop="0dp" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:minHeight="48dp"
        android:layout_marginLeft="16dp"
        android:text="Lorem ipsum"
        app:layout_constraintLeft_toRightOf="@+id/imageView"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginStart="16dp"
        app:layout_constraintTop_toTopOf="@+id/imageView" />

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="48dp"
        android:layout_height="48dp"
        app:srcCompat="@mipmap/ic_launcher"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView"
        android:layout_marginLeft="0dp"
        android:layout_marginTop="16dp" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="16dp"
        android:minHeight="48dp"
        android:text="Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. "
        app:layout_constraintLeft_toRightOf="@+id/imageView2"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginStart="16dp"
        app:layout_constraintTop_toTopOf="@+id/imageView2" />

    <ImageView
        android:id="@+id/imageView4"
        android:layout_width="48dp"
        android:layout_height="48dp"
        app:srcCompat="@mipmap/ic_launcher"
        android:layout_marginLeft="0dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginTop="16dp"
        app:layout_constraintTop_toBottomOf="@+id/textView2" />

    <TextView
        android:id="@+id/textView4"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:minHeight="48dp"
        android:text="Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. "
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginRight="0dp"
        app:layout_constraintLeft_toRightOf="@+id/imageView4"
        android:layout_marginLeft="16dp"
        app:layout_constraintTop_toTopOf="@+id/imageView4"
        android:layout_marginTop="0dp" />

</android.support.constraint.ConstraintLayout>
</code>```

Body:
I got this issue here, which is easily fixed if I would use nested linearlayout like this:

<LinearLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <LinearLayout android:layout_marginTop="32dp" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content">
        <ImageView/>
        <TexView/>
    </LinearLayout>

    <LinearLayout android:layout_marginTop="32dp" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content">
        <ImageView/>
        <TexView/>
    </LinearLayout>

    <LinearLayout android:layout_marginTop="32dp" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content">
        <ImageView/>
        <TexView/>
    </LinearLayout>
</LinearLayout>

But is there a way to solve this in constraints layout?
In the image, the square represents a fixed size imageview, the rectangle is a textview which can 1 line (smaller height than imageview) or multiline (height is larger than imageview)

I tried constraints spacing each imageview with xDp, it is ok if ALL textviews are not higher than the imageview, but if a textview is higher than a imageview, it will overlap.
I also tried to do spacing from ImageView to TextView, but then if the TextView is smaller than the ImageView, the spacing will be wrong again.

Is there a way to solve this in ConstraintLayout?

This is how it looks in Editor

and its layout xml

  <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ImageView
            android:id="@+id/imageView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_timer_black_24dp"
            app:layout_constraintEnd_toEndOf="@+id/imageView3"
            android:layout_marginTop="24dp"
            app:layout_constraintTop_toBottomOf="@+id/imageView3" />

        <ImageView
            android:id="@+id/imageView4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_timer_black_24dp"
            app:layout_constraintEnd_toEndOf="@+id/imageView"
            android:layout_marginTop="24dp"
            app:layout_constraintTop_toBottomOf="@+id/imageView" />

        <ImageView
            android:id="@+id/imageView3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_timer_black_24dp"
            tools:layout_editor_absoluteX="40dp"
            tools:layout_editor_absoluteY="32dp" />

        <TextView
            android:id="@+id/textView2"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:fontFamily="@font/source_sans"
            android:text="This text is a lot longer and overlaps the one below which is bad."
            android:textColor="@color/primary_text"
            android:textSize="24sp"
            android:typeface="normal"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toEndOf="@+id/imageView"
            app:layout_constraintTop_toTopOf="@+id/imageView" />

        <TextView
            android:id="@+id/textView4"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:fontFamily="@font/source_sans"
            android:text="This is a normal length text and that makes it."
            android:textColor="@color/primary_text"
            android:textSize="24sp"
            android:typeface="normal"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toEndOf="@+id/imageView4"
            app:layout_constraintTop_toTopOf="@+id/imageView4"
            app:layout_constraintHorizontal_bias="0.0" />

        <TextView
            android:id="@+id/textView8"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:fontFamily="@font/source_sans"
            android:text="Small Text"
            android:textColor="@color/primary_text"
            android:textSize="24sp"
            android:typeface="normal"
            app:layout_constraintTop_toTopOf="@+id/imageView3"
            app:layout_constraintStart_toEndOf="@+id/imageView3"
            android:layout_marginStart="16dp" />

    </android.support.constraint.ConstraintLayout>

Body:
I can do that if you will change android:layout_width and android:layout_height in your ImageView to constant dimensions e.g. 48dp instead wrap_content then in your TextView add android:minHeight="48dp". Below adds an working example and xml:

<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="20dp">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="48dp"
        android:layout_height="48dp"
        app:srcCompat="@mipmap/ic_launcher"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginLeft="0dp"
        android:layout_marginTop="0dp" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:minHeight="48dp"
        android:layout_marginLeft="16dp"
        android:text="Lorem ipsum"
        app:layout_constraintLeft_toRightOf="@+id/imageView"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginStart="16dp"
        app:layout_constraintTop_toTopOf="@+id/imageView" />

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="48dp"
        android:layout_height="48dp"
        app:srcCompat="@mipmap/ic_launcher"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView"
        android:layout_marginLeft="0dp"
        android:layout_marginTop="16dp" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="16dp"
        android:minHeight="48dp"
        android:text="Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. "
        app:layout_constraintLeft_toRightOf="@+id/imageView2"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginStart="16dp"
        app:layout_constraintTop_toTopOf="@+id/imageView2" />

    <ImageView
        android:id="@+id/imageView4"
        android:layout_width="48dp"
        android:layout_height="48dp"
        app:srcCompat="@mipmap/ic_launcher"
        android:layout_marginLeft="0dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginTop="16dp"
        app:layout_constraintTop_toBottomOf="@+id/textView2" />

    <TextView
        android:id="@+id/textView4"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:minHeight="48dp"
        android:text="Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. "
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginRight="0dp"
        app:layout_constraintLeft_toRightOf="@+id/imageView4"
        android:layout_marginLeft="16dp"
        app:layout_constraintTop_toTopOf="@+id/imageView4"
        android:layout_marginTop="0dp" />

</android.support.constraint.ConstraintLayout>


问:
Python & Yelp API: how to bypass JSON response LOCATION_NOT_FOUND
I arrive to retrieve JSON from Yelp API.
Problems arrive when I search for a town but that town is not in Yelp database.
In this case I receive a response:

```<code>{
  "error": {
    "code": "LOCATION_NOT_FOUND",
    "description": "Could not execute search, try specifying a more exact location."
  }
}
</code>```

As I'm searching in bulk I would like to write a statement that says that if "LOCATION_NOT_FOUND" is inside my JSON response, do nothing and pass to the next town.

I need something like this:

```<code>if response_data['error']['code'] == 'LOCATION_NOT_FOUND':
    pass
else:
</code>```

but is not working because it says:

```<code>if response_data['error']['code'] == 'LOCATION_NOT_FOUND':
KeyError: 'error'
</code>```

this because error is not always there but just when there is no town

答:
You need to first check if there is an error. This can be done using the key in dict syntax.

```<code>if 'error' in response_data:  # Check if there is a key called "error"
    if response_data['error'].get('code') != 'LOCATION_NOT_FOUND':
        # A different code, should probably log this.
        logging.error(json.dumps(response_data))
else:
    # Continue as normal.
</code>```

Body:
I arrive to retrieve JSON from Yelp API.
Problems arrive when I search for a town but that town is not in Yelp database.
In this case I receive a response:

{
  "error": {
    "code": "LOCATION_NOT_FOUND",
    "description": "Could not execute search, try specifying a more exact location."
  }
}

As I'm searching in bulk I would like to write a statement that says that if "LOCATION_NOT_FOUND" is inside my JSON response, do nothing and pass to the next town.

I need something like this:

if response_data['error']['code'] == 'LOCATION_NOT_FOUND':
    pass
else:

but is not working because it says:

if response_data['error']['code'] == 'LOCATION_NOT_FOUND':
KeyError: 'error'

this because error is not always there but just when there is no town

Body:
You need to first check if there is an error. This can be done using the key in dict syntax.

if 'error' in response_data:  # Check if there is a key called "error"
    if response_data['error'].get('code') != 'LOCATION_NOT_FOUND':
        # A different code, should probably log this.
        logging.error(json.dumps(response_data))
else:
    # Continue as normal.


答:
I think offset will do what you want.  Unfortunately, MySQL requires a LIMIT value, but you can just put in a ridiculous number:

```<code>SELECT name
FROM names
OFFSET 1499
LIMIT 999999999;
</code>```

Title: How to select rows above #

Body:
I'm currently trying to setup a query that only selects from a row number and upwards from it. I've tried to use the LIMIT method in this way:

SELECT name FROM names LIMIT 1500, *

Which I expected to select from row number 1500 till the table's rows ended, but got a MySQL error instead.

I then tried to use a conditional for the ID of the rows like so:

SELECT name FROM names WHERE id >= 1500

Which gave unpredictable behavior since there are rows that get deleted, so it's not taking the real row numbers.

Body:
I think offset will do what you want.  Unfortunately, MySQL requires a LIMIT value, but you can just put in a ridiculous number:

SELECT name
FROM names
OFFSET 1499
LIMIT 999999999;


问:
Optimizing A Loan Portfolio On Weighted Average Criteria
EDIT: I realised that my previous attempt at a way to describe the problem wasn't very helpful and indeed didnt actually model what I'm currently doing at the moment very well, so I've rewritten the post. I've included my working code. The data in the example I will use is the lending club loan data (csv format), which can be downloaded from here: https://www.kaggle.com/wendykan/lending-club-loan-data

I'm currently utilising PuLP and pandas in python to solve an optimization issue I have at the moment. I am quite new to linear programming, and utilised it recently to solve issues around minimising cost problems.

For this lending club example, lets say I have $100,000. Given that lending club loans are securitised and can be invested in by individuals, I would like to distribute the $100,000 such that:

1.  the weighted average interest rate of the invested $100,000 cannot be below 8%.

2. The weighted average debt-to-income ratio of the invested $100,000 cannot exceed 10

Ignore for now (3. To minimise exposure to any one loan, the average loan size of the
    optimised portfolio cannot exceed $10,000.)

I am having difficulties implementing constraint 3 and the constraint of my investment ceiling of $100,000. For constraints 1 & 2, I've weighted loans by loan size and multiplied the interest rate and Debt-income ratio by the weights, and can thus model those constraints in a linear fashion such that:

```<code>Sum of weighted interest rates => 0.08
Sum of weighted debt-income ratios <= 10
</code>```

The final portfolio of loans purchased do not need to exactly equal $100,000. The objective function is to get to as close to 100,000 within the constraints i.e. LpMaximise.

I've chosen to model the selection of loans as a binary variable, as I would simply like to know if they are in or out. Furthermore, for the sake of speed and memory, I've chosen a slice of 50 rows from the data to work with.

Here is my code:

```<code>import pandas as pd
from pulp import *
import numpy as np

df = pd.read_csv('~/Desktop/loan.csv')
df.columns = [c.replace(' ','') for c in df.columns]

#cleaning up the data to get rid of spaces and to standardise percentage data

df.loc[:,'id'] = df.loc[:,'id'].astype(int)
df['int_rate'] = df['int_rate']/100     #convert interest rate to ratios.

#slicing the data to get a small sample of 50 loans
df = df.iloc[0:49,:]

#setting up the weighted averages for linear equations
sumloans = df.loc[:,'funded_amnt'].sum()
df['weights'] = df['funded_amnt'].div(sumloans,axis='index')

#Converting dataframe to weighted values!
df2 = df[["id","funded_amnt","dti","int_rate"]]
df2[["funded_amntwtd","dtiwtd","int_ratewtd"]] = df[["funded_amnt","dti","int_rate"]].multiply(df["weights"],axis="index")
df3 = pd.merge(df,df2.iloc[:,[4,5,6]],on=df["id"],how='left')

#Free up memory
df = None
df2 = None

#Variable construction
loanid = df3['id'].tolist()
dtiwtd = df3.set_index('id').to_dict()['dtiwtd']
loanmix = df3.set_index('id').to_dict()['funded_amnt']
wtdloanmix = df3.set_index('id').to_dict()['funded_amntwtd']
wa_int = df3.set_index('id').to_dict()['int_ratewtd']

id_vars = LpVariable.dicts("ID",indexs=loanid, cat='Integer',lowBound=0, upBound=1)

#Objective function added first. Summing all the loan values but examining constraints

prob = LpProblem("Funding",pulp.LpMaximize)
prob += lpSum([loanmix[i]*id_vars[i] for i in id_vars])
prob += lpSum([loanmix[i]*id_vars[i] for i in id_vars]) <= 100000 #"Sum of loans purchased must be equal to or less than $100,000"
prob += lpSum([dtiwtd[i]*id_vars[i] for i in id_vars]) <= 10 #"Sum of weighted dtis cannot be greater than 10"
prob += lpSum([wa_int[i]*id_vars[i] for i in id_vars]) >= 0.08 #"Sum of weighted interest rates cannot be less than 8%"
#Placeholder for inserting constraint on avg. loan size
prob.solve()

print("Status:", pulp.LpStatus[prob.status])

for v in prob.variables():
    print(v.name, "=", v.varValue)

print("Total amount invested = ", value(prob.objective))
</code>```

The solution status comes out as 'Unfeasible' and the output has some non binary integers.

I would appreciate any help around this matter. I'm a newbie to linear algebra and higher mathematics, but i have read this page (http://lpsolve.sourceforge.net/5.1/ratio.htm) which helped me set up the first two constraints. I'm just stuck on how to write an equation or code that would ensure the optimized portfolio has a average loan value of less than $10,000.

答:
You are doing linear programming on integers, which is more troublesome than with reals (doubles). Since your amounts can be treated as doubles, drop the ints.

Is id_vars supposed to hold amounts or proportions (adding to 1)? If the latter then you need an extra constraint on their sum. (And with your binary set up it would mean a single one and n-1 zeroes.) And if they are amounts then your weighted averages are not averages, e.g. as it stands you ensure that the sum (not average) of interest rates is at least 8%, which you can achieve with 8 loans at 1%.

Also:
If I understand the syntax correctly (I am familiar with LP but not with your library), you are trying to maximize the investment amount, under constraint that it be at least 100000. This is unexpected: why not maximize return?

Constraint 2, "average debt-to-income ratio cannot exceed 10", is mathematically incorrect. If you have 2 investments with debts d1 and d2, income i1 and i2, with proportions a and 1-a, the debt-to-income ratio of the lot is [a*d1 + (1-a)d2] / [ai1 + (1-a)i2], not ad1/i1 + (1-a)*d2/i2.

Constraint 3 would be better implemented as a series of constraints (as hinted at in the comments): loanmix[i] <= 0.1 for all i.

Minimum loan requirements are not linear (big taboo in linear programming). Indeed, they are of the form: for all i, loanmix[i] == 0 or loanmix[i] >= minloan[i]. A hack may be to discretize: instead of min of $1000, use increments of $1000. But then you are back to Integerland.

Body:
EDIT: I realised that my previous attempt at a way to describe the problem wasn't very helpful and indeed didnt actually model what I'm currently doing at the moment very well, so I've rewritten the post. I've included my working code. The data in the example I will use is the lending club loan data (csv format), which can be downloaded from here: https://www.kaggle.com/wendykan/lending-club-loan-data

I'm currently utilising PuLP and pandas in python to solve an optimization issue I have at the moment. I am quite new to linear programming, and utilised it recently to solve issues around minimising cost problems.

For this lending club example, lets say I have $100,000. Given that lending club loans are securitised and can be invested in by individuals, I would like to distribute the $100,000 such that:

1.  the weighted average interest rate of the invested $100,000 cannot be below 8%.

2. The weighted average debt-to-income ratio of the invested $100,000 cannot exceed 10

Ignore for now (3. To minimise exposure to any one loan, the average loan size of the
    optimised portfolio cannot exceed $10,000.)

I am having difficulties implementing constraint 3 and the constraint of my investment ceiling of $100,000. For constraints 1 & 2, I've weighted loans by loan size and multiplied the interest rate and Debt-income ratio by the weights, and can thus model those constraints in a linear fashion such that:

Sum of weighted interest rates => 0.08
Sum of weighted debt-income ratios <= 10

The final portfolio of loans purchased do not need to exactly equal $100,000. The objective function is to get to as close to 100,000 within the constraints i.e. LpMaximise.

I've chosen to model the selection of loans as a binary variable, as I would simply like to know if they are in or out. Furthermore, for the sake of speed and memory, I've chosen a slice of 50 rows from the data to work with.

Here is my code:

import pandas as pd
from pulp import *
import numpy as np

df = pd.read_csv('~/Desktop/loan.csv')
df.columns = [c.replace(' ','') for c in df.columns]

#cleaning up the data to get rid of spaces and to standardise percentage data

df.loc[:,'id'] = df.loc[:,'id'].astype(int)
df['int_rate'] = df['int_rate']/100     #convert interest rate to ratios.

#slicing the data to get a small sample of 50 loans
df = df.iloc[0:49,:]

#setting up the weighted averages for linear equations
sumloans = df.loc[:,'funded_amnt'].sum()
df['weights'] = df['funded_amnt'].div(sumloans,axis='index')

#Converting dataframe to weighted values!
df2 = df[["id","funded_amnt","dti","int_rate"]]
df2[["funded_amntwtd","dtiwtd","int_ratewtd"]] = df[["funded_amnt","dti","int_rate"]].multiply(df["weights"],axis="index")
df3 = pd.merge(df,df2.iloc[:,[4,5,6]],on=df["id"],how='left')

#Free up memory
df = None
df2 = None

#Variable construction
loanid = df3['id'].tolist()
dtiwtd = df3.set_index('id').to_dict()['dtiwtd']
loanmix = df3.set_index('id').to_dict()['funded_amnt']
wtdloanmix = df3.set_index('id').to_dict()['funded_amntwtd']
wa_int = df3.set_index('id').to_dict()['int_ratewtd']

id_vars = LpVariable.dicts("ID",indexs=loanid, cat='Integer',lowBound=0, upBound=1)

#Objective function added first. Summing all the loan values but examining constraints

prob = LpProblem("Funding",pulp.LpMaximize)
prob += lpSum([loanmix[i]*id_vars[i] for i in id_vars])
prob += lpSum([loanmix[i]*id_vars[i] for i in id_vars]) <= 100000 #"Sum of loans purchased must be equal to or less than $100,000"
prob += lpSum([dtiwtd[i]*id_vars[i] for i in id_vars]) <= 10 #"Sum of weighted dtis cannot be greater than 10"
prob += lpSum([wa_int[i]*id_vars[i] for i in id_vars]) >= 0.08 #"Sum of weighted interest rates cannot be less than 8%"
#Placeholder for inserting constraint on avg. loan size
prob.solve()

print("Status:", pulp.LpStatus[prob.status])

for v in prob.variables():
    print(v.name, "=", v.varValue)

print("Total amount invested = ", value(prob.objective))

The solution status comes out as 'Unfeasible' and the output has some non binary integers.

I would appreciate any help around this matter. I'm a newbie to linear algebra and higher mathematics, but i have read this page (http://lpsolve.sourceforge.net/5.1/ratio.htm) which helped me set up the first two constraints. I'm just stuck on how to write an equation or code that would ensure the optimized portfolio has a average loan value of less than $10,000.