问:
Are there any better ways to check this condition in Java 8?
I need to simplify following code in java.  Are there any way to using set and do this ?</p>

```<code>      if (!(((AdministrativeState.PLANNED == dispensingOccasionModel.getOccasionDTO().getAdminState()) ||
             (AdministrativeState.MISSED == dispensingOccasionModel.getOccasionDTO().getAdminState()) ||
             (AdministrativeState.SKIPPED == dispensingOccasionModel.getOccasionDTO().getAdminState()) ||
             (AdministrativeState.SELF_ADMINISTERED == dispensingOccasionModel.getOccasionDTO().getAdminState()) ||
(AdministrativeState.SELF_ADMINISTERED_BY_RANGE == dispensingOccasionModel.getOccasionDTO().getAdminState())) &&
        isSpecialDoseType(doseDetail))
</code>```

答:
It is unclear what data types are we dealing with here so I can't give you a better answer until you can shed more light on this. But assuming AdministrativeState is an enumerator you can do something like this:

```<code>public enum AdministrativeState {

    NONE, PLANNED, MISSED, SKIPPED, SELF_ADMINISTERED,
    SELF_ADMINISTERED_BY_RANGE;
}

public static class OccasionModel {

    AdministrativeState state;

    OccasionModel() {
        this.state = AdministrativeState.NONE;
    }

    OccasionModel setState(AdministrativeState state) {
        this.state = state;
    }
}

public static void checkAdminState(OccasionModel model) {

    OccasionModel dispensingOccasionModel = model;

    if (dispensingOccasionModel.state != AdministrativeState.NONE) {
        // Do something here...
    }
    else System.out.println("Administrative state is not set yet");
}

public static void main(String[] args) throws IOException {

    checkAdminState(new OccasionModel());
    checkAdminState(new OccasionModel().setState(AdministrativeState.PLANNED));
}
</code>```

I am not sure if this is what you're looking for but this doesn't have anything to do with Java 8 in particular. If you can provide more information about what's what I can help you out further.

Body:
I need to simplify following code in java.  Are there any way to using set and do this ?

      if (!(((AdministrativeState.PLANNED == dispensingOccasionModel.getOccasionDTO().getAdminState()) ||
             (AdministrativeState.MISSED == dispensingOccasionModel.getOccasionDTO().getAdminState()) ||
             (AdministrativeState.SKIPPED == dispensingOccasionModel.getOccasionDTO().getAdminState()) ||
             (AdministrativeState.SELF_ADMINISTERED == dispensingOccasionModel.getOccasionDTO().getAdminState()) ||
(AdministrativeState.SELF_ADMINISTERED_BY_RANGE == dispensingOccasionModel.getOccasionDTO().getAdminState())) &&
        isSpecialDoseType(doseDetail))

Body:
It is unclear what data types are we dealing with here so I can't give you a better answer until you can shed more light on this. But assuming AdministrativeState is an enumerator you can do something like this:

public enum AdministrativeState {

    NONE, PLANNED, MISSED, SKIPPED, SELF_ADMINISTERED,
    SELF_ADMINISTERED_BY_RANGE;
}

public static class OccasionModel {

    AdministrativeState state;

    OccasionModel() {
        this.state = AdministrativeState.NONE;
    }

    OccasionModel setState(AdministrativeState state) {
        this.state = state;
    }
}

public static void checkAdminState(OccasionModel model) {

    OccasionModel dispensingOccasionModel = model;

    if (dispensingOccasionModel.state != AdministrativeState.NONE) {
        // Do something here...
    }
    else System.out.println("Administrative state is not set yet");
}

public static void main(String[] args) throws IOException {

    checkAdminState(new OccasionModel());
    checkAdminState(new OccasionModel().setState(AdministrativeState.PLANNED));
}

I am not sure if this is what you're looking for but this doesn't have anything to do with Java 8 in particular. If you can provide more information about what's what I can help you out further.


来源: stackexchange

问:
How to display group_concat result seperately in html table cell?
On my previous question How to group array value duplicate and customize the display of the results of the array in html table? which has not been answered yet, I opt in other way to display the 5 rows only.

This is the database:

```<code> lid   class_id   class         Q1-2      Q3-4      total   item_group
-----  -------    -----         -----    -----      -----   ----------
   1     73       Leader        5000      50000     10000      33
   1     77       Consultant    4000      4000      8000       33
   1     83       Coordinator   3000      3000      6000       33
   2     73       Leader        10000     10000     20000      33
   2     76       Staff         4000      4000      8000       33
   2     77       Consultant    5000      50000     10000      33
   3     73       Leader        15000     15000     30000      33
   3     78       Team Leader   4000      4000      8000       33
</code>```

Here is the SQL query that I used:

```<code>$sql = "SELECT *, group_concat(AZ.lid) as lids, group_concat(AZ.total) AS totals FROM (
    SELECT * FROM view_items WHERE lid='1'
    UNION
    SELECT * FROM view_items WHERE lid='2'
    UNION
    SELECT * FROM view_items WHERE lid='3'
) AS AZ WHERE item_group='33' GROUP BY class_id";
</code>```

This is the SQL result:

```<code>class id    class        lid    Q1-2    Q3-4     lids    totals             item_group
---------   -----       ------  -----   -----    -----   ------             ----------
   73      Leader         1     5000    5000     1,2,3   10000,20000,30000     33
   77      Consultant     1     4000    4000     1,2     8000,10000            33
   83      Coordinator    1     3000    3000     1       6000                  33
   76      Staff          2                      2       8000                  33
   78      Team Leader    3                      3       8000                  33
</code>```

$proj_lid->lid is equals to 1 (Displayed in the P1 column only)

$row->lid is equals to 1 (Displayed in the P1 column only)

$limit is 3 (The count of P's)

This is the html table part:

```<code><?php
 for($iy=1; $iy<=$limit; $iy++){
    $sql_lid =  "SELECT * FROM view_items WHERE lid='$iy' GROUP BY lib_id ORDER BY lid ASC";
    $query_lid = $this->db->prepare($sql_lid);
    $query_lid->execute();
    $res=$query_lid->fetch();
    $lids = $res->lid;
    $lid_arr[] = $lids ;
    $sql_arr = "";
    if($iy==1) $sql_arr .= "SELECT *, group_concat(AZ.lid) as lids, group_concat(AZ.total) AS totals FROM (";
    $sql_arr.="SELECT * FROM view_items WHERE lid='$lids'";
    if($iy!=$limit) $sql_arr .= " UNION ";
    if($iy==$limit)  $sql_arr.=" ) AS AZ WHERE item_group='33' GROUP BY class_id";
    $sqlArr[] = $sql_arr;
}
 $sql = implode("",$sqlArr);
 $query = $this->db->prepare($sql);
 $query = $this->db->prepare($sql);
 $query->execute();
 $result = $query->fetchAll();
 foreach($result as $row){
    if($row->item_group == "33"){
        $q1 = ($row->q1-2)
        $q3 = ($row->q3-4)
        $total = $q1 + $q3;
?>
<tr>
    <td><?php echo $row->class; ?></td>
    <td><?php if($q1 != 0 && $proj_li->lid == $row->lid){ echo ($q1 < 0 ? "(".number_format(abs($q1),2).")" : number_format($q1,2));} else{ echo "-";} ?> </td>
    <td><?php if($q3 != 0 && $proj_lid->lid == $row->lid ){ echo ($q3 < 0 ? "(".number_format(abs($q3),2).")" : number_format($q3,2));} else{ echo "-";} ?> </td>
    <td><?php if($total != 0 && $proj_lid->lid == $row->lid ){ echo ($total < 0 ? "(".number_format(abs($total),2).")" : number_format($total,2));} else{ echo "-";} ?> </td>
<?php
    $totals = explode(", ", $row->totals);
    foreach ($totals as $rowstotals) {
    }
    for($i = 1; $i <= $limit; $i++){
    if ($i != $proj_lid->lid && $proJ-lid->lid < $i){
?>
      <td><?php if($rowstotals != 0){ echo ($rowstotals < 0 ? "(".number_format(abs($rowstotals),2).")" : number_format($rowstotals,2));} else{ echo "-";}?></td>
<?php
    } else{ }
   }
  }
 }
?>
</tr>
</code>```

I managed to display the expected output

Expected Output (with 5 rows only, no duplicate class id)

But another problem occurred in displaying the group_concat values separately. I need the values in P2 and P3 to display only one result from the group_concat.

This should be the expected output

UPDATE: I found (maybe) a similar output to what I want to do (forgot where I saw this link)
Link

答:
This is what I had in mind:

```<code>SELECT lid, class_id,class, `Q1-2`,`Q3-4`,total,
       CASE WHEN COUNT(*)>=2 THEN SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(total ORDER BY lid ASC SEPARATOR ' '),' ',2),' ',-1) END AS P2,
       CASE WHEN COUNT(*)>=3 THEN SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(total ORDER BY lid ASC SEPARATOR ' '),' ',3),' ',-1) END AS P3
      FROM (SELECT * FROM view_items WHERE lid='1' UNION
            SELECT * FROM view_items WHERE lid='2' UNION
            SELECT * FROM view_items WHERE lid='3' ) AS AZ
      WHERE item_group='33'
GROUP BY class_id ORDER BY lid ASC;
</code>```

I use SUBSTRING_INDEX function twice on a GROUP_CONCAT value that is 2 or more but in this example I stopped at 3 count. I also added ORDER BY lid ASC in GROUP_CONCAT to make sure that it will return value ordered by lid.

ContentLicense: CC BY-SA 4.0

Body:
On my previous question How to group array value duplicate and customize the display of the results of the array in html table? which has not been answered yet, I opt in other way to display the 5 rows only.

This is the database:

 lid   class_id   class         Q1-2      Q3-4      total   item_group
-----  -------    -----         -----    -----      -----   ----------
   1     73       Leader        5000      50000     10000      33
   1     77       Consultant    4000      4000      8000       33
   1     83       Coordinator   3000      3000      6000       33
   2     73       Leader        10000     10000     20000      33
   2     76       Staff         4000      4000      8000       33
   2     77       Consultant    5000      50000     10000      33
   3     73       Leader        15000     15000     30000      33
   3     78       Team Leader   4000      4000      8000       33

Here is the SQL query that I used:

$sql = "SELECT *, group_concat(AZ.lid) as lids, group_concat(AZ.total) AS totals FROM (
    SELECT * FROM view_items WHERE lid='1'
    UNION
    SELECT * FROM view_items WHERE lid='2'
    UNION
    SELECT * FROM view_items WHERE lid='3'
) AS AZ WHERE item_group='33' GROUP BY class_id";

This is the SQL result:

class id    class        lid    Q1-2    Q3-4     lids    totals             item_group
---------   -----       ------  -----   -----    -----   ------             ----------
   73      Leader         1     5000    5000     1,2,3   10000,20000,30000     33
   77      Consultant     1     4000    4000     1,2     8000,10000            33
   83      Coordinator    1     3000    3000     1       6000                  33
   76      Staff          2                      2       8000                  33
   78      Team Leader    3                      3       8000                  33

$proj_lid->lid is equals to 1 (Displayed in the P1 column only)

$row->lid is equals to 1 (Displayed in the P1 column only)

$limit is 3 (The count of P's)

This is the html table part:

<?php
 for($iy=1; $iy<=$limit; $iy++){
    $sql_lid =  "SELECT * FROM view_items WHERE lid='$iy' GROUP BY lib_id ORDER BY lid ASC";
    $query_lid = $this->db->prepare($sql_lid);
    $query_lid->execute();
    $res=$query_lid->fetch();
    $lids = $res->lid;
    $lid_arr[] = $lids ;
    $sql_arr = "";
    if($iy==1) $sql_arr .= "SELECT *, group_concat(AZ.lid) as lids, group_concat(AZ.total) AS totals FROM (";
    $sql_arr.="SELECT * FROM view_items WHERE lid='$lids'";
    if($iy!=$limit) $sql_arr .= " UNION ";
    if($iy==$limit)  $sql_arr.=" ) AS AZ WHERE item_group='33' GROUP BY class_id";
    $sqlArr[] = $sql_arr;
}
 $sql = implode("",$sqlArr);
 $query = $this->db->prepare($sql);
 $query = $this->db->prepare($sql);
 $query->execute();
 $result = $query->fetchAll();
 foreach($result as $row){
    if($row->item_group == "33"){
        $q1 = ($row->q1-2)
        $q3 = ($row->q3-4)
        $total = $q1 + $q3;
?>

    <?php echo $row->class; ?>
    <?php if($q1 != 0 && $proj_li->lid == $row->lid){ echo ($q1 < 0 ? "(".number_format(abs($q1),2).")" : number_format($q1,2));} else{ echo "-";} ?>
    <?php if($q3 != 0 && $proj_lid->lid == $row->lid ){ echo ($q3 < 0 ? "(".number_format(abs($q3),2).")" : number_format($q3,2));} else{ echo "-";} ?>
    <?php if($total != 0 && $proj_lid->lid == $row->lid ){ echo ($total < 0 ? "(".number_format(abs($total),2).")" : number_format($total,2));} else{ echo "-";} ?>
<?php
    $totals = explode(", ", $row->totals);
    foreach ($totals as $rowstotals) {
    }
    for($i = 1; $i <= $limit; $i++){
    if ($i != $proj_lid->lid && $proJ-lid->lid < $i){
?>
      <?php if($rowstotals != 0){ echo ($rowstotals < 0 ? "(".number_format(abs($rowstotals),2).")" : number_format($rowstotals,2));} else{ echo "-";}?>
<?php
    } else{ }
   }
  }
 }
?>

I managed to display the expected output

Expected Output (with 5 rows only, no duplicate class id)

But another problem occurred in displaying the group_concat values separately. I need the values in P2 and P3 to display only one result from the group_concat.

This should be the expected output

UPDATE: I found (maybe) a similar output to what I want to do (forgot where I saw this link)
Link

Body:
This is what I had in mind:

SELECT lid, class_id,class, `Q1-2`,`Q3-4`,total,
       CASE WHEN COUNT(*)>=2 THEN SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(total ORDER BY lid ASC SEPARATOR ' '),' ',2),' ',-1) END AS P2,
       CASE WHEN COUNT(*)>=3 THEN SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(total ORDER BY lid ASC SEPARATOR ' '),' ',3),' ',-1) END AS P3
      FROM (SELECT * FROM view_items WHERE lid='1' UNION
            SELECT * FROM view_items WHERE lid='2' UNION
            SELECT * FROM view_items WHERE lid='3' ) AS AZ
      WHERE item_group='33'
GROUP BY class_id ORDER BY lid ASC;

I use SUBSTRING_INDEX function twice on a GROUP_CONCAT value that is 2 or more but in this example I stopped at 3 count. I also added ORDER BY lid ASC in GROUP_CONCAT to make sure that it will return value ordered by lid.


问:
How can I run a "DELETE FROM TABLE" with jdbc in spark 2.4?
I'm using a code like this:

```<code>spark.read.format("jdbc").options(Map("url" -> "jdbc:url"))
</code>```

I need to use a DELETE FROM.

答:
DELETE/ UPDATE are not supported in Native Open source Spark.

There has been some effort in bringing this support as part of various Open source projects like HUDI, Iceberg, Delta.

Body:
I'm using a code like this:

spark.read.format("jdbc").options(Map("url" -> "jdbc:url"))

I need to use a DELETE FROM.


问:
Hailstone Java Program
I am working on The hailstone sequence program in which the user picks a positive integer. If number is even, it will be divided by two. If the number is odd, it'll be multiplied it by three and added by one. The program will continue until the number is equal to 1. The program will also tell the user the amount of steps it took to reach 1.

The goal is to be done recursively, my issue is that I am unable to declare each step to the user as the calculation happens to the number, for e.g "number is so I divide by 2 and it = "

This is my code so far, any suggestions or alternatives will help.

Thanks

import javax.swing*

```<code>{
   public class hailstone {
   static int Count;
   static int HailstoneNumbers(int Num)
   output += (Num + " " ) ;
   JOptionPane.showMessageDialog(null, output);

    if (Num == 1 && Count == 0) {
        return Count;

    }
    else if (Num == 1 && Count != 0) {
        //n-1
        Count++;
        return Count;
    }
    else if (Num % 2 == 0) {
        Count++;
        HailstoneNumbers(Num / 2);
    }
    else if (Num % 2 != 0) {
        Count++;
         HailstoneNumbers(3 * Num + 1);
    }
    return Count;

}

public static void main(String[] args)
{
    int Num = Integer.parseInt(JOptionPane.showInputDialog("\n Enter a positive number"));
    int x;

    x = HailstoneNumbers(Num);

   JOptionPane.showMessageDialog(null, "Number of Steps" + x );
}
</code>```

}

答:
Another solution. Simplified by putting the print statement in the method.  Also, user should not have to worry about initializing the step count so I overloaded the collatz method. Note:  The official name of this is the Collatz Conjecture so I named the methods accordingly.

   public int collatz(int v) {
      return hail(v, 0);
   }

   private int collatz(int v, int count) {
      System.out.println(v);
      if (v != 1) {
         return hail((v & 1) == 1 ? v * 3 + 1
               : v / 2, count + 1);
      }
      return count;
   }
```

Title: Hailstone Java Program

Body:
I am working on The hailstone sequence program in which the user picks a positive integer. If number is even, it will be divided by two. If the number is odd, it'll be multiplied it by three and added by one. The program will continue until the number is equal to 1. The program will also tell the user the amount of steps it took to reach 1.

The goal is to be done recursively, my issue is that I am unable to declare each step to the user as the calculation happens to the number, for e.g "number is so I divide by 2 and it = "

This is my code so far, any suggestions or alternatives will help.

Thanks

import javax.swing*

{
   public class hailstone {
   static int Count;
   static int HailstoneNumbers(int Num)
   output += (Num + " " ) ;
   JOptionPane.showMessageDialog(null, output);

    if (Num == 1 && Count == 0) {
        return Count;

    }
    else if (Num == 1 && Count != 0) {
        //n-1
        Count++;
        return Count;
    }
    else if (Num % 2 == 0) {
        Count++;
        HailstoneNumbers(Num / 2);
    }
    else if (Num % 2 != 0) {
        Count++;
         HailstoneNumbers(3 * Num + 1);
    }
    return Count;

}

public static void main(String[] args)
{
    int Num = Integer.parseInt(JOptionPane.showInputDialog("\n Enter a positive number"));
    int x;

    x = HailstoneNumbers(Num);

   JOptionPane.showMessageDialog(null, "Number of Steps" + x );
}

}


问:
Algorithm for finding a formula that connects inputs and outputs
I seem to recall having learned a method for finding the formula that connects inputs and outputs from a table. For example:

```<code>a b c | r
1 1 0 | 0
0 1 1 | 1
1 1 1 | 1
</code>```

where "r" is the result, and a, b and c are the inputs. The method involved equations with many unknowns and ended up with a formula that explained it all. (This is an example that is not that meaningful, since r = c, but you get the idea).

However, I can not remember the details, and not enough keywords to be able to find it on the web. The subject teaching this method also included a lot of boolean algebra.

I know this is a vague question, but what could this method for finding the formula from a table of values be?

答: I think you mean the Cunjunctive Normal Form. You need the complete truth table for this, though.</p>

ContentLicense: CC BY-SA 3.0

Body:
I seem to recall having learned a method for finding the formula that connects inputs and outputs from a table. For example:

a b c | r
1 1 0 | 0
0 1 1 | 1
1 1 1 | 1

where "r" is the result, and a, b and c are the inputs. The method involved equations with many unknowns and ended up with a formula that explained it all. (This is an example that is not that meaningful, since r = c, but you get the idea).

However, I can not remember the details, and not enough keywords to be able to find it on the web. The subject teaching this method also included a lot of boolean algebra.

I know this is a vague question, but what could this method for finding the formula from a table of values be?


问:
How to find and extract certain string from XML and replace in another XML document
can someone help me on how to extract certain string from xml and replace in another xml. Like I want to extract only mediaId from second line of 1.XML

```<code>- <sample_settings_config version="23" mediaId="0x6868">
</code>```

and replace it in 2.xml document (code of both XML's are same except the mediaId).

Where as 1.xml location is dynamic (C:\users\xxxx\Documents), so am looking for append, find extract and replace. :(

I am trying for Python or batch script.

struggling with this batch script

```<code>setlocal EnableDelayedExpansion

(Set UPD=C:\Users)

(Set UDS=\RAP\Documents\MB)

For /F "delims=" %%a in ('findstr /I /L "mediaId" 1.xml') do (
   set "line=%%a"
   set "line=!line:*<string>=!"
   for /F "delims=<" %%b in ("!line!") do echo %%b
</code>```

but it is not working, any help is appreciated, thank you.

答:
from xml.etree.ElementTree import ElementTree

tree = ElementTree()

tree.parse("1.xml")
root = tree.getroot()
media_id = root.find('sample_settings_config').attrib['mediaId']

tree.parse("2.xml")
root = tree.getroot()
root.find('sample_settings_config').attrib['mediaId'] = media_id
tree.write('2.xml', xml_declaration=True)
```

<p>You can use <code>xml.etree.ElementTree</code> to read and
write to XML, by the use of Python.</p>

<p>The code imports <code>ElementTree</code> and an instance is
created as <code>tree</code>. From <code>tree</code>, the XML file is
parsed and get the <code>root</code>. Then, find the tag
<code>sample_settings_config</code> and get the value of the
attribute of <code>mediaId</code>.</p>

<p>Repeat the parsing, get <code>root</code> and find the tag.
Update the dictionary key of <code>mediaId</code> with the
value stored in the variable <code>media_id</code>.
Write the modified content to the XML file.</p>

<p><strong>1.xml</strong>:</p>

<pre class="lang-xml prettyprint-override"><code><?xml version='1.0' encoding='us-ascii'?>
<root>
  <sample_settings_config version="123" mediaId="0x6868">
    "XML File 1"
  </sample_settings_config>
</root>
</code>```

2.xml:

<?xml version='1.0' encoding='us-ascii'?>
<root>
  <sample_settings_config version="456" mediaId="0x0">
    "XML File 2"
  </sample_settings_config>
</root>
```

<p><strong>2.xml modified</strong>:</p>

<pre class="lang-xml prettyprint-override"><code><?xml version='1.0' encoding='us-ascii'?>
<root>
  <sample_settings_config mediaId="0x6868" version="456">
    "XML File 2"
  </sample_settings_config>
</root>
</code>```

Body:
can someone help me on how to extract certain string from xml and replace in another xml. Like I want to extract only mediaId from second line of 1.XML

- <sample_settings_config version="23" mediaId="0x6868">

and replace it in 2.xml document (code of both XML's are same except the mediaId).

Where as 1.xml location is dynamic (C:\users\xxxx\Documents), so am looking for append, find extract and replace. :(

I am trying for Python or batch script.

struggling with this batch script

setlocal EnableDelayedExpansion

(Set UPD=C:\Users)

(Set UDS=\RAP\Documents\MB)

For /F "delims=" %%a in ('findstr /I /L "mediaId" 1.xml') do (
   set "line=%%a"
   set "line=!line:*<string>=!"
   for /F "delims=<" %%b in ("!line!") do echo %%b

but it is not working, any help is appreciated, thank you.

Body:
from xml.etree.ElementTree import ElementTree

tree = ElementTree()

tree.parse("1.xml")
root = tree.getroot()
media_id = root.find('sample_settings_config').attrib['mediaId']

tree.parse("2.xml")
root = tree.getroot()
root.find('sample_settings_config').attrib['mediaId'] = media_id
tree.write('2.xml', xml_declaration=True)

You can use xml.etree.ElementTree to read and
write to XML, by the use of Python.

The code imports ElementTree and an instance is
created as tree. From tree, the XML file is
parsed and get the root. Then, find the tag
sample_settings_config and get the value of the
attribute of mediaId.

Repeat the parsing, get root and find the tag.
Update the dictionary key of mediaId with the
value stored in the variable media_id.
Write the modified content to the XML file.

1.xml:

<?xml version='1.0' encoding='us-ascii'?>
<root>
  <sample_settings_config version="123" mediaId="0x6868">
    "XML File 1"
  </sample_settings_config>
</root>

2.xml:

<?xml version='1.0' encoding='us-ascii'?>
<root>
  <sample_settings_config version="456" mediaId="0x0">
    "XML File 2"
  </sample_settings_config>
</root>

2.xml modified:

<?xml version='1.0' encoding='us-ascii'?>
<root>
  <sample_settings_config mediaId="0x6868" version="456">
    "XML File 2"
  </sample_settings_config>
</root>


问:
How to add margins between columns in Bootsrap4?
I try to arrange 3 sections columns equally by assigning either col-lg-4 or col-lg-3 for each of them with Bootsstrap 4.

With col-lg-4 or any responsive combination that takes total of 12 columns, I get no margin between the columns.

With col-lg-3 the margins become too wide.

The same problem arises with both "container" and "container-fluid" class.

I tried also to adjust the margins manually, replacing mx-auto with Bootstrap4 margin set at m-3, but it does not solve the problem because in that case all the columns move to the left, leaving empty space on the right side of the screen.

The problem arises the moment I try to put margins. Otherwise, if there are no margins I can set col-lg-4 without a problem. I will get for instance 3 nice columns. But once I put margins, it becomes wrong. I followed the recommendation on https://getbootstrap.com/docs/4.0/utilities/spacing/ but still it does not help.

* {
  box-sizing: border-box;
}

body {
    font-size: 16px;
    color: black;
    background-color: #eeeeee;
    font-family: 'Oxygen', sans-serif;
  }

 .navbar {
    background-color: rgb(178, 238, 13);
    border-radius: 0;
    border: 0;
    margin: 0;
    padding: 0;
  }

  #collapsibleNavbar {
    background-color: rgb(229, 243, 192);
    text-align: center;
  }

  .navbar-nav li a {
    color: black;
    border-style: solid;
    border-width: 1px;
  }

  .navbar-brand {
      color: black;
      padding: 15px;
  }

  h5{
    margin-bottom: 15px;
    padding-top: 7px;
  }

  h2{
    font-size: 175%;
    margin-bottom: 30px;
    margin-top: 20px;
  }

  .paraf{
    background-color: #e6ee9c;
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
 <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Module 3</title>
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <link rel="stylesheet" href="styles.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</head>
<body>

<header>
    <nav class="navbar navbar-expand-md navbar-light">
            Food, LLC

            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">
                    <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="collapsibleNavbar">
                    <ul class="d-lg-none d-md-none navbar-nav">
                      <li class="nav-item">
                        Chicken
                      </li>
                      <li class="nav-item">
                        Beef
                      </li>
                      <li class="nav-item">
                        Sushi
                      </li>
                    </ul>
                  </div>
    </nav>

</header>
<h2 class="text-center"> Our Menu </h2>

<div class="container">
<div class="row">

<div class="col-lg-4 col-md-6 col-sm-12 col-12 paraf mx-auto">
<h5 class="text-center" id="chicken">Chicken</h5>
<p>Lorem ipsum dolor sit amet, consectetur felis ut venenatis tortor, nulla fringilla commodo eget ullamcorper
viverra nulla. Quis donec ultricies, in non eget ultricies ut wisi pede. Eget faucibus ligula lacinia, ligula risus quasi,
vestibulum amet mattis mi sit egestas, a velit integer, feugiat lectus et. Ullamcorper ut lobortis est, consequat magnis,
donec lorem posuere sit ridiculus lacinia augue, morbi magna velit pellentesque a vestibulum arcu, in facilisi ultricies
dolor eu dolor quis. Nec eu libero, fermentum sagittis augue wisi wisi adipiscing. Est risus dapibus cursus, praesent
vivamus mattis est, ac euismod quis. Primis diam enim tortor fermentum, varius pede officia pellentesque nibh quam
blandit, accumsan vestibulum interdum vivamus, iaculis wisi lacus sodales facilisi. Molestie accusantium, sed nisl
ratione eu euismod nulla ac, morbi aliquet. Lacus egestas. Purus sem fusce et id nibh mauris, luctus magnis diam morbi
enim, nunc iste, laoreet commodo in tortor lobortis. Congue suspendisse pellentesque eget, nibh pulvinar dolor donec
hac, quis diam at vehicula suspendisse. Eget commodo libero, tortor integer, nec integer, mauris eget iaculis nec
imperdiet dolor eros.
Lorem ipsum dolor sit amet, consectetur felis ut venenatis tortor, nulla fringilla commodo eget ullamcorper
viverra nulla. Quis donec ultricies, in non eget ultricies ut wisi pede. Eget faucibus ligula lacinia, ligula risus quasi,
vestibulum amet mattis mi sit egestas, a velit integer, feugiat lectus et. Ullamcorper ut lobortis est, consequat magnis,
donec lorem posuere sit ridiculus lacinia augue, morbi magna velit pellentesque a vestibulum arcu, in facilisi ultricies
dolor eu dolor quis. Nec eu libero, fermentum sagittis augue wisi wisi adipiscing. Est risus dapibus cursus, praesent
vivamus mattis est, ac euismod quis. Primis diam enim tortor fermentum, varius pede officia pellentesque nibh quam
blandit, accumsan vestibulum interdum vivamus, iaculis wisi lacus sodales facilisi. Molestie accusantium, sed nisl
ratione eu euismod nulla ac, morbi aliquet. Lacus egestas. Purus sem fusce et id nibh mauris, luctus magnis diam morbi
enim, nunc iste, laoreet commodo in tortor lobortis. Congue suspendisse pellentesque eget, nibh pulvinar dolor donec
hac, quis diam at vehicula suspendisse. Eget commodo libero, tortor integer, nec integer, mauris eget iaculis nec
imperdiet dolor eros. <br> (End of Chicken section) Back to Top</p></div>

<div class="col-lg-4 col-md-6 col-sm-12 col-12 paraf mx-auto">
<h5 class="text-center" id="beef">Beef</h5>
<p>Lorem ipsum dolor sit amet, consectetur felis ut venenatis tortor, nulla fringilla commodo eget ullamcorper
viverra nulla. Quis donec ultricies, in non eget ultricies ut wisi pede. Eget faucibus ligula lacinia, ligula risus quasi,
vestibulum amet mattis mi sit egestas, a velit integer, feugiat lectus et. Ullamcorper ut lobortis est, consequat magnis,
donec lorem posuere sit ridiculus lacinia augue, morbi magna velit pellentesque a vestibulum arcu, in facilisi ultricies
dolor eu dolor quis. Nec eu libero, fermentum sagittis augue wisi wisi adipiscing. Est risus dapibus cursus, praesent
vivamus mattis est, ac euismod quis. Primis diam enim tortor fermentum, varius pede officia pellentesque nibh quam
blandit, accumsan vestibulum interdum vivamus, iaculis wisi lacus sodales facilisi. Molestie accusantium, sed nisl
ratione eu euismod nulla ac, morbi aliquet. Lacus egestas. Purus sem fusce et id nibh mauris, luctus magnis diam morbi
enim, nunc iste, laoreet commodo in tortor lobortis. Congue suspendisse pellentesque eget, nibh pulvinar dolor donec
hac, quis diam at vehicula suspendisse. Eget commodo libero, tortor integer, nec integer, mauris eget iaculis nec
imperdiet dolor eros.
Lorem ipsum dolor sit amet, consectetur felis ut venenatis tortor, nulla fringilla commodo eget ullamcorper
viverra nulla. Quis donec ultricies, in non eget ultricies ut wisi pede. Eget faucibus ligula lacinia, ligula risus quasi,
vestibulum amet mattis mi sit egestas, a velit integer, feugiat lectus et. Ullamcorper ut lobortis est, consequat magnis,
donec lorem posuere sit ridiculus lacinia augue, morbi magna velit pellentesque a vestibulum arcu, in facilisi ultricies
dolor eu dolor quis. Nec eu libero, fermentum sagittis augue wisi wisi adipiscing. Est risus dapibus cursus, praesent
vivamus mattis est, ac euismod quis. Primis diam enim tortor fermentum, varius pede officia pellentesque nibh quam
blandit, accumsan vestibulum interdum vivamus, iaculis wisi lacus sodales facilisi. Molestie accusantium, sed nisl
ratione eu euismod nulla ac, morbi aliquet. Lacus egestas. Purus sem fusce et id nibh mauris, luctus magnis diam morbi
enim, nunc iste, laoreet commodo in tortor lobortis. Congue suspendisse pellentesque eget, nibh pulvinar dolor donec
hac, quis diam at vehicula suspendisse. Eget commodo libero, tortor integer, nec integer, mauris eget iaculis nec
imperdiet dolor eros.<br>(End of Beef section) Back to Top</p></div>

<div class="col-lg-4 col-md-12 col-sm-12 col-12 paraf mx-auto">
<h5 class="text-center" id="sushi">Sushi</h5>
<p>Lorem ipsum dolor sit amet, consectetur felis ut venenatis tortor, nulla fringilla commodo eget ullamcorper
viverra nulla. Quis donec ultricies, in non eget ultricies ut wisi pede. Eget faucibus ligula lacinia, ligula risus quasi,
vestibulum amet mattis mi sit egestas, a velit integer, feugiat lectus et. Ullamcorper ut lobortis est, consequat magnis,
donec lorem posuere sit ridiculus lacinia augue, morbi magna velit pellentesque a vestibulum arcu, in facilisi ultricies
dolor eu dolor quis. Nec eu libero, fermentum sagittis augue wisi wisi adipiscing. Est risus dapibus cursus, praesent
vivamus mattis est, ac euismod quis. Primis diam enim tortor fermentum, varius pede officia pellentesque nibh quam
blandit, accumsan vestibulum interdum vivamus, iaculis wisi lacus sodales facilisi. Molestie accusantium, sed nisl
ratione eu euismod nulla ac, morbi aliquet. Lacus egestas. Purus sem fusce et id nibh mauris, luctus magnis diam morbi
enim, nunc iste, laoreet commodo in tortor lobortis. Congue suspendisse pellentesque eget, nibh pulvinar dolor donec
hac, quis diam at vehicula suspendisse. Eget commodo libero, tortor integer, nec integer, mauris eget iaculis nec
imperdiet dolor eros.
Lorem ipsum dolor sit amet, consectetur felis ut venenatis tortor, nulla fringilla commodo eget ullamcorper
viverra nulla. Quis donec ultricies, in non eget ultricies ut wisi pede. Eget faucibus ligula lacinia, ligula risus quasi,
vestibulum amet mattis mi sit egestas, a velit integer, feugiat lectus et. Ullamcorper ut lobortis est, consequat magnis,
donec lorem posuere sit ridiculus lacinia augue, morbi magna velit pellentesque a vestibulum arcu, in facilisi ultricies
dolor eu dolor quis. Nec eu libero, fermentum sagittis augue wisi wisi adipiscing. Est risus dapibus cursus, praesent
vivamus mattis est, ac euismod quis. Primis diam enim tortor fermentum, varius pede officia pellentesque nibh quam
blandit, accumsan vestibulum interdum vivamus, iaculis wisi lacus sodales facilisi. Molestie accusantium, sed nisl
ratione eu euismod nulla ac, morbi aliquet. Lacus egestas. Purus sem fusce et id nibh mauris, luctus magnis diam morbi
enim, nunc iste, laoreet commodo in tortor lobortis. Congue suspendisse pellentesque eget, nibh pulvinar dolor donec
hac, quis diam at vehicula suspendisse. Eget commodo libero, tortor integer, nec integer, mauris eget iaculis nec
imperdiet dolor eros.<br>(End of Sushi section) Back to Top</p></div>
</div>
</div>

</body>
</html></code>```

Can you suggest how to fix this and get margins between the columns.

答: Just add mt-2 and mb-2 in your class col-md-3.

Body:
I try to arrange 3 sections columns equally by assigning either col-lg-4 or col-lg-3 for each of them with Bootsstrap 4.

With col-lg-4 or any responsive combination that takes total of 12 columns, I get no margin between the columns.

With col-lg-3 the margins become too wide.

The same problem arises with both "container" and "container-fluid" class.

I tried also to adjust the margins manually, replacing mx-auto with Bootstrap4 margin set at m-3, but it does not solve the problem because in that case all the columns move to the left, leaving empty space on the right side of the screen.

The problem arises the moment I try to put margins. Otherwise, if there are no margins I can set col-lg-4 without a problem. I will get for instance 3 nice columns. But once I put margins, it becomes wrong. I followed the recommendation on https://getbootstrap.com/docs/4.0/utilities/spacing/ but still it does not help.

* {
  box-sizing: border-box;
}

body {
    font-size: 16px;
    color: black;
    background-color: #eeeeee;
    font-family: 'Oxygen', sans-serif;
  }

 .navbar {
    background-color: rgb(178, 238, 13);
    border-radius: 0;
    border: 0;
    margin: 0;
    padding: 0;
  }

  #collapsibleNavbar {
    background-color: rgb(229, 243, 192);
    text-align: center;
  }

  .navbar-nav li a {
    color: black;
    border-style: solid;
    border-width: 1px;
  }

  .navbar-brand {
      color: black;
      padding: 15px;
  }

  h5{
    margin-bottom: 15px;
    padding-top: 7px;
  }

  h2{
    font-size: 175%;
    margin-bottom: 30px;
    margin-top: 20px;
  }

  .paraf{
    background-color: #e6ee9c;
  }

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
 <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Module 3</title>
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <link rel="stylesheet" href="styles.css">

            Food, LLC

            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">

            </button>

                        Chicken

                        Beef

                        Sushi

 Our Menu

Chicken

Lorem ipsum dolor sit amet, consectetur felis ut venenatis tortor, nulla fringilla commodo eget ullamcorper
viverra nulla. Quis donec ultricies, in non eget ultricies ut wisi pede. Eget faucibus ligula lacinia, ligula risus quasi,
vestibulum amet mattis mi sit egestas, a velit integer, feugiat lectus et. Ullamcorper ut lobortis est, consequat magnis,
donec lorem posuere sit ridiculus lacinia augue, morbi magna velit pellentesque a vestibulum arcu, in facilisi ultricies
dolor eu dolor quis. Nec eu libero, fermentum sagittis augue wisi wisi adipiscing. Est risus dapibus cursus, praesent
vivamus mattis est, ac euismod quis. Primis diam enim tortor fermentum, varius pede officia pellentesque nibh quam
blandit, accumsan vestibulum interdum vivamus, iaculis wisi lacus sodales facilisi. Molestie accusantium, sed nisl
ratione eu euismod nulla ac, morbi aliquet. Lacus egestas. Purus sem fusce et id nibh mauris, luctus magnis diam morbi
enim, nunc iste, laoreet commodo in tortor lobortis. Congue suspendisse pellentesque eget, nibh pulvinar dolor donec
hac, quis diam at vehicula suspendisse. Eget commodo libero, tortor integer, nec integer, mauris eget iaculis nec
imperdiet dolor eros.
Lorem ipsum dolor sit amet, consectetur felis ut venenatis tortor, nulla fringilla commodo eget ullamcorper
viverra nulla. Quis donec ultricies, in non eget ultricies ut wisi pede. Eget faucibus ligula lacinia, ligula risus quasi,
vestibulum amet mattis mi sit egestas, a velit integer, feugiat lectus et. Ullamcorper ut lobortis est, consequat magnis,
donec lorem posuere sit ridiculus lacinia augue, morbi magna velit pellentesque a vestibulum arcu, in facilisi ultricies
dolor eu dolor quis. Nec eu libero, fermentum sagittis augue wisi wisi adipiscing. Est risus dapibus cursus, praesent
vivamus mattis est, ac euismod quis. Primis diam enim tortor fermentum, varius pede officia pellentesque nibh quam
blandit, accumsan vestibulum interdum vivamus, iaculis wisi lacus sodales facilisi. Molestie accusantium, sed nisl
ratione eu euismod nulla ac, morbi aliquet. Lacus egestas. Purus sem fusce et id nibh mauris, luctus magnis diam morbi
enim, nunc iste, laoreet commodo in tortor lobortis. Congue suspendisse pellentesque eget, nibh pulvinar dolor donec
hac, quis diam at vehicula suspendisse. Eget commodo libero, tortor integer, nec integer, mauris eget iaculis nec
imperdiet dolor eros.
 (End of Chicken section) Back to Top

Beef

Lorem ipsum dolor sit amet, consectetur felis ut venenatis tortor, nulla fringilla commodo eget ullamcorper
viverra nulla. Quis donec ultricies, in non eget ultricies ut wisi pede. Eget faucibus ligula lacinia, ligula risus quasi,
vestibulum amet mattis mi sit egestas, a velit integer, feugiat lectus et. Ullamcorper ut lobortis est, consequat magnis,
donec lorem posuere sit ridiculus lacinia augue, morbi magna velit pellentesque a vestibulum arcu, in facilisi ultricies
dolor eu dolor quis. Nec eu libero, fermentum sagittis augue wisi wisi adipiscing. Est risus dapibus cursus, praesent
vivamus mattis est, ac euismod quis. Primis diam enim tortor fermentum, varius pede officia pellentesque nibh quam
blandit, accumsan vestibulum interdum vivamus, iaculis wisi lacus sodales facilisi. Molestie accusantium, sed nisl
ratione eu euismod nulla ac, morbi aliquet. Lacus egestas. Purus sem fusce et id nibh mauris, luctus magnis diam morbi
enim, nunc iste, laoreet commodo in tortor lobortis. Congue suspendisse pellentesque eget, nibh pulvinar dolor donec
hac, quis diam at vehicula suspendisse. Eget commodo libero, tortor integer, nec integer, mauris eget iaculis nec
imperdiet dolor eros.
Lorem ipsum dolor sit amet, consectetur felis ut venenatis tortor, nulla fringilla commodo eget ullamcorper
viverra nulla. Quis donec ultricies, in non eget ultricies ut wisi pede. Eget faucibus ligula lacinia, ligula risus quasi,
vestibulum amet mattis mi sit egestas, a velit integer, feugiat lectus et. Ullamcorper ut lobortis est, consequat magnis,
donec lorem posuere sit ridiculus lacinia augue, morbi magna velit pellentesque a vestibulum arcu, in facilisi ultricies
dolor eu dolor quis. Nec eu libero, fermentum sagittis augue wisi wisi adipiscing. Est risus dapibus cursus, praesent
vivamus mattis est, ac euismod quis. Primis diam enim tortor fermentum, varius pede officia pellentesque nibh quam
blandit, accumsan vestibulum interdum vivamus, iaculis wisi lacus sodales facilisi. Molestie accusantium, sed nisl
ratione eu euismod nulla ac, morbi aliquet. Lacus egestas. Purus sem fusce et id nibh mauris, luctus magnis diam morbi
enim, nunc iste, laoreet commodo in tortor lobortis. Congue suspendisse pellentesque eget, nibh pulvinar dolor donec
hac, quis diam at vehicula suspendisse. Eget commodo libero, tortor integer, nec integer, mauris eget iaculis nec
imperdiet dolor eros.
(End of Beef section) Back to Top

Sushi

Lorem ipsum dolor sit amet, consectetur felis ut venenatis tortor, nulla fringilla commodo eget ullamcorper
viverra nulla. Quis donec ultricies, in non eget ultricies ut wisi pede. Eget faucibus ligula lacinia, ligula risus quasi,
vestibulum amet mattis mi sit egestas, a velit integer, feugiat lectus et. Ullamcorper ut lobortis est, consequat magnis,
donec lorem posuere sit ridiculus lacinia augue, morbi magna velit pellentesque a vestibulum arcu, in facilisi ultricies
dolor eu dolor quis. Nec eu libero, fermentum sagittis augue wisi wisi adipiscing. Est risus dapibus cursus, praesent
vivamus mattis est, ac euismod quis. Primis diam enim tortor fermentum, varius pede officia pellentesque nibh quam
blandit, accumsan vestibulum interdum vivamus, iaculis wisi lacus sodales facilisi. Molestie accusantium, sed nisl
ratione eu euismod nulla ac, morbi aliquet. Lacus egestas. Purus sem fusce et id nibh mauris, luctus magnis diam morbi
enim, nunc iste, laoreet commodo in tortor lobortis. Congue suspendisse pellentesque eget, nibh pulvinar dolor donec
hac, quis diam at vehicula suspendisse. Eget commodo libero, tortor integer, nec integer, mauris eget iaculis nec
imperdiet dolor eros.
Lorem ipsum dolor sit amet, consectetur felis ut venenatis tortor, nulla fringilla commodo eget ullamcorper
viverra nulla. Quis donec ultricies, in non eget ultricies ut wisi pede. Eget faucibus ligula lacinia, ligula risus quasi,
vestibulum amet mattis mi sit egestas, a velit integer, feugiat lectus et. Ullamcorper ut lobortis est, consequat magnis,
donec lorem posuere sit ridiculus lacinia augue, morbi magna velit pellentesque a vestibulum arcu, in facilisi ultricies
dolor eu dolor quis. Nec eu libero, fermentum sagittis augue wisi wisi adipiscing. Est risus dapibus cursus, praesent
vivamus mattis est, ac euismod quis. Primis diam enim tortor fermentum, varius pede officia pellentesque nibh quam
blandit, accumsan vestibulum interdum vivamus, iaculis wisi lacus sodales facilisi. Molestie accusantium, sed nisl
ratione eu euismod nulla ac, morbi aliquet. Lacus egestas. Purus sem fusce et id nibh mauris, luctus magnis diam morbi
enim, nunc iste, laoreet commodo in tortor lobortis. Congue suspendisse pellentesque eget, nibh pulvinar dolor donec
hac, quis diam at vehicula suspendisse. Eget commodo libero, tortor integer, nec integer, mauris eget iaculis nec
imperdiet dolor eros.
(End of Sushi section) Back to Top

Can you suggest how to fix this and get margins between the columns.


问:
How to set column mapping relation when generating entities in Haskell?
I am trying to use Persistent to access my database. I know that Persistent can generate the code of entity, but there is something I can't generate so easily.
Like I got a table which looks like:

```<code>CREATE TABLE `user` (
  `user_id` bigint(11) NOT NULL,
  `user_name` varchar(255) DEFAULT NULL,
  `user_password` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
</code>```

then my haskell code like :

```<code>mkPersist sqlSettings [persistLowerCase|
User
  name String
  password String
  deriving Show
|]
</code>```

These fields are different include the primary key, I want to set their mapping relation. The official page (https://www.yesodweb.com/book/persistent) doesn't say how to do it.

Need I write the code to define it instead of generating it?

答:
I've found it on this page https://github.com/yesodweb/persistent/blob/master/docs/Persistent-entity-syntax.md

I can do some customization follow these syntax.

Body:
I am trying to use Persistent to access my database. I know that Persistent can generate the code of entity, but there is something I can't generate so easily.
Like I got a table which looks like:

CREATE TABLE `user` (
  `user_id` bigint(11) NOT NULL,
  `user_name` varchar(255) DEFAULT NULL,
  `user_password` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

then my haskell code like :

mkPersist sqlSettings [persistLowerCase|
User
  name String
  password String
  deriving Show
|]

These fields are different include the primary key, I want to set their mapping relation. The official page (https://www.yesodweb.com/book/persistent) doesn't say how to do it.

Need I write the code to define it instead of generating it?


问:
How to conditionally cast a type in dart?
It seems if it's just a variable, I can conditionally cast like this.

```<code>Animal animal = Dog();
if (animal is Dog) {
  animal.bark(); // animal is of type Dog here
}
</code>```

But if it's a property on a class, how do I conditionally cast?

```<code>House house = House()
house.animal = Dog();
if (house.animal is Dog) {
  house.animal.bark(); // fail
}
</code>```

I know I can do it like this

```<code>if (house.animal is Dog) {
  Dog animal = house.animal;
  animal.bark();
}
</code>```

But that seems cumbersome. Is there anyway I can check and cast type in one go like I can with variables?

Thanks a lot.

答:
tl;dr

Replace multiple field accesses by a local variable.

final house = House()..animal = Dog()
final animal = house.animal;

if (animal is Dog) {
  animal.bark();
} else if (animal is Cat) {
  animal.meow();
} else if (animal is Wolf) {
  animal.howl();
}
```
<h1>Complete answer</h1>
<p>This is a Dart limitation. It happens because the compiler cannot guarantee that the result of the first access to <code>animal</code> is the same as the second access. Even is the field is final, a subclass may override its getter to change the return value at different accesses.</p>
<p>Check the adapted example below from Leaf Petersen. (Thanks @jamesdlin for mentioning.)</p>
<pre class="lang-dart prettyprint-override"><code>class A {
  final num x = 3;
}

class B extends A {
  num y = 3;
  num get x => y;
}

void main() {
  B b = B();
  A a = b;
  if (a.x is int) {
    b.y = 3.0;
    (a.x as int).isEven; // Fall down go boom.
  }
}
</code>```

One way to work around that is by avoiding multiple field accesses. This can be done by assigning the result of the field access to a local variable such as:

final house = House()..animal = Dog()
final animal = house.animal;

if (animal is Dog) {
  animal.bark();
} else if (animal is Cat) {
  animal.meow();
} else if (animal is Wolf) {
  animal.howl();
}
```

Body:
It seems if it's just a variable, I can conditionally cast like this.

Animal animal = Dog();
if (animal is Dog) {
  animal.bark(); // animal is of type Dog here
}

But if it's a property on a class, how do I conditionally cast?

House house = House()
house.animal = Dog();
if (house.animal is Dog) {
  house.animal.bark(); // fail
}

I know I can do it like this

if (house.animal is Dog) {
  Dog animal = house.animal;
  animal.bark();
}

But that seems cumbersome. Is there anyway I can check and cast type in one go like I can with variables?

Thanks a lot.

Body:
tl;dr

Replace multiple field accesses by a local variable.

final house = House()..animal = Dog()
final animal = house.animal;

if (animal is Dog) {
  animal.bark();
} else if (animal is Cat) {
  animal.meow();
} else if (animal is Wolf) {
  animal.howl();
}

Complete answer

This is a Dart limitation. It happens because the compiler cannot guarantee that the result of the first access to animal is the same as the second access. Even is the field is final, a subclass may override its getter to change the return value at different accesses.

Check the adapted example below from Leaf Petersen. (Thanks @jamesdlin for mentioning.)

class A {
  final num x = 3;
}

class B extends A {
  num y = 3;
  num get x => y;
}

void main() {
  B b = B();
  A a = b;
  if (a.x is int) {
    b.y = 3.0;
    (a.x as int).isEven; // Fall down go boom.
  }
}

One way to work around that is by avoiding multiple field accesses. This can be done by assigning the result of the field access to a local variable such as:

final house = House()..animal = Dog()
final animal = house.animal;

if (animal is Dog) {
  animal.bark();
} else if (animal is Cat) {
  animal.meow();
} else if (animal is Wolf) {
  animal.howl();
}


问:
java.lang.ClassNotFoundException throwing some error
```<code>java.lang.ClassNotFoundException: org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
</code>```

I added following jar files:

```<code>commons-fileupload-1.2.1.jar
commons-logging-1.1.1.jar
freemarker-2.3.16.jar
ognl-3.0.jar
servlet-api.jar
struts2-core-2.2.1.jar
xwork-core-2.2.1.jar
</code>```

答: According to findjar you may have to add struts2-core-2.1.6.jar or above

Body:
java.lang.ClassNotFoundException: org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter

I added following jar files:

commons-fileupload-1.2.1.jar
commons-logging-1.1.1.jar
freemarker-2.3.16.jar
ognl-3.0.jar
servlet-api.jar
struts2-core-2.2.1.jar
xwork-core-2.2.1.jar


问:
Nodejs - How do HTTP responses always hit the right device?
Нello to all! A while ago I asked this question. After helpful responses I learned that the web, by design, makes it impossible to directly differentiate devices connected to the same router.

So for example, the code below can never be 100% functional...

```<code>require('http').createServer((req, res) => {

    let uniqueDeviceId = getUniqueDeviceId(req);

}).listen(80, '<my public ip>', 511);
</code>```

... because there's no way to implement getUniqueDeviceId in a guaranteed way. It can't just return req.connection.remoteAddress, as multiple devices could have the same address.

Given this, my question is: How does res.end(...) always respond to the correct device??

E.g. consider this simple server:

```<code>require('http').createServer((req, res) => {

    res.end(req.url);

}).listen(80, '{{my public ip}}', 511);
</code>```

Take two different devices, connected to the same IP address. Each device uses its own url:

Device 1 uses http://{{my public ip}}/device1

Device 2 uses http://{{my public ip}}/device2

Now both these devices bombard their url with thousands of requests per second.

In response, Device 1 will always get /device1, and Device 2 will always get /device2, even with this configuration that should lead to race conditions!

Even though I can't determine a device's unique id directly, res.end will always correspond to the appropriate req - it will never blunder and send a response to some different req, even if that different req was received at almost exactly the same time, from the same IP address. To me this is proof that at some level, lower than Nodejs, unique device IDs can be determined.

If this is correct, at what level of HTTP architecture do we get the guarantee that a response will always go back to its initial requester? And how is this implemented?

答:
"To me this is proof that at some level, lower than Nodejs, unique device IDs can be determined"

-- No, it's not the "unique device ID" that can be determined, but the unique "IP - Port" combination that is determined.

For example, in your case, Device 1 and Device 2 are hidden behind a router, which makes their IP identical (the IP of router) to your web server. However, although they have the same IP, their port are different.

For Device 1, from your Node.js web server's point of view, the socket (combination of SourceIP/Port - DestinationIP/Port) could be:

```<code>{{RouterIP}}:{{PortX}} - {{Node.js serverIP}}:{{Node.js serverPort}}
</code>```

For Device 2, from your Node.js web server's point of view, the socket could be:

```<code>{{RouterIP}}:{{PortY}} - {{Node.js serverIP}}:{{Node.js serverPort}}
</code>```

Thus, although Device 1 and Device 2 have the same IP, the HTTP response would be returned to corresponding port in router -- response for device 1 would be returned to PortX of router, while response for device 2 would be returned to PortY.

Then, inside the router, there is a mapping, such as:

```<code>{{PortX}} - {{Device 1's private IP}}:{{Device 1's Port}}
{{PortY}} - {{Device 2's private IP}}:{{Device 2's Port}}
</code>```

So, the response returned to PortX of router woule be redirected to Device 1 (and its corresponding port), and the response returned to PortY would be redirected to Device 2.

This is called NAT, and above description is just a very simple example.

"what level of HTTP architecture do we get the guarantee that a response will always go back to its initial requester? And how is this implemented?"

-- This has nothing to do with HTTP, it's belong to IP layer. The implementation happens in router. Web application developer don't need to do anything.

Body:
Нello to all! A while ago I asked this question. After helpful responses I learned that the web, by design, makes it impossible to directly differentiate devices connected to the same router.

So for example, the code below can never be 100% functional...

require('http').createServer((req, res) => {

    let uniqueDeviceId = getUniqueDeviceId(req);

}).listen(80, '<my public ip>', 511);

... because there's no way to implement getUniqueDeviceId in a guaranteed way. It can't just return req.connection.remoteAddress, as multiple devices could have the same address.

Given this, my question is: How does res.end(...) always respond to the correct device??

E.g. consider this simple server:

require('http').createServer((req, res) => {

    res.end(req.url);

}).listen(80, '{{my public ip}}', 511);

Take two different devices, connected to the same IP address. Each device uses its own url:

Device 1 uses http://{{my public ip}}/device1

Device 2 uses http://{{my public ip}}/device2

Now both these devices bombard their url with thousands of requests per second.

In response, Device 1 will always get /device1, and Device 2 will always get /device2, even with this configuration that should lead to race conditions!

Even though I can't determine a device's unique id directly, res.end will always correspond to the appropriate req - it will never blunder and send a response to some different req, even if that different req was received at almost exactly the same time, from the same IP address. To me this is proof that at some level, lower than Nodejs, unique device IDs can be determined.

If this is correct, at what level of HTTP architecture do we get the guarantee that a response will always go back to its initial requester? And how is this implemented?

Body:
"To me this is proof that at some level, lower than Nodejs, unique device IDs can be determined"

-- No, it's not the "unique device ID" that can be determined, but the unique "IP - Port" combination that is determined.

For example, in your case, Device 1 and Device 2 are hidden behind a router, which makes their IP identical (the IP of router) to your web server. However, although they have the same IP, their port are different.

For Device 1, from your Node.js web server's point of view, the socket (combination of SourceIP/Port - DestinationIP/Port) could be:

{{RouterIP}}:{{PortX}} - {{Node.js serverIP}}:{{Node.js serverPort}}

For Device 2, from your Node.js web server's point of view, the socket could be:

{{RouterIP}}:{{PortY}} - {{Node.js serverIP}}:{{Node.js serverPort}}

Thus, although Device 1 and Device 2 have the same IP, the HTTP response would be returned to corresponding port in router -- response for device 1 would be returned to PortX of router, while response for device 2 would be returned to PortY.

Then, inside the router, there is a mapping, such as:

{{PortX}} - {{Device 1's private IP}}:{{Device 1's Port}}
{{PortY}} - {{Device 2's private IP}}:{{Device 2's Port}}

So, the response returned to PortX of router woule be redirected to Device 1 (and its corresponding port), and the response returned to PortY would be redirected to Device 2.

This is called NAT, and above description is just a very simple example.

"what level of HTTP architecture do we get the guarantee that a response will always go back to its initial requester? And how is this implemented?"

-- This has nothing to do with HTTP, it's belong to IP layer. The implementation happens in router. Web application developer don't need to do anything.


问:
How do I make my react app still run with lint errors?
I am working on a React application with webpack, when I run 'npm start' it takes a long time to build, but if there are lint errors it will fail at the end of the build with 'Exit status 1' and I will need to fix the error and then run 'npm start'.

The errors are things like 'un-used var', 'line too long' etc. so they shouldn't stop the app from running, and it wastes my time to wait for it to build again.

I still want to see the lint errors, but how can I stop them from causing the build to Exit?

答:
If the lint error/warning causes the exit, you may want to update your eslint loader configuration according to this https://github.com/webpack-contrib/eslint-loader#errors-and-warning

A simple instruction:

1.Go to your Webpack configuration file.

Find a loader called 'eslint-loader', you may exepect something like this:

```<code>rules: [
  {
    test: /\.js$/,
    exclude: /node_modules/,
    loader: "eslint-loader",
    options: {
    /* this is the eslint-loader option */
      failOnWarning: true
    }
  }
]
</code>```

2.In the options filed under the eslint-loader. you may want to update this field to something like:

```<code>rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: "eslint-loader",
        options: {
        /* this is the eslint-loader option */
          failOnWarning: false,
          failOnError: false
        }
      }
    ]
</code>```

In this case, though your eslint-loader find error/warnings. The building won't crash. (though this is not recommended)

Body:
If the lint error/warning causes the exit, you may want to update your eslint loader configuration according to this https://github.com/webpack-contrib/eslint-loader#errors-and-warning

A simple instruction:

1.Go to your Webpack configuration file.

Find a loader called 'eslint-loader', you may exepect something like this:

rules: [
  {
    test: /\.js$/,
    exclude: /node_modules/,
    loader: "eslint-loader",
    options: {
    /* this is the eslint-loader option */
      failOnWarning: true
    }
  }
]

2.In the options filed under the eslint-loader. you may want to update this field to something like:

rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: "eslint-loader",
        options: {
        /* this is the eslint-loader option */
          failOnWarning: false,
          failOnError: false
        }
      }
    ]

In this case, though your eslint-loader find error/warnings. The building won't crash. (though this is not recommended)


问:
Hive partitioned table reads all the partitions despite having a Spark filter
I'm using spark with scala to read a specific Hive partition. The partition is year, month, day, a and b

scala> spark.sql("select * from db.table where year=2019 and month=2 and day=28 and a='y' and b='z'").show

But I get this error:

org.apache.spark.SparkException: Job aborted due to stage failure: Task 236 in stage 0.0 failed 4 times, most recent failure: Lost task 236.3 in stage 0.0 (TID 287, server, executor 17): org.apache.hadoop.security.AccessControlException: Permission denied: user=user, access=READ, inode="/path-to-table/table/year=2019/month=2/day=27/a=w/b=x/part-00002":user:group:-rw-rw----

As you can see, spark is trying to read a different partition and I don't have permisions there.

It shouldn't be, because I created a filter and this filter is my partition.

I tried the same query with Hive and it's works perfectly (No access problems)

Hive> select * from db.table where year=2019 and month=2 and day=28 and a='y' and b='z';

Why is spark trying to read this partition and Hive doesn't?

There is a Spark configuration that am I missing?

Edit: More information

Some files were created with Hive, others were copied from one server and pasted to our server with different permissions (we can not change the permissions), then they should have refreshed the data.

We are using:
cloudera 5.13.2.1
hive 1.1.0
spark 2.3.0
hadoop 2.6.0
scala 2.11.8
java 1.8.0_144

Show create table

```<code>|CREATE EXTERNAL TABLE Columns and type
PARTITIONED BY (`year` int COMMENT '*', `month` int COMMENT '*', `day` int COMMENT '*', `a` string COMMENT '*', `b` string COMMENT '*')
ROW FORMAT SERDE 'org.apache.hadoop.hive.ql.io.parquet.serde.ParquetHiveSerDe'
WITH SERDEPROPERTIES (
 'serialization.format' = '1'
)
STORED AS
 INPUTFORMAT 'org.apache.hadoop.hive.ql.io.parquet.MapredParquetInputFormat'
 OUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.parquet.MapredParquetOutputFormat'
LOCATION 'hdfs://path'
TBLPROPERTIES (
 'transient_lastDdlTime' = '1559029332'
)
|
</code>```

答:
This can happen when metastore does not have the partition values for the partition column.
Can we run from Spark

```<code>ALTER TABLE db.table RECOVER PARTITIONS
</code>```

And then rerun the same query.

Body:
I'm using spark with scala to read a specific Hive partition. The partition is year, month, day, a and b

scala> spark.sql("select * from db.table where year=2019 and month=2 and day=28 and a='y' and b='z'").show

But I get this error:

org.apache.spark.SparkException: Job aborted due to stage failure: Task 236 in stage 0.0 failed 4 times, most recent failure: Lost task 236.3 in stage 0.0 (TID 287, server, executor 17): org.apache.hadoop.security.AccessControlException: Permission denied: user=user, access=READ, inode="/path-to-table/table/year=2019/month=2/day=27/a=w/b=x/part-00002":user:group:-rw-rw----

As you can see, spark is trying to read a different partition and I don't have permisions there.

It shouldn't be, because I created a filter and this filter is my partition.

I tried the same query with Hive and it's works perfectly (No access problems)

Hive> select * from db.table where year=2019 and month=2 and day=28 and a='y' and b='z';

Why is spark trying to read this partition and Hive doesn't?

There is a Spark configuration that am I missing?

Edit: More information

Some files were created with Hive, others were copied from one server and pasted to our server with different permissions (we can not change the permissions), then they should have refreshed the data.

We are using:
cloudera 5.13.2.1
hive 1.1.0
spark 2.3.0
hadoop 2.6.0
scala 2.11.8
java 1.8.0_144

Show create table

|CREATE EXTERNAL TABLE Columns and type
PARTITIONED BY (`year` int COMMENT '*', `month` int COMMENT '*', `day` int COMMENT '*', `a` string COMMENT '*', `b` string COMMENT '*')
ROW FORMAT SERDE 'org.apache.hadoop.hive.ql.io.parquet.serde.ParquetHiveSerDe'
WITH SERDEPROPERTIES (
 'serialization.format' = '1'
)
STORED AS
 INPUTFORMAT 'org.apache.hadoop.hive.ql.io.parquet.MapredParquetInputFormat'
 OUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.parquet.MapredParquetOutputFormat'
LOCATION 'hdfs://path'
TBLPROPERTIES (
 'transient_lastDdlTime' = '1559029332'
)
|

Body:
This can happen when metastore does not have the partition values for the partition column.
Can we run from Spark

ALTER TABLE db.table RECOVER PARTITIONS

And then rerun the same query.


问:
Take a screenshot of a web page with firefox webextension?
I need write webextension that can take screenshot and save it on hard drive (better in folder i specify) can some one share with me peace of code or point to good tutorial about this?</p>

答:
Firefox has a feature that takes screenshots. If this is what you are looking for.

Another option would be to print that whole page and save it as a pdf to your drive.


问:
Batch Filtering with Multi-Filter throws a 'Class attribute not set' exception
We have a data set of 15k classified tweets with which we need to perform sentiment analysis. I would like to test against a test set of 5k classified tweets. Due to Weka needing the same attributes within the header of the test set as exist in the header of training set, I will have to use batch filtering if I want to be able to run my classifier against this 5k test set.

However, there are several filters that I need to run my training set through, so I figured the running a multifilter against the training set would be a good idea. The multifilter works fine when not running the batch argument, but when I try to batch filter I get an error from the CLI as it tried to execute the first filter within the multi-filter:

CLI multiFilter command w/batch argument:

```<code>java weka.filters.MultiFilter -F "weka.filters.supervised.instance.Resample -B 1.0 -S 1 -Z 15.0 -no-replacement" \
-F "weka.filters.unsupervised.attribute.StringToWordVector -R first-last -W 100000 -prune-rate -1.0 -N 0 -S -stemmer weka.core.stemmers.NullStemmer -M 2 -tokenizer weka.core.tokenizers.AlphabeticTokenizer" \
-F "weka.filters.unsupervised.attribute.Reorder -R 2-last,first"\
-F "weka.filters.supervised.attribute.AttributeSelection -E \"weka.attributeSelection.InfoGainAttributeEval \" -S \"weka.attributeSelection.Ranker -T 0.0 -N -1\"" \
-F weka.filters.AllFilter \
-b -i input\Train.arff -o output\Train_b_out.arff -r input\Test.arff -s output\Test_b_out.arff
</code>```

Here is the resultant error from the CLI:

```<code>weka.core.UnassignedClassException: weka.filters.supervised.instance.Resample: Class attribute not set!
at weka.core.Capabilities.test(Capabilities.java:1091)
at weka.core.Capabilities.test(Capabilities.java:1023)
at weka.core.Capabilities.testWithFail(Capabilities.java:1302)
at weka.filters.Filter.testInputFormat(Filter.java:434)
at weka.filters.Filter.setInputFormat(Filter.java:452)
at weka.filters.SimpleFilter.setInputFormat(SimpleFilter.java:195)
at weka.filters.Filter.batchFilterFile(Filter.java:1243)
at weka.filters.Filter.runFilter(Filter.java:1319)
at weka.filters.MultiFilter.main(MultiFilter.java:425)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at weka.gui.SimpleCLIPanel$ClassRunner.run(SimpleCLIPanel.java:265)
</code>```

And here are the headers with a portion of data for both the training and test input arffs:

Training:

```<code>@RELATION classifiedTweets
@ATTRIBUTE @@sentence@@ string
@ATTRIBUTE @@class@@ {1,-1,0}
@DATA
"Conditioning be very important for curly dry hair",0
"Combine with Sunday paper coupon and",0
"Price may vary by store",0
"Oil be not really moisturizers",-1
</code>```

Testing:

```<code>@RELATION classifiedTweets
@ATTRIBUTE @@sentence@@ string
@ATTRIBUTE @@class@@ {1,-1,0}
@DATA
"5",0
"I give the curl a good form and discipline",1
"I have be cowashing every day",0
"LOL",0
"TITLETITLE Walgreens Weekly and Midweek Deal",0
"And then they walk away",0
</code>```

Am I doing something wrong here? I know that supervised resampling requires the class attribute to be on the bottom of the attribute list within the header, and it is... within both the test and training input files.

EDIT:

Further testing reveals that this error does not occur with relationship to the batch filtering, it occurs whenever I run the supervised resample filter from the CLI... The data that I use works on every other filter I've tried within the CLI, so I don't understand why this filter is any different... resampling the data in the GUI works fine as well...

Update:

This also happens with the SMOTE filter instead of the resample filter

答:
You could have used the multifilter along with the ClassAssigner method to make it work:

java -classpath $jcp weka.filters.MultiFilter
     -F "weka.filters.unsupervised.attribute.ClassAssigner -C last"
     -F "weka.filters.supervised.instance.Resample -B 1.0 -S 1 -Z 66.0"
```

Body:
We have a data set of 15k classified tweets with which we need to perform sentiment analysis. I would like to test against a test set of 5k classified tweets. Due to Weka needing the same attributes within the header of the test set as exist in the header of training set, I will have to use batch filtering if I want to be able to run my classifier against this 5k test set.

However, there are several filters that I need to run my training set through, so I figured the running a multifilter against the training set would be a good idea. The multifilter works fine when not running the batch argument, but when I try to batch filter I get an error from the CLI as it tried to execute the first filter within the multi-filter:

CLI multiFilter command w/batch argument:

java weka.filters.MultiFilter -F "weka.filters.supervised.instance.Resample -B 1.0 -S 1 -Z 15.0 -no-replacement" \
-F "weka.filters.unsupervised.attribute.StringToWordVector -R first-last -W 100000 -prune-rate -1.0 -N 0 -S -stemmer weka.core.stemmers.NullStemmer -M 2 -tokenizer weka.core.tokenizers.AlphabeticTokenizer" \
-F "weka.filters.unsupervised.attribute.Reorder -R 2-last,first"\
-F "weka.filters.supervised.attribute.AttributeSelection -E \"weka.attributeSelection.InfoGainAttributeEval \" -S \"weka.attributeSelection.Ranker -T 0.0 -N -1\"" \
-F weka.filters.AllFilter \
-b -i input\Train.arff -o output\Train_b_out.arff -r input\Test.arff -s output\Test_b_out.arff

Here is the resultant error from the CLI:

weka.core.UnassignedClassException: weka.filters.supervised.instance.Resample: Class attribute not set!
at weka.core.Capabilities.test(Capabilities.java:1091)
at weka.core.Capabilities.test(Capabilities.java:1023)
at weka.core.Capabilities.testWithFail(Capabilities.java:1302)
at weka.filters.Filter.testInputFormat(Filter.java:434)
at weka.filters.Filter.setInputFormat(Filter.java:452)
at weka.filters.SimpleFilter.setInputFormat(SimpleFilter.java:195)
at weka.filters.Filter.batchFilterFile(Filter.java:1243)
at weka.filters.Filter.runFilter(Filter.java:1319)
at weka.filters.MultiFilter.main(MultiFilter.java:425)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at weka.gui.SimpleCLIPanel$ClassRunner.run(SimpleCLIPanel.java:265)

And here are the headers with a portion of data for both the training and test input arffs:

Training:

@RELATION classifiedTweets
@ATTRIBUTE @@sentence@@ string
@ATTRIBUTE @@class@@ {1,-1,0}
@DATA
"Conditioning be very important for curly dry hair",0
"Combine with Sunday paper coupon and",0
"Price may vary by store",0
"Oil be not really moisturizers",-1

Testing:

@RELATION classifiedTweets
@ATTRIBUTE @@sentence@@ string
@ATTRIBUTE @@class@@ {1,-1,0}
@DATA
"5",0
"I give the curl a good form and discipline",1
"I have be cowashing every day",0
"LOL",0
"TITLETITLE Walgreens Weekly and Midweek Deal",0
"And then they walk away",0

Am I doing something wrong here? I know that supervised resampling requires the class attribute to be on the bottom of the attribute list within the header, and it is... within both the test and training input files.

EDIT:

Further testing reveals that this error does not occur with relationship to the batch filtering, it occurs whenever I run the supervised resample filter from the CLI... The data that I use works on every other filter I've tried within the CLI, so I don't understand why this filter is any different... resampling the data in the GUI works fine as well...

Update:

This also happens with the SMOTE filter instead of the resample filter


问:
Knn using Cross Validation function
I need to run the R code to find the number of folder = 1 for k=(c(1:12)) but the following warnings were displayed:

```<code>> warnings()
Mensagens de aviso:
1: model fit failed for Fold1.Rep1: k= 1 Error in x[1, 1] : subscript out of bounds

2: model fit failed for Fold1.Rep1: k= 2 Error in x[1, 1] : subscript out of bounds

3: model fit failed for Fold1.Rep1: k= 3 Error in x[1, 1] : subscript out of bounds

. . .

12: model fit failed for Fold1.Rep1: k=12 Error in x[1, 1] : subscript out of bounds

13: In nominalTrainWorkflow(x = x, y = y, wts = weights, info = trainInfo,  ... :
  There were missing values in resampled performance measures.
</code>```

This is a R code using caret package.

```<code>biopsy_final = na.omit(biopsy[,-c(1)]) # ID & NA excluded

ctrl <- trainControl(method="repeatedcv", number=1, repeats=1)
nn_grid <- expand.grid(k=c(1:12))
nn_grid

best_knn <- train(class~., data=biopsy_,
              method="knn",
              trControl=ctrl,
              preProcess = c("center", "scale"),  # standardize
              tuneGrid=nn_grid)
print(best_knn)
</code>```

答:
Try this.</p>

```<code>grid <- expand.grid(k = 1:12)

{
  set.seed(1)

  index <- caret::createDataPartition(biopsy_$class, p = 0.75, list = FALSE) # partiotion test-train

  train <- biopsy_[index, ]
  test  <- biopsy_[-index, ]

  ctrl <- caret::trainControl(method  = "repeatedcv",
                              number  = 10, # see this
                              repeats = 10   # see this
                              )

  model <- caret::train(class~.,
                        data = train,
                        method = "knn",
                        trControl = ctrl,
                        preProcess = c("center","scale"),
                        tuneGrid = grid)
}

# plot(model)
# model$bestTune # best k

# library(dplyr)
# predictions <- model %>% predict(test)
# RMSE(predictions, test$class)
</code>```

Title: Knn using Cross Validation function

Body:
I need to run the R code to find the number of folder = 1 for k=(c(1:12)) but the following warnings were displayed:

> warnings()
Mensagens de aviso:
1: model fit failed for Fold1.Rep1: k= 1 Error in x[1, 1] : subscript out of bounds

2: model fit failed for Fold1.Rep1: k= 2 Error in x[1, 1] : subscript out of bounds

3: model fit failed for Fold1.Rep1: k= 3 Error in x[1, 1] : subscript out of bounds

. . .

12: model fit failed for Fold1.Rep1: k=12 Error in x[1, 1] : subscript out of bounds

13: In nominalTrainWorkflow(x = x, y = y, wts = weights, info = trainInfo,  ... :
  There were missing values in resampled performance measures.

This is a R code using caret package.

biopsy_final = na.omit(biopsy[,-c(1)]) # ID & NA excluded

ctrl <- trainControl(method="repeatedcv", number=1, repeats=1)
nn_grid <- expand.grid(k=c(1:12))
nn_grid

best_knn <- train(class~., data=biopsy_,
              method="knn",
              trControl=ctrl,
              preProcess = c("center", "scale"),  # standardize
              tuneGrid=nn_grid)
print(best_knn)

Body:
Try this.

grid <- expand.grid(k = 1:12)

{
  set.seed(1)

  index <- caret::createDataPartition(biopsy_$class, p = 0.75, list = FALSE) # partiotion test-train

  train <- biopsy_[index, ]
  test  <- biopsy_[-index, ]

  ctrl <- caret::trainControl(method  = "repeatedcv",
                              number  = 10, # see this
                              repeats = 10   # see this
                              )

  model <- caret::train(class~.,
                        data = train,
                        method = "knn",
                        trControl = ctrl,
                        preProcess = c("center","scale"),
                        tuneGrid = grid)
}

# plot(model)
# model$bestTune # best k

# library(dplyr)
# predictions <- model %>% predict(test)
# RMSE(predictions, test$class)


问:
How do I convert a string to a dictionary which appears to already be a dictionary?
I have a dictionary that appears as:

```<code>my_string = "{'C': [(1, 2, 'string'), (3, 4, 'second string')]}"
</code>```

for some reason, even though it appears to be a dict, when I check type(my_string) it appears to be a string.

When I try converting it to a dictionary by dict(my_string) I am met with the error:

ValueError: dictionary update sequence element #0 has length 1; 2 is
  required

答:
Another option is to use json.loads to parse the string as a json object.

This means that the string must be valid json though, which in your case leads to some rather awkward replace operations of the characters ', ( and ):

```<code>>>> import json
>>> s = "{'C': [(1, 2, 'string'), (3, 4, 'second string')]}"
>>> s.replace("'", '"').replace('(', '[').replace(')', ']')
>>> s
'{"C": [[1, 2, "string"], [3, 4, "second string"]]}'
>>> d = json.loads(s)
>>> d
{'C': [[1, 2, 'string'], [3, 4, 'second string']]}
</code>```

Body:
I have a dictionary that appears as:

my_string = "{'C': [(1, 2, 'string'), (3, 4, 'second string')]}"

for some reason, even though it appears to be a dict, when I check type(my_string) it appears to be a string.

When I try converting it to a dictionary by dict(my_string) I am met with the error:

ValueError: dictionary update sequence element #0 has length 1; 2 is
  required

Body:
Another option is to use json.loads to parse the string as a json object.

This means that the string must be valid json though, which in your case leads to some rather awkward replace operations of the characters ', ( and ):

>>> import json
>>> s = "{'C': [(1, 2, 'string'), (3, 4, 'second string')]}"
>>> s.replace("'", '"').replace('(', '[').replace(')', ']')
>>> s
'{"C": [[1, 2, "string"], [3, 4, "second string"]]}'
>>> d = json.loads(s)
>>> d
{'C': [[1, 2, 'string'], [3, 4, 'second string']]}


问:
Null Pointer Exception When Populating a ListView
I'm creating an application for a cookbook and I'm trying to display recipes from a database into a ListView. When I call setItems() on the ListView I get a Null Pointer Exception. I'm not super familiar with JavaFX so I can't figure out how to prevent it here. I made sure that the ListView has an fx:id , my fxml files specify the controller, and I tried some other things that fixed other people's problems with this. My guess is that the problem has to do with the fact that I'm loading the FXML from MainMenu_Controller and then trying to add the items to the ListView from the ViewRecipes_Controller but I have not been able to figure it out.

Main Class:

```<code>public class Main extends Application {

    @Override
    public void start(Stage primaryStage) {
        try {
            Parent root = FXMLLoader.load(getClass().getResource("/Cookbook_MainMenu.fxml"));
            Scene scene = new Scene(root);
            scene.getStylesheets().add(getClass().getResource("styles.css").toExternalForm());
            primaryStage.setTitle("Cookbook");
            primaryStage.setScene(scene);
            primaryStage.show();
            DatabaseConnection db = new DatabaseConnection();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}
</code>```

MainMenu_Controller:

```<code>public class MainMenu_Controller {

    //controls when user clicks view recipes
    @FXML
    protected void viewRecipesBtnClick(ActionEvent event){
        try {
            Parent root = FXMLLoader.load(getClass().getResource("/Cookbook_ViewRecipes.fxml"));
            Scene scene = new Scene(root);
            scene.getStylesheets().add(getClass().getResource("styles.css").toExternalForm());
            Stage primaryStage = new Stage();
            primaryStage.setTitle("View Recipes");
            primaryStage.setScene(scene);
            primaryStage.show();
            //close previous window
            ((Node)(event.getSource())).getScene().getWindow().hide();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    //controls when user clicks add recipe
    @FXML
    protected void addRecipeBtnClick(ActionEvent event){
        try {
            Parent root = FXMLLoader.load(getClass().getResource("/Cookbook_MainMenu.fxml"));
            Scene scene = new Scene(root);
            scene.getStylesheets().add(getClass().getResource("styles.css").toExternalForm());
            Stage primaryStage = new Stage();
            primaryStage.setTitle("Add Recipe");
            primaryStage.setScene(scene);
            primaryStage.show();
            //close previous window
            ((Node)(event.getSource())).getScene().getWindow().hide();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}
</code>```

ViewRecipes_Controller:

```<code>public class ViewRecipes_Controller {

    @FXML
    private ListView recipeListView;

    public ViewRecipes_Controller() {
        DatabaseConnection db = new DatabaseConnection();
        ObservableList<String> names = FXCollections.observableArrayList();
        names = db.getRecipeName();
        recipeListView.setItems(names);     //error occurs here
    }

    //controls when user clicks back to menu
    @FXML
    protected void backToMenuBtnClick(ActionEvent event){
        try {
            Parent root = FXMLLoader.load(getClass().getResource("/Cookbook_MainMenu.fxml"));
            Scene scene = new Scene(root);
            scene.getStylesheets().add(getClass().getResource("styles.css").toExternalForm());
            Stage primaryStage = new Stage();
            primaryStage.setTitle("Cookbook");
            primaryStage.setScene(scene);
            primaryStage.show();
            //close previous window
            ((Node)(event.getSource())).getScene().getWindow().hide();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}
</code>```

Cookbook_MainMenu.fxml:

```<code><AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="261.0" prefWidth="600.0" stylesheets="@application/styles.css" xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.MainMenu_Controller">
   <children>
      <Label layoutX="173.0" layoutY="20.0" styleClass="titleLbl" text="Cookbook">
         <font>
            <Font name="Ink Free" size="68.0" />
         </font>
      </Label>
      <Button fx:id="viewRecipeBtn" layoutX="136.0" layoutY="188.0" mnemonicParsing="false" onAction="#viewRecipesBtnClick" styleClass="btnDefault" text="View Recipes">
         <font>
            <Font name="ELEGANCE" size="12.0" />
         </font>
      </Button>
      <Button fx:id="addRecipeBtn" layoutX="380.0" layoutY="188.0" mnemonicParsing="false" onAction="#addRecipeBtnClick" styleClass="btnDefault" text="Add Recipe" />
   </children>
</AnchorPane>
</code>```

Cookbook_ViewRecipes.fxml:

```<code><AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="416.0" prefWidth="301.0" xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.ViewRecipes_Controller">
   <children>
      <Label layoutX="54.0" styleClass="titleLbl" text="Recipes">
         <font>
            <Font name="Ink Free" size="62.0" />
         </font>
      </Label>
      <Button fx:id="backToMenuBtn" layoutX="51.0" layoutY="355.0" mnemonicParsing="false" onAction="#backToMenuBtnClick" styleClass="btnDefault" text="Back to Menu" />
      <ListView fx:id="recipeListView" layoutX="51.0" layoutY="116.0" prefHeight="200.0" prefWidth="200.0" styleClass="recipeList" />
      <Button fx:id="getDetailsBtn" layoutX="177.0" layoutY="355.0" mnemonicParsing="false" styleClass="btnDefault" text="Get Details" />
   </children>
</AnchorPane>
</code>```

答:
Best solution I can give you without having more insight into what's going on here is to make sure recipeListView is not null before proceeding to access the object:

```<code>public ViewRecipes_Controller() {
    DatabaseConnection db = new DatabaseConnection();
    ObservableList<String> names = FXCollections.observableArrayList();
    names = db.getRecipeName();
    if (recipeListView != null) {
        recipeListView.setItems(names);     //error occurs here
    }
    else {
        System.out.println("Unable to set items, recipeListView is null")
    }
}
</code>```

If you would like to find out why the object is null then you should run a debugging session with breakpoints and analyze your code flow.

Body:
I'm creating an application for a cookbook and I'm trying to display recipes from a database into a ListView. When I call setItems() on the ListView I get a Null Pointer Exception. I'm not super familiar with JavaFX so I can't figure out how to prevent it here. I made sure that the ListView has an fx:id , my fxml files specify the controller, and I tried some other things that fixed other people's problems with this. My guess is that the problem has to do with the fact that I'm loading the FXML from MainMenu_Controller and then trying to add the items to the ListView from the ViewRecipes_Controller but I have not been able to figure it out.

Main Class:

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) {
        try {
            Parent root = FXMLLoader.load(getClass().getResource("/Cookbook_MainMenu.fxml"));
            Scene scene = new Scene(root);
            scene.getStylesheets().add(getClass().getResource("styles.css").toExternalForm());
            primaryStage.setTitle("Cookbook");
            primaryStage.setScene(scene);
            primaryStage.show();
            DatabaseConnection db = new DatabaseConnection();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}

MainMenu_Controller:

public class MainMenu_Controller {

    //controls when user clicks view recipes
    @FXML
    protected void viewRecipesBtnClick(ActionEvent event){
        try {
            Parent root = FXMLLoader.load(getClass().getResource("/Cookbook_ViewRecipes.fxml"));
            Scene scene = new Scene(root);
            scene.getStylesheets().add(getClass().getResource("styles.css").toExternalForm());
            Stage primaryStage = new Stage();
            primaryStage.setTitle("View Recipes");
            primaryStage.setScene(scene);
            primaryStage.show();
            //close previous window
            ((Node)(event.getSource())).getScene().getWindow().hide();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    //controls when user clicks add recipe
    @FXML
    protected void addRecipeBtnClick(ActionEvent event){
        try {
            Parent root = FXMLLoader.load(getClass().getResource("/Cookbook_MainMenu.fxml"));
            Scene scene = new Scene(root);
            scene.getStylesheets().add(getClass().getResource("styles.css").toExternalForm());
            Stage primaryStage = new Stage();
            primaryStage.setTitle("Add Recipe");
            primaryStage.setScene(scene);
            primaryStage.show();
            //close previous window
            ((Node)(event.getSource())).getScene().getWindow().hide();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}

ViewRecipes_Controller:

public class ViewRecipes_Controller {

    @FXML
    private ListView recipeListView;

    public ViewRecipes_Controller() {
        DatabaseConnection db = new DatabaseConnection();
        ObservableList<String> names = FXCollections.observableArrayList();
        names = db.getRecipeName();
        recipeListView.setItems(names);     //error occurs here
    }

    //controls when user clicks back to menu
    @FXML
    protected void backToMenuBtnClick(ActionEvent event){
        try {
            Parent root = FXMLLoader.load(getClass().getResource("/Cookbook_MainMenu.fxml"));
            Scene scene = new Scene(root);
            scene.getStylesheets().add(getClass().getResource("styles.css").toExternalForm());
            Stage primaryStage = new Stage();
            primaryStage.setTitle("Cookbook");
            primaryStage.setScene(scene);
            primaryStage.show();
            //close previous window
            ((Node)(event.getSource())).getScene().getWindow().hide();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}

Cookbook_MainMenu.fxml:

<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="261.0" prefWidth="600.0" stylesheets="@application/styles.css" xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.MainMenu_Controller">
   <children>

      <Button fx:id="viewRecipeBtn" layoutX="136.0" layoutY="188.0" mnemonicParsing="false" onAction="#viewRecipesBtnClick" styleClass="btnDefault" text="View Recipes">

      </Button>
      <Button fx:id="addRecipeBtn" layoutX="380.0" layoutY="188.0" mnemonicParsing="false" onAction="#addRecipeBtnClick" styleClass="btnDefault" text="Add Recipe" />
   </children>
</AnchorPane>

Cookbook_ViewRecipes.fxml:

<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="416.0" prefWidth="301.0" xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.ViewRecipes_Controller">
   <children>

      <Button fx:id="backToMenuBtn" layoutX="51.0" layoutY="355.0" mnemonicParsing="false" onAction="#backToMenuBtnClick" styleClass="btnDefault" text="Back to Menu" />
      <ListView fx:id="recipeListView" layoutX="51.0" layoutY="116.0" prefHeight="200.0" prefWidth="200.0" styleClass="recipeList" />
      <Button fx:id="getDetailsBtn" layoutX="177.0" layoutY="355.0" mnemonicParsing="false" styleClass="btnDefault" text="Get Details" />
   </children>
</AnchorPane>

Body:
Best solution I can give you without having more insight into what's going on here is to make sure recipeListView is not null before proceeding to access the object:

public ViewRecipes_Controller() {
    DatabaseConnection db = new DatabaseConnection();
    ObservableList<String> names = FXCollections.observableArrayList();
    names = db.getRecipeName();
    if (recipeListView != null) {
        recipeListView.setItems(names);     //error occurs here
    }
    else {
        System.out.println("Unable to set items, recipeListView is null")
    }
}

If you would like to find out why the object is null then you should run a debugging session with breakpoints and analyze your code flow.


问:
reverse order in R leaflet continuous legend
I am trying to reverse the value display of my leaflet legend in R. This post covers categorical data, but I am working with continuous data. Here's a toy example:

```<code>map <- leaflet() %>% addProviderTiles('Esri.WorldTopoMap')
x <- 1:100
pal <- colorNumeric(c("#d7191c","#fdae61","#ffffbf","#abd9e9", "#2c7bb6"), x)
map %>% addLegend('topright', pal=pal, values=x)
</code>```

I'd like the legend to read 100 at the top and 1 on the bottom with the colors reversed. I can certainly reverse the colors in colorNumeric(), but reversing the order of the labels is harder. I have tried reversing the order of the values in x, and I even fiddled with the labelFormat() parameter for addLegend() to reference a lookup table of reversed values... nothing seems to work. Is there an easy way to do this?

答:
Unfortunately the accepted answer to this will get the numbers out of alignment (in fact exactly reversed) from the colours they represent.

Here's the original proposed solution, which I say is incorrect:

```<code>map <- leaflet() %>% addProviderTiles('Esri.WorldTopoMap')
x <- 1:100
pal <- colorNumeric(c("#d7191c","#fdae61","#ffffbf","#abd9e9", "#2c7bb6"), x)
map %>% addLegend('topright', pal=pal, values=x)

# This solution shows 100 as red
map %>% addLegend('topright',
                  pal = pal,
                  values = x,
                  labFormat = labelFormat(transform = function(x) sort(x, decreasing = TRUE)))
</code>```

But if you've been using the pal() function to draw anything on your map, you now have it exactly wrong.

```<code># But 100 is blue, not red
plot(1, 1, pch = 19, cex = 3, col = pal(100))
</code>```

I think the solution is to define to functions that allocate colours to numbers, one in reverse for the legend, and one for actually drawing things:

```<code>pal_rev <- colorNumeric(c("#d7191c","#fdae61","#ffffbf","#abd9e9", "#2c7bb6"), x, reverse = TRUE)

map %>% addLegend('topright',
                  pal = pal_rev,
                  values = x,
                  labFormat = labelFormat(transform = function(x) sort(x, decreasing = TRUE)))
</code>```

This gives us a legend that matches anything we will have drawn ie 100 is now correctly shown to be blue:

Body:
I am trying to reverse the value display of my leaflet legend in R. This post covers categorical data, but I am working with continuous data. Here's a toy example:

map <- leaflet() %>% addProviderTiles('Esri.WorldTopoMap')
x <- 1:100
pal <- colorNumeric(c("#d7191c","#fdae61","#ffffbf","#abd9e9", "#2c7bb6"), x)
map %>% addLegend('topright', pal=pal, values=x)

I'd like the legend to read 100 at the top and 1 on the bottom with the colors reversed. I can certainly reverse the colors in colorNumeric(), but reversing the order of the labels is harder. I have tried reversing the order of the values in x, and I even fiddled with the labelFormat() parameter for addLegend() to reference a lookup table of reversed values... nothing seems to work. Is there an easy way to do this?

Body:
Unfortunately the accepted answer to this will get the numbers out of alignment (in fact exactly reversed) from the colours they represent.

Here's the original proposed solution, which I say is incorrect:

map <- leaflet() %>% addProviderTiles('Esri.WorldTopoMap')
x <- 1:100
pal <- colorNumeric(c("#d7191c","#fdae61","#ffffbf","#abd9e9", "#2c7bb6"), x)
map %>% addLegend('topright', pal=pal, values=x)

# This solution shows 100 as red
map %>% addLegend('topright',
                  pal = pal,
                  values = x,
                  labFormat = labelFormat(transform = function(x) sort(x, decreasing = TRUE)))

But if you've been using the pal() function to draw anything on your map, you now have it exactly wrong.

# But 100 is blue, not red
plot(1, 1, pch = 19, cex = 3, col = pal(100))

I think the solution is to define to functions that allocate colours to numbers, one in reverse for the legend, and one for actually drawing things:

pal_rev <- colorNumeric(c("#d7191c","#fdae61","#ffffbf","#abd9e9", "#2c7bb6"), x, reverse = TRUE)

map %>% addLegend('topright',
                  pal = pal_rev,
                  values = x,
                  labFormat = labelFormat(transform = function(x) sort(x, decreasing = TRUE)))

This gives us a legend that matches anything we will have drawn ie 100 is now correctly shown to be blue: