来源: stackexchange

问:
Not able to change default starting page in netbeans
I create a web application in Netbeans, named test9. I have create various jsp files and servlets,etc in it.Now i want to change the starting page index.html to index.jsp so I created a new file index.jsp and deleted index.html but after running it, It is still trying to open index.html and displaying 404 error resource not found i even made changes in my xml file but still it is doing it.
Do i have to make some other changes ?

xml file

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">

<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<filter>
    <filter-name>RequestLoggingFilter</filter-name>
    <filter-class>bean.RequestLoggingFilter</filter-class>
</filter>
<filter>
    <filter-name>AuthenticationFilter</filter-name>
    <filter-class>bean.AuthenticationFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>AuthenticationFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
    <filter-name>RequestLoggingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>bean.LoginServlet</servlet-class>
</servlet>
<servlet>
    <servlet-name>LogoutServlet</servlet-name>
    <servlet-class>bean.LogoutServlet</servlet-class>
</servlet>
<servlet>
    <servlet-name>DepartmentServlet</servlet-name>
    <servlet-class>bean.DepartmentServlet</servlet-class>
</servlet>
<servlet>
    <servlet-name>C_userServlet</servlet-name>
    <servlet-class>bean.C_userServlet</servlet-class>
</servlet>
<servlet>
    <servlet-name>statusServlet</servlet-name>
    <servlet-class>bean.statusServlet</servlet-class>
</servlet>
<servlet>
    <servlet-name>FileServlet</servlet-name>
    <servlet-class>bean.FileServlet</servlet-class>
</servlet>
<servlet>
    <servlet-name>SearchServlet</servlet-name>
    <servlet-class>bean.SearchServlet</servlet-class>
</servlet>
<servlet>
    <servlet-name>NoCacheFilter</servlet-name>
    <servlet-class>bean.NoCacheFilter</servlet-class>
</servlet>
<servlet>
    <servlet-name>forgotServlet</servlet-name>
    <servlet-class>bean.forgotServlet</servlet-class>
</servlet>
<servlet>
    <servlet-name>passServlet</servlet-name>
    <servlet-class>bean.passServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>LogoutServlet</servlet-name>
    <url-pattern>/LogoutServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>DepartmentServlet</servlet-name>
    <url-pattern>/DepartmentServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>C_userServlet</servlet-name>
    <url-pattern>/C_userServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>statusServlet</servlet-name>
    <url-pattern>/statusServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>FileServlet</servlet-name>
    <url-pattern>/FileServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>SearchServlet</servlet-name>
    <url-pattern>/SearchServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>NoCacheFilter</servlet-name>
    <url-pattern>/NoCacheFilter</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>forgotServlet</servlet-name>
    <url-pattern>/forgotServlet</url-pattern>
</servlet-mapping>
<session-config>
    <session-timeout>
        30
    </session-timeout>
</session-config>
</web-app>
</code>```

答:
I know that this is an old post but since i had the same issue and solved it i am posting my answer to help some others who might stuck in a situation like this.

What worked for me was to take the new jsp file out of the WEB-INF folder.

ContentLicense: CC BY-SA 3.0

Body:
I create a web application in Netbeans, named test9. I have create various jsp files and servlets,etc in it.Now i want to change the starting page index.html to index.jsp so I created a new file index.jsp and deleted index.html but after running it, It is still trying to open index.html and displaying 404 error resource not found i even made changes in my xml file but still it is doing it.
Do i have to make some other changes ?

xml file

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">

<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<filter>
    <filter-name>RequestLoggingFilter</filter-name>
    <filter-class>bean.RequestLoggingFilter</filter-class>
</filter>
<filter>
    <filter-name>AuthenticationFilter</filter-name>
    <filter-class>bean.AuthenticationFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>AuthenticationFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
    <filter-name>RequestLoggingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>bean.LoginServlet</servlet-class>
</servlet>
<servlet>
    <servlet-name>LogoutServlet</servlet-name>
    <servlet-class>bean.LogoutServlet</servlet-class>
</servlet>
<servlet>
    <servlet-name>DepartmentServlet</servlet-name>
    <servlet-class>bean.DepartmentServlet</servlet-class>
</servlet>
<servlet>
    <servlet-name>C_userServlet</servlet-name>
    <servlet-class>bean.C_userServlet</servlet-class>
</servlet>
<servlet>
    <servlet-name>statusServlet</servlet-name>
    <servlet-class>bean.statusServlet</servlet-class>
</servlet>
<servlet>
    <servlet-name>FileServlet</servlet-name>
    <servlet-class>bean.FileServlet</servlet-class>
</servlet>
<servlet>
    <servlet-name>SearchServlet</servlet-name>
    <servlet-class>bean.SearchServlet</servlet-class>
</servlet>
<servlet>
    <servlet-name>NoCacheFilter</servlet-name>
    <servlet-class>bean.NoCacheFilter</servlet-class>
</servlet>
<servlet>
    <servlet-name>forgotServlet</servlet-name>
    <servlet-class>bean.forgotServlet</servlet-class>
</servlet>
<servlet>
    <servlet-name>passServlet</servlet-name>
    <servlet-class>bean.passServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>LogoutServlet</servlet-name>
    <url-pattern>/LogoutServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>DepartmentServlet</servlet-name>
    <url-pattern>/DepartmentServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>C_userServlet</servlet-name>
    <url-pattern>/C_userServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>statusServlet</servlet-name>
    <url-pattern>/statusServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>FileServlet</servlet-name>
    <url-pattern>/FileServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>SearchServlet</servlet-name>
    <url-pattern>/SearchServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>NoCacheFilter</servlet-name>
    <url-pattern>/NoCacheFilter</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>forgotServlet</servlet-name>
    <url-pattern>/forgotServlet</url-pattern>
</servlet-mapping>
<session-config>
    <session-timeout>
        30
    </session-timeout>
</session-config>
</web-app>

ContentLicense: CC BY-SA 4.0


问:
Django admin tools and user control panel (no admin control panel)
i want use django-admin-tools in a user control panel, any idea how implement?

Thanks you guys

答:
You mean the django admin extensions?

To setup it properly you can look at the documentation

or you need something more specific?


问:
Partition & consecutive in SQL
fellow stackers

I have a data set like so:

```<code>+---------+------+--------+
| user_id | date | metric |
+---------+------+--------+
|       1 |    1 |      1 |
|       1 |    2 |      1 |
|       1 |    3 |      1 |
|       2 |    1 |      1 |
|       2 |    2 |      1 |
|       2 |    3 |      0 |
|       2 |    4 |      1 |
+---------+------+--------+
</code>```

I am looking to flag those customers who has 3 consecutive "1"s in the metric column. I have a solution as below.

```<code>select      distinct user_id
from        (
             select      user_id
                         ,metric +
                          ifnull( lag(metric, 1) OVER (PARTITION BY user_id ORDER BY date), 0 ) +
                          ifnull( lag(metric, 2) OVER (PARTITION BY user_id ORDER BY date), 0 )
                          as consecutive_3
             from        df
             ) b
where       consecutive_3 = 3
</code>```

While it works it is not scalable. As one can imagine what the above query would look like if I were looking for a consecutive 50.
May I ask if there is a scalable solution? Any cloud SQL will do. Thank you.

答:
If you only want such users, you can use a sum().  Assuming that metric is only 0 or 1:

```<code>select user_id,
       (case when max(metric_3) = 3 then 1 else 0 end) as flag_3
from (select df.*,
             sum(metric) over (partition by user_id
                               order by date
                               rows between 2 preceding and current row
                              ) as metric_3
      from df
     ) df
group by user_id;
</code>```

By using a windowing clause, you can easily expand to as many adjacent 1s as you like.

Title: Partition & consecutive in SQL

Body:
fellow stackers

I have a data set like so:

+---------+------+--------+
| user_id | date | metric |
+---------+------+--------+
|       1 |    1 |      1 |
|       1 |    2 |      1 |
|       1 |    3 |      1 |
|       2 |    1 |      1 |
|       2 |    2 |      1 |
|       2 |    3 |      0 |
|       2 |    4 |      1 |
+---------+------+--------+

I am looking to flag those customers who has 3 consecutive "1"s in the metric column. I have a solution as below.

select      distinct user_id
from        (
             select      user_id
                         ,metric +
                          ifnull( lag(metric, 1) OVER (PARTITION BY user_id ORDER BY date), 0 ) +
                          ifnull( lag(metric, 2) OVER (PARTITION BY user_id ORDER BY date), 0 )
                          as consecutive_3
             from        df
             ) b
where       consecutive_3 = 3

While it works it is not scalable. As one can imagine what the above query would look like if I were looking for a consecutive 50.
May I ask if there is a scalable solution? Any cloud SQL will do. Thank you.

Body:
If you only want such users, you can use a sum().  Assuming that metric is only 0 or 1:

select user_id,
       (case when max(metric_3) = 3 then 1 else 0 end) as flag_3
from (select df.*,
             sum(metric) over (partition by user_id
                               order by date
                               rows between 2 preceding and current row
                              ) as metric_3
      from df
     ) df
group by user_id;

By using a windowing clause, you can easily expand to as many adjacent 1s as you like.


问:
how to add check symbol in excel cell SXSSFSheet java
I need to put a check symbol in this cell if the condition met. Here's my sample code:

```<code>private SXSSFWorkbook RepWkBook = null;
private SXSSFSheet RepSheet = null;
private int RepRowNum = 0;
private ResultSet RepResult = null;
private Row RepRow = null;

    RepSheet = RepWkBook.createSheet(reportType);
    RepRowNum = 0;
    Row row = RepSheet.createRow(RepRowNum++);
    CellStyle cellStyle = RepWkBook.createCellStyle();
    Font font = RepWkBook.createFont();
    font.setBold(true);
    cellStyle.setFont(font);cell = RepRow.createCell(col++);

        boolean isMOBhigherThanArea = RepResult.getString("IS_MOB_HIGHER_THAN_AREA").equalsIgnoreCase("1");

        char st = '\u2713';

        if(isMOBhigherThanArea && (!areaStr.equalsIgnoreCase("No Data") || !mobStr.equalsIgnoreCase("No Data"))) {
            cell.setCellValue(st);}
</code>```

I already used

UTF-16 - feff2713

UTF-16BE - 2713

UTF-16LE - 1327

UTF-8 - e29c93

click here for sample output
SAMPLE EXPECTED OUTPUT

Area | MOB Target | Area Result | MOB > Area

City |     85%    |       80%   |     ✔

答:
There is no method setCellValue which takes a char. Try using a String there.

The following works for me:

```<code>import java.io.FileOutputStream;
import org.apache.poi.xssf.streaming.*;

class CreateSXSSFUnicode {

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

  char st = '\u2713';
  String[] headers = new String[] {"Area", "MOB Target", "Area Result", "MOB > Area"};

  try (SXSSFWorkbook workbook = new SXSSFWorkbook();
       FileOutputStream fileout = new FileOutputStream("Excel.xlsx") ) {

   SXSSFSheet sheet = workbook.createSheet();
   SXSSFRow row;

   int rowNum = 0;
   row = sheet.createRow(rowNum++);
   for (int c = 0; c < headers.length; c++) {
    row.createCell(c).setCellValue(headers[c]);
   }
   row = sheet.createRow(rowNum++);
   int c = 0;
   row.createCell(c++).setCellValue("City");
   row.createCell(c++).setCellValue("85%");
   row.createCell(c++).setCellValue("80%");
   //row.createCell(c++).setCellValue(st); // does not work as st is a char
   row.createCell(c++).setCellValue(String.valueOf(st)); // this works

   workbook.write(fileout);
   workbook.dispose();
  }
 }
}
</code>```

Result:

Body:
I need to put a check symbol in this cell if the condition met. Here's my sample code:

private SXSSFWorkbook RepWkBook = null;
private SXSSFSheet RepSheet = null;
private int RepRowNum = 0;
private ResultSet RepResult = null;
private Row RepRow = null;

    RepSheet = RepWkBook.createSheet(reportType);
    RepRowNum = 0;
    Row row = RepSheet.createRow(RepRowNum++);
    CellStyle cellStyle = RepWkBook.createCellStyle();
    Font font = RepWkBook.createFont();
    font.setBold(true);
    cellStyle.setFont(font);cell = RepRow.createCell(col++);

        boolean isMOBhigherThanArea = RepResult.getString("IS_MOB_HIGHER_THAN_AREA").equalsIgnoreCase("1");

        char st = '\u2713';

        if(isMOBhigherThanArea && (!areaStr.equalsIgnoreCase("No Data") || !mobStr.equalsIgnoreCase("No Data"))) {
            cell.setCellValue(st);}

I already used

UTF-16 - feff2713

UTF-16BE - 2713

UTF-16LE - 1327

UTF-8 - e29c93

click here for sample output
SAMPLE EXPECTED OUTPUT

Area | MOB Target | Area Result | MOB > Area

City |     85%    |       80%   |     ✔

Body:
There is no method setCellValue which takes a char. Try using a String there.

The following works for me:

import java.io.FileOutputStream;
import org.apache.poi.xssf.streaming.*;

class CreateSXSSFUnicode {

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

  char st = '\u2713';
  String[] headers = new String[] {"Area", "MOB Target", "Area Result", "MOB > Area"};

  try (SXSSFWorkbook workbook = new SXSSFWorkbook();
       FileOutputStream fileout = new FileOutputStream("Excel.xlsx") ) {

   SXSSFSheet sheet = workbook.createSheet();
   SXSSFRow row;

   int rowNum = 0;
   row = sheet.createRow(rowNum++);
   for (int c = 0; c < headers.length; c++) {
    row.createCell(c).setCellValue(headers[c]);
   }
   row = sheet.createRow(rowNum++);
   int c = 0;
   row.createCell(c++).setCellValue("City");
   row.createCell(c++).setCellValue("85%");
   row.createCell(c++).setCellValue("80%");
   //row.createCell(c++).setCellValue(st); // does not work as st is a char
   row.createCell(c++).setCellValue(String.valueOf(st)); // this works

   workbook.write(fileout);
   workbook.dispose();
  }
 }
}

Result:


问:
Split terminal output while keeping spaces
I'm trying to split the output of a program on a fixed position. I found the recommendation of awk, but I need to keep the empty spaces in the last part of the output. This is what I need to do:

The output I'm trying to split looks like this:

```<code>  trace-cmd-16029 [000]  5635.254957: function:             switch_mm_irqs_off
  trace-cmd-16029 [000]  5635.254961: function:                load_new_mm_cr3
  trinity-c0-16027 [000]  5635.254961: function:             finish_task_switch
  trinity-c0-16027 [000]  5635.254963: function:             smp_reschedule_interrupt
  trinity-c0-16027 [000]  5635.254965: function:             scheduler_ipi
  trinity-c0-16027 [000]  5635.254965: function:                irq_enter
  trinity-c0-16027 [000]  5635.254965: function:                   rcu_irq_enter
  trinity-c0-16027 [000]  5635.254965: function:                   rcu_nmi_enter
  trinity-c0-16027 [000]  5635.254965: function:                sched_ttwu_pending
</code>```

I need it to be formatted like this:

```<code>load_new_mm_cr3
finish_task_switch
smp_reschedule_interrupt
scheduler_ipi
   irq_enter
      rcu_irq_enter
      rcu_nmi_enter
   sched_ttwu_pending
</code>```

Basically the preamble always ends with "function:", followed by a lot of empty spaces. Some empty spaces are not from formatting but show called subfunctions (e.g. the empty space infront of "load_nw_mm_cr3" is there because its a subfunction of "switch_mm_irqs_off"). AWK will remove all empty spaces even the ones I still need.

Anybody with some tips how I can format this output in the terminal?

答:
Once you count the number of spaces between the function: and the top-level names, it's easy to do with sed:

```<code>$ sed 's/^.* function: \{13\}//' input.txt
switch_mm_irqs_off
   load_new_mm_cr3
finish_task_switch
smp_reschedule_interrupt
scheduler_ipi
   irq_enter
      rcu_irq_enter
      rcu_nmi_enter
   sched_ttwu_pending
</code>```

This just uses s// to remove everything extraneous to what your results should be. \{13\} in the regular expression matches 13 spaces (There's a leading space there that inline code markup eats; but it's obvious in the code block).

Body:
I'm trying to split the output of a program on a fixed position. I found the recommendation of awk, but I need to keep the empty spaces in the last part of the output. This is what I need to do:

The output I'm trying to split looks like this:

  trace-cmd-16029 [000]  5635.254957: function:             switch_mm_irqs_off
  trace-cmd-16029 [000]  5635.254961: function:                load_new_mm_cr3
  trinity-c0-16027 [000]  5635.254961: function:             finish_task_switch
  trinity-c0-16027 [000]  5635.254963: function:             smp_reschedule_interrupt
  trinity-c0-16027 [000]  5635.254965: function:             scheduler_ipi
  trinity-c0-16027 [000]  5635.254965: function:                irq_enter
  trinity-c0-16027 [000]  5635.254965: function:                   rcu_irq_enter
  trinity-c0-16027 [000]  5635.254965: function:                   rcu_nmi_enter
  trinity-c0-16027 [000]  5635.254965: function:                sched_ttwu_pending

I need it to be formatted like this:

load_new_mm_cr3
finish_task_switch
smp_reschedule_interrupt
scheduler_ipi
   irq_enter
      rcu_irq_enter
      rcu_nmi_enter
   sched_ttwu_pending

Basically the preamble always ends with "function:", followed by a lot of empty spaces. Some empty spaces are not from formatting but show called subfunctions (e.g. the empty space infront of "load_nw_mm_cr3" is there because its a subfunction of "switch_mm_irqs_off"). AWK will remove all empty spaces even the ones I still need.

Anybody with some tips how I can format this output in the terminal?

Body:
Once you count the number of spaces between the function: and the top-level names, it's easy to do with sed:

$ sed 's/^.* function: \{13\}//' input.txt
switch_mm_irqs_off
   load_new_mm_cr3
finish_task_switch
smp_reschedule_interrupt
scheduler_ipi
   irq_enter
      rcu_irq_enter
      rcu_nmi_enter
   sched_ttwu_pending

This just uses s// to remove everything extraneous to what your results should be. \{13\} in the regular expression matches 13 spaces (There's a leading space there that inline code markup eats; but it's obvious in the code block).


问:
Eastwood linter not disabling deprecation warnings
Using Eastwood, I'm trying to disable deprecation warnings, for a specific package, when linting a given Clojure namespace. In this case, eastwood is failing  when making a Google API call which is deprecated.

As per the documentation, I tried to disable the linter for that package.

```<code>λ cat src/main/resources/third-party-libs.clj

(disable-warning
  {:linter :deprecations
   :symbol-matches #{"^#'com\.google\.api\.core\.*'"}})
</code>```

But no dice. How can I turn off deprecation for specific classes or packages?

```<code>my/namespace.clj:13:5: deprecations: Static method 'public static void com.google.api.core.ApiFutures.addCallback(com.google.api.core.ApiFuture,com.google.api.core.ApiFutureCallback)' is deprecated.
</code>```

EDIT

A) I'm able to load src/main/resources/my-eastwood-config.clj. But com.google.api.core.ApiFutures.* still isn't ignored.

```<code>(disable-warning
  {:linter :deprecations
   :symbol-matches #{#"com\.google\.api\.core\.ApiFutures.*"}})
</code>```

B) Either of these formats gives me the error below.

i)

```<code>(disable-warning
  {:linter :deprecations
   :symbol-matches #{"^#'com\.google\.api\.core\..*'"}})

(disable-warning
  {:linter :deprecations
   :symbol-matches #{"^#'com\\.google\\.api\\.core\\..*'"}})
</code>```

ii)

```<code>CompilerException java.lang.RuntimeException: Unsupported escape character: \., compiling:(null:4:31)
        clojure.lang.Compiler.load (Compiler.java:7521)
        clojure.lang.Compiler.load (Compiler.java:7461)
        clojure.core/load-reader (core.clj:4053)
        clojure.core/load-reader (core.clj:4048)
        eastwood.util/init-warning-enable-config/fn--40733 (util.clj:916)
        eastwood.util/init-warning-enable-config (util.clj:914)
        eastwood.util/init-warning-enable-config (util.clj:907)
        eastwood.lint/last-options-map-adjustments (lint.clj:467)
        eastwood.lint/last-options-map-adjustments (lint.clj:456)
        eastwood.lint/eastwood (lint.clj:511)
        eastwood.lint/eastwood (lint.clj:501)
        eastwood.lint/eastwood (lint.clj:502)
        eastwood.lint/eastwood (lint.clj:501)
        eastwood.lint/eastwood-from-cmdline (lint.clj:529)
        eastwood.lint/eastwood-from-cmdline (lint.clj:528)
        clojure.lang.Var.invoke (Var.java:381)
        eastwood.versioncheck/run-eastwood (versioncheck.clj:15)
        eastwood.versioncheck/run-eastwood (versioncheck.clj:9)
        user/eval39298 (form-init6182731209880131993.clj:1)
        user/eval39298 (form-init6182731209880131993.clj:1)
        clojure.lang.Compiler.eval (Compiler.java:7062)
        clojure.lang.Compiler.eval (Compiler.java:7052)
        clojure.lang.Compiler.load (Compiler.java:7514)
        clojure.lang.Compiler.loadFile (Compiler.java:7452)
        clojure.main/load-script (main.clj:278)
        clojure.main/init-opt (main.clj:280)
        clojure.main/init-opt (main.clj:280)
        clojure.main/initialize (main.clj:311)
        clojure.main/null-opt (main.clj:345)
        clojure.main/null-opt (main.clj:342)
        clojure.main/main (main.clj:424)
        clojure.main/main (main.clj:387)
        clojure.lang.Var.applyTo (Var.java:702)
clojure.main.main (main.java:37)
</code>```

答:
Eastwood is not picking up your config file.  You can debug this with:

```<code>lein eastwood '{:debug [:config]}'
== Eastwood 0.3.7 Clojure 1.10.1 JVM 1.8.0_242 ==
Loading config file: jar:file:$HOME/.m2/repository/jonase/eastwood/0.3.7/eastwood-0.3.7.jar!/eastwood/config/clojure.clj
Loading config file: jar:file:$HOME/.m2/repository/jonase/eastwood/0.3.7/eastwood-0.3.7.jar!/eastwood/config/clojure-contrib.clj
Loading config file: jar:file:$HOME/.m2/repository/jonase/eastwood/0.3.7/eastwood-0.3.7.jar!/eastwood/config/third-party-libs.clj
...
</code>```

The reason, why a similar named file is not picked up:

You can specify the key :builtin-config-files in the options map to
  override the built-in config files read. It defaults to ["clojure.clj"
  "clojure-contrib.clj" "third-party-libs.clj"]. All such file names are
  only looked for in Eastwood's built-in config files.

Similarly you can specify :config-files in the options map to give
  additional files to read. These are file names that can be anywhere in
  your file system, specified as strings, or if Eastwood is invoked from
  the REPL, anything that can be passed to clojure.java.io/reader.

Source: https://github.com/jonase/eastwood#eastwood-config-files

Not very specific, but that would imply they are looked up as resources
under /eastwood/config/....

If you would put a file under that same location with the same name you may
or may not win against the default configs (e.g. one wins).  So the way out is to
specify the config just yourself.  E.g.

```<code>lein eastwood '{:config-files ["eastwood-config.clj"] :debug [:config]}'
== Eastwood 0.3.7 Clojure 1.10.1 JVM 1.8.0_242 ==
Loading config file: jar://...
...
Loading config file: eastwood-config.clj
...
</code>```

Also watch out with your regexp.  I think you want: "^#'com\.google\.api\.core\..*'" (note the additional . before the *); otherwise the \. repeats.

Body:
Using Eastwood, I'm trying to disable deprecation warnings, for a specific package, when linting a given Clojure namespace. In this case, eastwood is failing  when making a Google API call which is deprecated.

As per the documentation, I tried to disable the linter for that package.

λ cat src/main/resources/third-party-libs.clj

(disable-warning
  {:linter :deprecations
   :symbol-matches #{"^#'com\.google\.api\.core\.*'"}})

But no dice. How can I turn off deprecation for specific classes or packages?

my/namespace.clj:13:5: deprecations: Static method 'public static void com.google.api.core.ApiFutures.addCallback(com.google.api.core.ApiFuture,com.google.api.core.ApiFutureCallback)' is deprecated.

EDIT

A) I'm able to load src/main/resources/my-eastwood-config.clj. But com.google.api.core.ApiFutures.* still isn't ignored.

(disable-warning
  {:linter :deprecations
   :symbol-matches #{#"com\.google\.api\.core\.ApiFutures.*"}})

B) Either of these formats gives me the error below.

i)

(disable-warning
  {:linter :deprecations
   :symbol-matches #{"^#'com\.google\.api\.core\..*'"}})

(disable-warning
  {:linter :deprecations
   :symbol-matches #{"^#'com\\.google\\.api\\.core\\..*'"}})

ii)

CompilerException java.lang.RuntimeException: Unsupported escape character: \., compiling:(null:4:31)
        clojure.lang.Compiler.load (Compiler.java:7521)
        clojure.lang.Compiler.load (Compiler.java:7461)
        clojure.core/load-reader (core.clj:4053)
        clojure.core/load-reader (core.clj:4048)
        eastwood.util/init-warning-enable-config/fn--40733 (util.clj:916)
        eastwood.util/init-warning-enable-config (util.clj:914)
        eastwood.util/init-warning-enable-config (util.clj:907)
        eastwood.lint/last-options-map-adjustments (lint.clj:467)
        eastwood.lint/last-options-map-adjustments (lint.clj:456)
        eastwood.lint/eastwood (lint.clj:511)
        eastwood.lint/eastwood (lint.clj:501)
        eastwood.lint/eastwood (lint.clj:502)
        eastwood.lint/eastwood (lint.clj:501)
        eastwood.lint/eastwood-from-cmdline (lint.clj:529)
        eastwood.lint/eastwood-from-cmdline (lint.clj:528)
        clojure.lang.Var.invoke (Var.java:381)
        eastwood.versioncheck/run-eastwood (versioncheck.clj:15)
        eastwood.versioncheck/run-eastwood (versioncheck.clj:9)
        user/eval39298 (form-init6182731209880131993.clj:1)
        user/eval39298 (form-init6182731209880131993.clj:1)
        clojure.lang.Compiler.eval (Compiler.java:7062)
        clojure.lang.Compiler.eval (Compiler.java:7052)
        clojure.lang.Compiler.load (Compiler.java:7514)
        clojure.lang.Compiler.loadFile (Compiler.java:7452)
        clojure.main/load-script (main.clj:278)
        clojure.main/init-opt (main.clj:280)
        clojure.main/init-opt (main.clj:280)
        clojure.main/initialize (main.clj:311)
        clojure.main/null-opt (main.clj:345)
        clojure.main/null-opt (main.clj:342)
        clojure.main/main (main.clj:424)
        clojure.main/main (main.clj:387)
        clojure.lang.Var.applyTo (Var.java:702)
clojure.main.main (main.java:37)

Body:
Eastwood is not picking up your config file.  You can debug this with:

lein eastwood '{:debug [:config]}'
== Eastwood 0.3.7 Clojure 1.10.1 JVM 1.8.0_242 ==
Loading config file: jar:file:$HOME/.m2/repository/jonase/eastwood/0.3.7/eastwood-0.3.7.jar!/eastwood/config/clojure.clj
Loading config file: jar:file:$HOME/.m2/repository/jonase/eastwood/0.3.7/eastwood-0.3.7.jar!/eastwood/config/clojure-contrib.clj
Loading config file: jar:file:$HOME/.m2/repository/jonase/eastwood/0.3.7/eastwood-0.3.7.jar!/eastwood/config/third-party-libs.clj
...

The reason, why a similar named file is not picked up:

You can specify the key :builtin-config-files in the options map to
  override the built-in config files read. It defaults to ["clojure.clj"
  "clojure-contrib.clj" "third-party-libs.clj"]. All such file names are
  only looked for in Eastwood's built-in config files.

Similarly you can specify :config-files in the options map to give
  additional files to read. These are file names that can be anywhere in
  your file system, specified as strings, or if Eastwood is invoked from
  the REPL, anything that can be passed to clojure.java.io/reader.

Source: https://github.com/jonase/eastwood#eastwood-config-files

Not very specific, but that would imply they are looked up as resources
under /eastwood/config/....

If you would put a file under that same location with the same name you may
or may not win against the default configs (e.g. one wins).  So the way out is to
specify the config just yourself.  E.g.

lein eastwood '{:config-files ["eastwood-config.clj"] :debug [:config]}'
== Eastwood 0.3.7 Clojure 1.10.1 JVM 1.8.0_242 ==
Loading config file: jar://...
...
Loading config file: eastwood-config.clj
...

Also watch out with your regexp.  I think you want: "^#'com\.google\.api\.core\..*'" (note the additional . before the *); otherwise the \. repeats.


问:
Problem while creating Tab in react ERROR (2322)
So... I am following this link for Tab creation

And got the error...

Type '{ children: Element; iconClassName: string; linkClassName: string; }' is not assignable to type 'IntrinsicAttributes & Props'. Property 'children' does not exist on type 'IntrinsicAttributes & Props'.ts(2322)

There are few issues here on stackoverflow kinda like this, but not very useful for me. Related files are...

Tab.tsx

import * as React from 'react';

export interface Props {
  onClick ?: Function;
  tabIndex ?: Number;
  isActive ?: Boolean;
  iconClassName: String;
  linkClassName: String;
 }

 function Tab ({
  onClick = function(){return; },
  tabIndex = 0,
  isActive = false,
  iconClassName = '',
  linkClassName = ''
  }: Props) {
  return (

           {
                  event.preventDefault();
                  onClick(tabIndex);
              }}
          >
              {linkClassName}
              <i className={`tab-icon ${iconClassName}`}/>

  );
}
export default Tab;```
</div>
</div>
  </p>

<p><strong>Tabs.tsx</strong>  </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import * as React from 'react';

export default class Tabs extends React.Component<any, any> {

    constructor(props: any, context: any) {
        super(props, context);
        this.state = {
            activeTabIndex: 0,
        };
        this.handleTabClick = this.handleTabClick.bind(this);
    }

    handleTabClick(tabIndex: number) {
        this.setState({
            activeTabIndex: tabIndex === this.state.activeTabIndex ? this.state.activeTabIndex : tabIndex
        });
    }

    // Encapsulate <Tabs/> component API as props for <Tab/> children
    renderChildrenWithTabsApiAsProps() {
        return React.Children.map(this.props.children, (child: any, index) => {
            return React.cloneElement(child, {
                onClick : this.handleTabClick,
                tabIndex: index,
                isActive: index === this.state.activeTabIndex
            });
        });
    }

    // Render current active tab content
    renderActiveTabContent() {
        if (this.state.activeTabIndex !== undefined) {
            const {children} = this.props;
            const {activeTabIndex} = this.state;
            if (children != null) {
                if (children[activeTabIndex]) {
                    return children[activeTabIndex].props.children;
                }
            } else {
                console.dir('Error! This tab has no children!');
            }
        }
    }

    render() {
        return (
            <div className="tabs">
                <ul className="tabs-nav nav navbar-nav navbar-offices">
                    {this.renderChildrenWithTabsApiAsProps()}
                </ul>
                <div className="tabs-active-content">
                    {this.renderActiveTabContent()}
                </div>
            </div>
        );
    }
}</code>```

...and RenderTabs

class RenderTabs extends React.Component{
  render(){
    return(

        <Tabs>
              <Tab iconClassName="" linkClassName="Tab1">

Elastacloud is great

              </Tab>
              <Tab iconClassName="" linkClassName="Tab2">

Check out Elastacloud the website

              </Tab>
                    <Tab iconClassName="" linkClassName="Tab3">

Seriously, Elastacloud also have some amazing blog posts

You should check those out too

                    </Tab>
                </Tabs>

    )
  }
}```

答:
So I find out solution it is...

Adding children property under interface Props in Tab.tsx

Tab.tsx now has one additional property children:React.ReactNode;

export interface Props {
  onClick ?: Function;
  tabIndex ?: Number;
  isActive ?: Boolean;
  iconClassName: String;
  linkClassName: String;
  children: React.ReactNode;
 }

 function Tab ({
  onClick = function(){return; },
  tabIndex = 0,
  isActive = false,
  iconClassName = '',
  linkClassName = ''
  }: Props) {
  return (

           {
                  event.preventDefault();
                  onClick(tabIndex);
              }}
          >
              {linkClassName}
              <i className={`tab-icon ${iconClassName}`}/>

  );
}
export default Tab;```

Body:
So... I am following this link for Tab creation

And got the error...

Type '{ children: Element; iconClassName: string; linkClassName: string; }' is not assignable to type 'IntrinsicAttributes & Props'. Property 'children' does not exist on type 'IntrinsicAttributes & Props'.ts(2322)

There are few issues here on stackoverflow kinda like this, but not very useful for me. Related files are...

Tab.tsx

import * as React from 'react';

export interface Props {
  onClick ?: Function;
  tabIndex ?: Number;
  isActive ?: Boolean;
  iconClassName: String;
  linkClassName: String;
 }

 function Tab ({
  onClick = function(){return; },
  tabIndex = 0,
  isActive = false,
  iconClassName = '',
  linkClassName = ''
  }: Props) {
  return (

          <a
              className={`tab-link ${linkClassName} ${isActive ? 'active' : ''}`}
              onClick={(event) => {
                  event.preventDefault();
                  onClick(tabIndex);
              }}
          >
              {linkClassName}
              <i className={`tab-icon ${iconClassName}`}/>

  );
}
export default Tab;

Tabs.tsx

import * as React from 'react';

export default class Tabs extends React.Component<any, any> {

    constructor(props: any, context: any) {
        super(props, context);
        this.state = {
            activeTabIndex: 0,
        };
        this.handleTabClick = this.handleTabClick.bind(this);
    }

    handleTabClick(tabIndex: number) {
        this.setState({
            activeTabIndex: tabIndex === this.state.activeTabIndex ? this.state.activeTabIndex : tabIndex
        });
    }

    // Encapsulate <Tabs/> component API as props for <Tab/> children
    renderChildrenWithTabsApiAsProps() {
        return React.Children.map(this.props.children, (child: any, index) => {
            return React.cloneElement(child, {
                onClick : this.handleTabClick,
                tabIndex: index,
                isActive: index === this.state.activeTabIndex
            });
        });
    }

    // Render current active tab content
    renderActiveTabContent() {
        if (this.state.activeTabIndex !== undefined) {
            const {children} = this.props;
            const {activeTabIndex} = this.state;
            if (children != null) {
                if (children[activeTabIndex]) {
                    return children[activeTabIndex].props.children;
                }
            } else {
                console.dir('Error! This tab has no children!');
            }
        }
    }

    render() {
        return (

                    {this.renderChildrenWithTabsApiAsProps()}

                    {this.renderActiveTabContent()}

        );
    }
}

...and RenderTabs

class RenderTabs extends React.Component{
  render(){
    return(

        <Tabs>
              <Tab iconClassName="" linkClassName="Tab1">

Elastacloud is great

              </Tab>
              <Tab iconClassName="" linkClassName="Tab2">

Check out Elastacloud the website

              </Tab>
                    <Tab iconClassName="" linkClassName="Tab3">

Seriously, Elastacloud also have some amazing blog posts

You should check those out too

                    </Tab>
                </Tabs>

    )
  }
}

Body:
So I find out solution it is...

Adding children property under interface Props in Tab.tsx

Tab.tsx now has one additional property children:React.ReactNode;

export interface Props {
  onClick ?: Function;
  tabIndex ?: Number;
  isActive ?: Boolean;
  iconClassName: String;
  linkClassName: String;
  children: React.ReactNode;
 }

 function Tab ({
  onClick = function(){return; },
  tabIndex = 0,
  isActive = false,
  iconClassName = '',
  linkClassName = ''
  }: Props) {
  return (
      <li className="tab">
          <a
              className={`tab-link ${linkClassName} ${isActive ? 'active' : ''}`}
              onClick={(event) => {
                  event.preventDefault();
                  onClick(tabIndex);
              }}
          >
              {linkClassName}
              <i className={`tab-icon ${iconClassName}`}/>
          </a>
      </li>
  );
}
export default Tab;


问:
weak_ptr, shared_ptr in lambda capture list and std::queue<T,Container>::emplace
I have a function which enqueue lambda using std::queue's build-in emplace. I created shared_ptr object (task), which later I would capture in lambda.

```<code>    template<typename Func, typename... Args>
    auto submit(Func&& f, Args&&... args)
    {
        using result_type = std::result_of_t<Func(Args...)>;
        using pckg_task_type = std::packaged_task<result_type()>;

        auto task = std::make_shared< pckg_task_type >(
                    std::bind(std::forward<Func>(f), std::forward<Args>(args)...) );
        ...
    }
</code>```

This is the part which is creating confusion:

Case 1: Which works perfectly

```<code>            tasks.emplace(
                [task](){
                    auto wptr = std::weak_ptr<pckg_task_type>(task);
                    if( auto p = wptr.lock() )
                    {
                        (*p)();
                    }
                    else
                        throw std::runtime_error("weak error");
                }
            );
</code>```

Case 2: Which immediately throws an exception

```<code>                tasks.emplace(
                [wc = std::weak_ptr<pckg_task_type>(task)](){
                    if( auto p = wc.lock() )
                    {
                        (*p)();
                    }
                    else
                        throw std::runtime_error("weak error");
                }
            );
</code>```

With tasks defined as

```<code>std::queue< std::function<void()> > tasks;
</code>```

Calling lambda from case 2 without emplace it into queue doesn't throw exception.

Can anyone explain the difference between cases above? Where is the problem?

答:
The problem is that in the case 2 the task shared pointer is not saved anywhere and the weak pointer wc that is saved in the lambda capture expires as soon as you return from submit. When the lambda is invoked, wc.lock() returns a null pointer.

You probably need to save the task shared_ptr somewhere for the lifetime duration of the enqueued function object. Or you don't need weak_ptr at all and can just save the task shared_ptr in the lambda capture and use it directly in the lambda body.

Body:
I have a function which enqueue lambda using std::queue's build-in emplace. I created shared_ptr object (task), which later I would capture in lambda.

    template<typename Func, typename... Args>
    auto submit(Func&& f, Args&&... args)
    {
        using result_type = std::result_of_t<Func(Args...)>;
        using pckg_task_type = std::packaged_task<result_type()>;

        auto task = std::make_shared< pckg_task_type >(
                    std::bind(std::forward<Func>(f), std::forward<Args>(args)...) );
        ...
    }

This is the part which is creating confusion:

Case 1: Which works perfectly

            tasks.emplace(
                [task](){
                    auto wptr = std::weak_ptr<pckg_task_type>(task);
                    if( auto p = wptr.lock() )
                    {
                        (*p)();
                    }
                    else
                        throw std::runtime_error("weak error");
                }
            );

Case 2: Which immediately throws an exception

                tasks.emplace(
                [wc = std::weak_ptr<pckg_task_type>(task)](){
                    if( auto p = wc.lock() )
                    {
                        (*p)();
                    }
                    else
                        throw std::runtime_error("weak error");
                }
            );

With tasks defined as

std::queue< std::function<void()> > tasks;

Calling lambda from case 2 without emplace it into queue doesn't throw exception.

Can anyone explain the difference between cases above? Where is the problem?


问:
Delete closest tr and it's childs
I have the following code where I can delete the closest tr using delete function, but I want to create another function called delete-contato where it would delete the closest tr and its children that is all "email" and "telefone" associated with that "contato".

```<code>$(wrapper).on("click", ".delete-contato", function(e) {
        e.preventDefault();
        $(this).closest('tr').empty();

        x--;
    })

</code>```

This is the fiddle with the scenario and here's  snippet:

// funcao para adicionar um novo input no Contato
$(document).ready(function() {
  var max_fields = 99;
  var wrapper = $(".container-contato");
  var add_button = $(".add-contato");
  var add_email = $(".add-email");
  var add_telefone = $(".add-telefone");

  var x = 1;

  $(add_email).click(function(e) {
    e.preventDefault();
    if (x < max_fields) {
      x++;
      $(wrapper).append(`

            <input type="text" name="contato_rpps.email['${x}']" placeholder="Outro Email"/>

              Delete

      `)
    }
  });

  $(add_telefone).click(function(e) {
    e.preventDefault();
    if (x < max_fields) {
      x++;
      $(wrapper).append(`

            <input type="text" class="telefone" name="contato_rpps.telefone['${x}']" maxlength="15" onkeyup="phoneMask()" placeholder="Outro Telefone"/>

              Delete

      `)
    }
  });

  $(add_button).click(function(e) {
    e.preventDefault();
    if (x < max_fields) {
      x++;
      $(wrapper).append(`

              <input type="text" class="nome" name="contato_rpps.nome['${x}']"/>

              <input type="text" name="contato_rpps.cargo['${x}']"/>

              <input type="text" name="contato_rpps.email['${x}']"/>

              <input type="text" class="telefone" name="contato_rpps.telefone['${x}']" maxlength="15" onkeyup="phoneMask()"/>

              Delete

          `); //add input box

    } else {
      alert('You Reached the limits')
    }
  });

  $(wrapper).on("click", ".delete", function(e) {
    e.preventDefault();
    $(this).closest('tr').empty();

    x--;
  })

  $(wrapper).on("click", ".delete-contato", function(e) {
    e.preventDefault();

    x--;
  })
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="add-contato">Novo Contato
              <span style="font-size:16px; font-weight:bold;">+ </span>
            </button>
<button type="button" class="add-email">Novo Email
              <span style="font-size:16px; font-weight:bold;">+ </span>
            </button>
<button type="button" class="add-telefone">Novo Telefone
              <span style="font-size:16px; font-weight:bold;">+ </span>
            </button>
<div>
  <table>
    <tbody class="container-contato">
      <tr>
        <td>
          <label><br>Nome</label>
          <input type="text" name="contato_rpps.nome['1']" class="nome">
          <br>
        </td>
        <td>
          <label><br>Cargo</label>
          <input type="text" name="contato_rpps.cargo['1']" class="cargo">
        </td>
        <td>
          <label><br>Email</label>
          <input type="email" name="contato_rpps.email['1']" class="email">
        </td>
        <td>
          <label><br>Telefone</label>
          <input type="text" class="telefone" placeholder="(00) 90000-0000" onkeyup="phoneMask()" name="contato_rpps.telefone['1']" maxlength="15">
        </td>
      </tr>
    </tbody>
  </table>
</div></code>```

I don't think i explained what i want cleary so.. when you press Novo Contato a new set of inputs is created and then you press Novo Email or Novo Telefone. So after press delete on Contanto i want all those new inputs to be deleted. Nome, Cargo, Email, Telefone and others Outros Emails and Outros Telefone generated.

Right now when you delete Contato, Outro Telefone and Outro Email stays.

答:
You can remove the parent "tr" by using .parents('tr')

```<code> $(wrapper).on("click", ".delete", function(e) {
     e.preventDefault();
     $(this).parents('tr').remove();
     x--;
  });

$(wrapper).on("click", ".delete-contato", function(e) {
    e.preventDefault();
    //$(this).closest('tr').remove(); // this will also work
    $(this).parents('tr').remove(); // // this will also work
    x--;
  })
</code>```

Title: Delete closest tr and it's childs

Body:
I have the following code where I can delete the closest tr using delete function, but I want to create another function called delete-contato where it would delete the closest tr and its children that is all "email" and "telefone" associated with that "contato".

$(wrapper).on("click", ".delete-contato", function(e) {
        e.preventDefault();
        $(this).closest('tr').empty();

        x--;
    })

This is the fiddle with the scenario and here's  snippet:

// funcao para adicionar um novo input no Contato
$(document).ready(function() {
  var max_fields = 99;
  var wrapper = $(".container-contato");
  var add_button = $(".add-contato");
  var add_email = $(".add-email");
  var add_telefone = $(".add-telefone");

  var x = 1;

  $(add_email).click(function(e) {
    e.preventDefault();
    if (x < max_fields) {
      x++;
      $(wrapper).append(`

            <input type="text" name="contato_rpps.email['${x}']" placeholder="Outro Email"/>

              Delete

      `)
    }
  });

  $(add_telefone).click(function(e) {
    e.preventDefault();
    if (x < max_fields) {
      x++;
      $(wrapper).append(`

            <input type="text" class="telefone" name="contato_rpps.telefone['${x}']" maxlength="15" onkeyup="phoneMask()" placeholder="Outro Telefone"/>

              Delete

      `)
    }
  });

  $(add_button).click(function(e) {
    e.preventDefault();
    if (x < max_fields) {
      x++;
      $(wrapper).append(`

              <input type="text" class="nome" name="contato_rpps.nome['${x}']"/>

              <input type="text" name="contato_rpps.cargo['${x}']"/>

              <input type="text" name="contato_rpps.email['${x}']"/>

              <input type="text" class="telefone" name="contato_rpps.telefone['${x}']" maxlength="15" onkeyup="phoneMask()"/>

              Delete

          `); //add input box

    } else {
      alert('You Reached the limits')
    }
  });

  $(wrapper).on("click", ".delete", function(e) {
    e.preventDefault();
    $(this).closest('tr').empty();

    x--;
  })

  $(wrapper).on("click", ".delete-contato", function(e) {
    e.preventDefault();

    x--;
  })
});

<button class="add-contato">Novo Contato
              +
            </button>
<button type="button" class="add-email">Novo Email
              +
            </button>
<button type="button" class="add-telefone">Novo Telefone
              +
            </button>

Nome
          <input type="text" name="contato_rpps.nome['1']" class="nome">

Cargo
          <input type="text" name="contato_rpps.cargo['1']" class="cargo">

Email
          <input type="email" name="contato_rpps.email['1']" class="email">

Telefone
          <input type="text" class="telefone" placeholder="(00) 90000-0000" onkeyup="phoneMask()" name="contato_rpps.telefone['1']" maxlength="15">

I don't think i explained what i want cleary so.. when you press Novo Contato a new set of inputs is created and then you press Novo Email or Novo Telefone. So after press delete on Contanto i want all those new inputs to be deleted. Nome, Cargo, Email, Telefone and others Outros Emails and Outros Telefone generated.

Right now when you delete Contato, Outro Telefone and Outro Email stays.

Body:
You can remove the parent "tr" by using .parents('tr')

 $(wrapper).on("click", ".delete", function(e) {
     e.preventDefault();
     $(this).parents('tr').remove();
     x--;
  });

$(wrapper).on("click", ".delete-contato", function(e) {
    e.preventDefault();
    //$(this).closest('tr').remove(); // this will also work
    $(this).parents('tr').remove(); // // this will also work
    x--;
  })


问:
Which are the best alternatives to Lucene?
It may run on Unix and it will be used for email searching (Dovecot, Postfix and maildir).

Lucene is not a problem, I'm just analyzing some alternatives.

答:
Some alternative indexers are mentioned here:

Which search technology to use with ASP.NET?

OwnerDisplayName: Rui Carneiro

LastEditorDisplayName: Rui Carneiro

OwnerDisplayName: Nick Crowther

ContentLicense: CC BY-SA 2.5


问:
Is it possible to get reference to comment element/block by JavaScript?
This sounds a little crazy, but I'm wondering whether possible to get reference to comment element so that I can dynamically replace it other content with JavaScript.

```<code><html>
<head>
</head>
<body>
<div id="header"></div>
<div id="content"></div>
<!-- sidebar place holder: some id-->
</body>
</html>
</code>```

In above page, can I get reference to the comment block and replace it with some content in local storage?

I know that I can have a div place holder. Just wondering whether it applies to comment block.
Thanks.

答:
```<code>var findComments = function(el) {
    var arr = [];
    for(var i = 0; i < el.childNodes.length; i++) {
        var node = el.childNodes[i];
        if(node.nodeType === 8) {
            arr.push(node);
        } else {
            arr.push.apply(arr, findComments(node));
        }
    }
    return arr;
};

var commentNodes = findComments(document);

// whatever you were going to do with the comment...
console.log(commentNodes[0].nodeValue);
</code>```

Body:
This sounds a little crazy, but I'm wondering whether possible to get reference to comment element so that I can dynamically replace it other content with JavaScript.

In above page, can I get reference to the comment block and replace it with some content in local storage?

I know that I can have a div place holder. Just wondering whether it applies to comment block.
Thanks.


问:
Why Are My Sample Weights Breaking My Neural Network?
Please note that I am new to tensorflow, and machine learning in general.

I have a neural network training on a set of imbalanced data, and thus I require different sample weights.

My model is constructed like so:

```<code>def loss(a1, a2):
    customloss = keras.backend.mean(keras.backend.square((a1 - a2)))
    return customloss

def build_model():
    model = keras.Sequential()
    model.add(keras.layers.Dense(101, activation=keras.activations.linear, input_shape=(101,)))
    model.add(keras.layers.Dense(101, activation=keras.activations.linear))
    model.add(keras.layers.Dense(101))

    optimizer = keras.optimizers.RMSprop(0.00001)

    model.compile(loss=loss, optimizer=optimizer, metrics=['mae', 'accuracy'])

    return model
</code>```

and I am training it like so:

```<code>EPOCHS=400
early_stop = keras.callbacks.EarlyStopping(monitor='val_loss', patience=20)
model = build_model()
history = model.fit(x, y, epochs=EPOCHS, validation_split=0.2, verbose=1, sample_weight=weights, callbacks=[early_stop])
</code>```

where weights is an array of shape (9171,), and x and y each have shape (9171,101).

If I remove the sample_weight argument, the network runs. But with it in place, I get the following error message:

```<code>Epoch 1/400
Traceback (most recent call last):
  File "nnotest.py", line 153, in <module>
    history = model.fit(x, y, epochs=EPOCHS, validation_split=0.2, verbose=1, sample_weight=weights, callbacks=[early_stop])
  File "/home/star2/hgc4/.local/lib/python3.6/site-packages/tensorflow/python/keras/engine/training.py", line 780, in fit
    steps_name='steps_per_epoch')
  File "/home/star2/hgc4/.local/lib/python3.6/site-packages/tensorflow/python/keras/engine/training_arrays.py", line 363, in model_iteration
    batch_outs = f(ins_batch)
  File "/home/star2/hgc4/.local/lib/python3.6/site-packages/tensorflow/python/keras/backend.py", line 3292, in __call__
    run_metadata=self.run_metadata)
  File "/home/star2/hgc4/.local/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1458, in __call__
    run_metadata_ptr)
tensorflow.python.framework.errors_impl.InvalidArgumentError: Can not squeeze dim[0], expected a dimension of 1, got 32
     [[{{node loss_1/dense_8_loss/weighted_loss/Squeeze}}]]
</code>```

I have my ideas about why this might not be working. I get that it may be trying to parse my 1D array into the default batch size of 32, but I can't understand why. From reading the documentation it would appear that you can add a 1D array to constitute a 1D mapping from weights to training data, so this should be easy? What am I missing?

答:
Because your loss doesn't have samples. You are getting a global mean.

If mean squared error is what you want, compile with loss='mse'.

If anything else, don't collapse the batch dimension (axis=0):

```<code>def loss(true, pred):
    return keras.backend.mean(keras.backend.square(true-pred), axis=-1)
</code>```

Body:
Please note that I am new to tensorflow, and machine learning in general.

I have a neural network training on a set of imbalanced data, and thus I require different sample weights.

My model is constructed like so:

def loss(a1, a2):
    customloss = keras.backend.mean(keras.backend.square((a1 - a2)))
    return customloss

def build_model():
    model = keras.Sequential()
    model.add(keras.layers.Dense(101, activation=keras.activations.linear, input_shape=(101,)))
    model.add(keras.layers.Dense(101, activation=keras.activations.linear))
    model.add(keras.layers.Dense(101))

    optimizer = keras.optimizers.RMSprop(0.00001)

    model.compile(loss=loss, optimizer=optimizer, metrics=['mae', 'accuracy'])

    return model

and I am training it like so:

EPOCHS=400
early_stop = keras.callbacks.EarlyStopping(monitor='val_loss', patience=20)
model = build_model()
history = model.fit(x, y, epochs=EPOCHS, validation_split=0.2, verbose=1, sample_weight=weights, callbacks=[early_stop])

where weights is an array of shape (9171,), and x and y each have shape (9171,101).

If I remove the sample_weight argument, the network runs. But with it in place, I get the following error message:

Epoch 1/400
Traceback (most recent call last):
  File "nnotest.py", line 153, in <module>
    history = model.fit(x, y, epochs=EPOCHS, validation_split=0.2, verbose=1, sample_weight=weights, callbacks=[early_stop])
  File "/home/star2/hgc4/.local/lib/python3.6/site-packages/tensorflow/python/keras/engine/training.py", line 780, in fit
    steps_name='steps_per_epoch')
  File "/home/star2/hgc4/.local/lib/python3.6/site-packages/tensorflow/python/keras/engine/training_arrays.py", line 363, in model_iteration
    batch_outs = f(ins_batch)
  File "/home/star2/hgc4/.local/lib/python3.6/site-packages/tensorflow/python/keras/backend.py", line 3292, in __call__
    run_metadata=self.run_metadata)
  File "/home/star2/hgc4/.local/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1458, in __call__
    run_metadata_ptr)
tensorflow.python.framework.errors_impl.InvalidArgumentError: Can not squeeze dim[0], expected a dimension of 1, got 32
     [[{{node loss_1/dense_8_loss/weighted_loss/Squeeze}}]]

I have my ideas about why this might not be working. I get that it may be trying to parse my 1D array into the default batch size of 32, but I can't understand why. From reading the documentation it would appear that you can add a 1D array to constitute a 1D mapping from weights to training data, so this should be easy? What am I missing?

Body:
Because your loss doesn't have samples. You are getting a global mean.

If mean squared error is what you want, compile with loss='mse'.

If anything else, don't collapse the batch dimension (axis=0):

def loss(true, pred):
    return keras.backend.mean(keras.backend.square(true-pred), axis=-1)


问:
Determine cardinlity of sets in GAMS
How can I determine the cardinality of a set in GAMS? Is there a keyword for this in GAMS?

Suppose I have the following declaration:

SET y  /1 * 10/ ;

I would like later in the model to make the asignment
x = cardinality_of_y;
How can I write this in GAMS?

答: The operator card() does the job.</p>

Title: Determine cardinlity of sets in GAMS

Body: The operator card() does the job.


问:
Cannot find a differ supporting object '[object Object]' of type 'object'. - context menu issues
I have issues with context menu. I am not sure why, I made similar thing many times but now I am unable to pass it. When I deleted this line:

```<code><div *ngFor="let element of contextMenu">
</div>
</code>```

Context menu works fine (but I need this line to fill my context menu.
This is part of html:

```<code><mat-menu #contextMenu="matMenu">
    <ng-template matMenuContent>
    <div *ngFor="let element of contextMenu">
    </div>
    </ng-template>
</mat-menu>
</code>```

And my context menu object:

```<code>  @Input() contextMenu: MenuElement[];
</code>```

And html with filled input:

```<code>  <lib-mp-file-explorer
          [fileElements]="fileElements | async"
          [path]="currentPath"
          [canNavigateUp]="canNavigateUp"
          [topMenu]="topMenu"
          [contextMenu]="contextMenu"
          (folderAdded)="addFolder($event)"
          (elementRemoved)="removeElement($event)"
          (navigatedDown)="navigateToFolder($event)"
          (navigatedUp)="navigateUp()"
          (elementRenamed)="renameElement($event)"
          (elementMoved)="moveElement($event)"
        >
  </lib-mp-file-explorer>
</code>```

And my construction:

```<code>this.contextMenu = [
      {
        name: 'Open in Mark',
        icon: 'M',
        action: undefined,
        disabled: true
      },
      ...
]
</code>```

I hate this error now:

core.js:5828 ERROR Error: Cannot find a differ supporting object
  '[object Object]' of type 'object'. NgFor only supports binding to
  Iterables such as Arrays.

But my array is iterable T.T

答:
Your menu reference variable has the same name..

<mat-menu #contextMenu="matMenu">

..as the array you are trying to loop through

A template reference variable is not iterable.

Try renaming your array:

```<code><div *ngFor="let element of menuElements">
</code>```

And Input():

```<code>@Input() menuElements: MenuElement[];
</code>```

and then

```<code>this.menuElements = [
 // your data
]
</code>```

Body:
I have issues with context menu. I am not sure why, I made similar thing many times but now I am unable to pass it. When I deleted this line:

Context menu works fine (but I need this line to fill my context menu.
This is part of html:

<mat-menu #contextMenu="matMenu">
    <ng-template matMenuContent>

    </ng-template>
</mat-menu>

And my context menu object:

  @Input() contextMenu: MenuElement[];

And html with filled input:

  <lib-mp-file-explorer
          [fileElements]="fileElements | async"
          [path]="currentPath"
          [canNavigateUp]="canNavigateUp"
          [topMenu]="topMenu"
          [contextMenu]="contextMenu"
          (folderAdded)="addFolder($event)"
          (elementRemoved)="removeElement($event)"
          (navigatedDown)="navigateToFolder($event)"
          (navigatedUp)="navigateUp()"
          (elementRenamed)="renameElement($event)"
          (elementMoved)="moveElement($event)"
        >
  </lib-mp-file-explorer>

And my construction:

this.contextMenu = [
      {
        name: 'Open in Mark',
        icon: 'M',
        action: undefined,
        disabled: true
      },
      ...
]

I hate this error now:

core.js:5828 ERROR Error: Cannot find a differ supporting object
  '[object Object]' of type 'object'. NgFor only supports binding to
  Iterables such as Arrays.

But my array is iterable T.T

Body:
Your menu reference variable has the same name..

<mat-menu #contextMenu="matMenu">

..as the array you are trying to loop through

<div *ngFor="let element of contextMenu">

A template reference variable is not iterable.

Try renaming your array:

<div *ngFor="let element of menuElements">

And Input():

@Input() menuElements: MenuElement[];

and then

this.menuElements = [
 // your data
]


问:
Fading one div into another
I'm having some slight problems with fading one div into another, here's my code (and test page):

HTML:

```<code><div id="grid">
    <div class="grid-box">
        <div class="phase-1">
           <img class="grid-image" src="http://teamworksdesign.com/v2/wp-content/themes/default/images/dtr.jpg" alt="" height="152" width="210" />
           <div class="grid-heading">
                <h2>DTR Medical</h2>
                <h3>Branding, Web, Print</h3>
            </div>
        </div>
        <div class="phase-2">
            <div class="grid-info">
                <h4>Probeything 2000</h4>
                <p>Marketing unglamorous single-use medical intruments is not simple. We helped Neurosign increasetheir sales by 25% and increasemarket awareness.</p>
            </div>
            <div class="grid-heading-hover">
                <h2>DTR Medical</h2>
                <h3>Branding, Web, Print</h3>
            </div>
        </div>
    </div>
</div>
</code>```

Javascript:

```<code><script type="text/javascript">

$(document).ready(function(){
            $(".phase-2").hide();
        });

$(function(){
$('.grid-box').hover(
        function(){
            $('.grid-box .phase-1').fadeOut(200, function(){
                $('.grid-box .phase-2').fadeIn(200);
            });
        },
        function(){
            $('.grid-box .phase-2').fadeOut(200, function(){
                $('.grid-box .phase-1').fadeIn(200);
            });
        }
        );
});
</script>
</code>```

CSS:

```<code>.phase-1 .grid-image {
    width:210px;
    height:220px;
    overflow:hidden;
    }

.phase-2 {
    position:relative;
    top:-220px;
    }
</code>```

UPDATE:
I have one "working" (see test link in question). Is it possible to stop it fading to white then fading in the next phase? I want to fade the two div into each other rather than to white first.

答:
If you type $ on the console, it answer undefined, so it probably was redefined by some other script. To use $ meaning jQuery again, use the following syntax

```<code>$(document).ready(function($) {
    // $ means jQuery again in here
});
</code>```

Notice the $ as the first argument of the function call.

Documentation here.

Title: Fading one div into another

Body:
I'm having some slight problems with fading one div into another, here's my code (and test page):

HTML:

DTR Medical

Branding, Web, Print

Probeything 2000

Marketing unglamorous single-use medical intruments is not simple. We helped Neurosign increasetheir sales by 25% and increasemarket awareness.

DTR Medical

Branding, Web, Print

Javascript:

CSS:

.phase-1 .grid-image {
    width:210px;
    height:220px;
    overflow:hidden;
    }

.phase-2 {
    position:relative;
    top:-220px;
    }

UPDATE:
I have one "working" (see test link in question). Is it possible to stop it fading to white then fading in the next phase? I want to fade the two div into each other rather than to white first.

Body:
If you type $ on the console, it answer undefined, so it probably was redefined by some other script. To use $ meaning jQuery again, use the following syntax

$(document).ready(function($) {
    // $ means jQuery again in here
});

Notice the $ as the first argument of the function call.

Documentation here.


问:
c++ move semantics when using pointers
How do I use the move assignment operator when working with raw pointers.

Is there any other way than doing something like:

```<code>void Function(T* dest)
{
    T* src = LoadT();
    (*dest) = std::move(*src);
    delete src;
}
</code>```

答:
You want to have the pointed-to-objects moved onto one another, then you are already doing that in the correct/standard/only way, that is de-reference the pointer and then move *src onto *dest.

That being said, you interface is semanticly 'problematic'. A pointer to a function is by convention taken to mean non-owning and optional. Ownership seems not to be the issue here, but optional is. Why use a pointer when you can use a reference ? and moreover why use a reference when you can just use return value ?

In effect you could simplify to:

```<code>T Function()
{
    return LoadT();
}
</code>```

Then let users of the function decide how to best use T. If T is polymorphic you could return std::unique_ptr<T> instead.

Title: c++ move semantics when using pointers

Body:
How do I use the move assignment operator when working with raw pointers.

Is there any other way than doing something like:

void Function(T* dest)
{
    T* src = LoadT();
    (*dest) = std::move(*src);
    delete src;
}

Body:
You want to have the pointed-to-objects moved onto one another, then you are already doing that in the correct/standard/only way, that is de-reference the pointer and then move *src onto *dest.

That being said, you interface is semanticly 'problematic'. A pointer to a function is by convention taken to mean non-owning and optional. Ownership seems not to be the issue here, but optional is. Why use a pointer when you can use a reference ? and moreover why use a reference when you can just use return value ?

In effect you could simplify to:

T Function()
{
    return LoadT();
}

Then let users of the function decide how to best use T. If T is polymorphic you could return std::unique_ptr<T> instead.


问:
remove the textfield on button click not working reactjs
I have multiple date textfield with close button, on clicking on close(x) should delete the textfield,
But not working,( remove the textfield on clicking on close button )
Here is my codelink https://codesandbox.io/s/strange-http-zhj4f</p>

答:
Better to code your map() this way

```<code>{closedatearr.map(datevalue => {
          return (
            <div className="text-content" key={datevalue.toString()}>
              <input type="text" value={datevalue} className="inputfield" readOnly />
              <button
                type="button"
                onClick={() => this.textareaHandler(datevalue)}
              >
                X
              </button>
            </div>
          );
        })}
</code>```

Body:
Better to code your map() this way

{closedatearr.map(datevalue => {
          return (
            <div className="text-content" key={datevalue.toString()}>
              <input type="text" value={datevalue} className="inputfield" readOnly />
              <button
                type="button"
                onClick={() => this.textareaHandler(datevalue)}
              >
                X
              </button>
            </div>
          );
        })}


问:
minikube stop doesn't stop the pods after sudo minikube start --vm-driver none. kube-apiserver still running
I use minikube v1.6.2, kubectl 1.17.

I start minikube without Virtualbox, with:

```<code>sudo minikube start --vm-driver none
</code>```

Now, to stop it, I do:

```<code>sudo minikube stop
minikube stop # I don't know which one is the good one, but I do both
</code>```

but, after that, when I do:

```<code>kubectl get po
</code>```

I still get the pods listing. The only way to stop it is to actually reboot my machine.

Why is it happening, and how should I fix it ?

答:
minikube stop when used with --vm-driver=none does not do any cleanup of the pods. As mentioned here:

When minikube starts without a hypervisor, it installs a local kubelet
  service on your host machine, which is important to know for later.

Right now it seems that minikube start is the only command aware of
  --vm-driver=none. Running minikube stop keeps resulting in errors related to docker-machine, and as luck would have it also results in
  none of the Kubernetes containers terminating, nor the kubelet service
  stopping.

Of course, if you wish to actually terminate minikube, you will need
  to execute service kubelet stop and then ensure the k8s containers are
  removed from the output in docker ps.

If you wish to know the overview of none (bare-metal) driver you can find it here.

Also as a workaround you can stop and remove all Docker containers that have 'k8s' in their name by executing the following command: docker stop (docker ps -q --filter name=k8s) and  docker rm (docker ps -aq --filter name=k8s).

Please let me know if that helped.

Body:
I use minikube v1.6.2, kubectl 1.17.

I start minikube without Virtualbox, with:

sudo minikube start --vm-driver none

Now, to stop it, I do:

sudo minikube stop
minikube stop # I don't know which one is the good one, but I do both

but, after that, when I do:

kubectl get po

I still get the pods listing. The only way to stop it is to actually reboot my machine.

Why is it happening, and how should I fix it ?


问:
Dax - grouping data for Sankey Chart in Power Bi
I am trying to group my data based on the column "Type" and prepare a sankey chart with Country data.
The desire results is to have value by country for type - "MLA" and value for country for type "Sponsor". The tricky part is that there is a lot of duplicated information and it needs to be by unique ID.

答:
You could look into potentially using the GROUPBY function:

https://learn.microsoft.com/en-us/dax/groupby-function-dax

You would add this to a blank table, and then it would create a summarised version of the original data table but summarised into the columns that you choose.


问:
How to count the number of rows containing a specific number in it's column
I would like to echo a count how many rows are containing the same specific number.

I have a column called "member_group_id" in my db.

For example, the leader group id is "4" some members have this number assigned in the db, so I would like to do something like:

```<code>$countLeaders = count($row['member_group_id'] == 4);
</code>```

How could I do that?

Here is my db query:

```<code>$result = mysqli_query($con,"SELECT * FROM core_members WHERE member_group_id IN (4, 7, 8, 6, 11) ORDER BY
    CASE member_group_id
        WHEN '4' THEN 1
        WHEN '7' THEN 2
        WHEN '8' THEN 3
        WHEN '6' THEN 4
        WHEN '11' THEN 5
    END ASC, name ASC");
</code>```

Here's my actual loop and desired result:

```<code>while($row = mysqli_fetch_array($result)){
    $group = $row['member_group_id'];
    $countLeaders = count($group == 4);
}

echo "<span>" . $countLeaders . " Leaders</span>";
</code>```

答:
You can't have an array with multiple time same key at same level, i explain :

```<code>$test['hello'] = 1;
$test['hello'] = 5;
</code>```

So key hello will contains only 5.
If you want to count all keys with same value, you can write a code like this:

```<code>$array = array('1', '1', '2', 'test' => '1', '1', '2', '3', '1', '9');
$count = \count(array_keys($array, '1'));
// output of $count is 5
</code>```

Search all keys corresponding to specified value, then count all keys.

Body:
I would like to echo a count how many rows are containing the same specific number.

I have a column called "member_group_id" in my db.

For example, the leader group id is "4" some members have this number assigned in the db, so I would like to do something like:

$countLeaders = count($row['member_group_id'] == 4);

How could I do that?

Here is my db query:

$result = mysqli_query($con,"SELECT * FROM core_members WHERE member_group_id IN (4, 7, 8, 6, 11) ORDER BY
    CASE member_group_id
        WHEN '4' THEN 1
        WHEN '7' THEN 2
        WHEN '8' THEN 3
        WHEN '6' THEN 4
        WHEN '11' THEN 5
    END ASC, name ASC");

Here's my actual loop and desired result:

while($row = mysqli_fetch_array($result)){
    $group = $row['member_group_id'];
    $countLeaders = count($group == 4);
}

echo "" . $countLeaders . " Leaders";

Body:
You can't have an array with multiple time same key at same level, i explain :

$test['hello'] = 1;
$test['hello'] = 5;

So key hello will contains only 5.
If you want to count all keys with same value, you can write a code like this:

$array = array('1', '1', '2', 'test' => '1', '1', '2', '3', '1', '9');
$count = \count(array_keys($array, '1'));
// output of $count is 5

Search all keys corresponding to specified value, then count all keys.


问:
How to getRange() of a group of cells while doing iteration in a Google Apps Script?
I want to check if there is any blank cells in a given range and trying to use below code for that. Problem is Range is not certain and subject to change with every iteration.
I tried something like getRange('A'+ row : 'H'+ row) but its in wrong syntax. Can someone help me with this issue ? Thanks!

var sheet1 = spreadsheet.getSheetByName('Red'); // Get worksheet
var endRow = sheet1.getLastRow();
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet(); // Get current active spreadsheet.
var sheet2 = spreadsheet.getSheetByName('Template');
var runloop = true;
var startRow = 3;

for (var row = startRow; row <= endRow; row++) {

    var sheet_name = sheet1.getRange("A" + row).getValue(); // Get the JD number for the file name.
    var range = sheet1.getRange('A' + row: 'H' + row);

    if (range.isBlank()) {
        # Dome Something here
    }
}
```

答:
You can concatenate the A1Notation before passing it to getRange()

Example:

function myFunction() {
  for (var row = 1; row <= 5; row++) {
    var rangeA = "A" + row;
    var rangeB = "H" + row;
    var range = rangeA + ":" + rangeB;

    Logger.log(range);

    // Get the JD number for the file name.
    var sheet_name = SpreadsheetApp.getActiveSheet().getRange(rangeA).getValue();
    var range = SpreadsheetApp.getActiveSheet().getRange(range);

    if (range.isBlank()) {

      Logger.log(range.getA1Notation() + " is blank!.");

    }
  }
}
```

Output log from the example:

Body:
You can concatenate the A1Notation before passing it to getRange()

Example:

function myFunction() {
  for (var row = 1; row <= 5; row++) {
    var rangeA = "A" + row;
    var rangeB = "H" + row;
    var range = rangeA + ":" + rangeB;

    Logger.log(range);

    // Get the JD number for the file name.
    var sheet_name = SpreadsheetApp.getActiveSheet().getRange(rangeA).getValue();
    var range = SpreadsheetApp.getActiveSheet().getRange(range);

    if (range.isBlank()) {

      Logger.log(range.getA1Notation() + " is blank!.");

    }
  }
}

Output log from the example:


问:
Maximum Size List in Java
It's useful to me to have a data structure in Java that has all the functionality of a List, but has a maximum storage capacity, and drops older data when newer data is added. Conceivably at some point I might want to implement a fixed size Queue which keeps a more general ordering of the data, and drops the old data lowest in that ordering, but that's the for the future.

At the moment I'm implementing it like this:

```<code>public class FixedSizeList<T> {

  private final int maxSize;
  private final LinkedList<T> list = new LinkedList<T>();

  public FixedSizeQueue(int maxSize) {
    this.maxSize = maxSize < 0 ? 0 : maxSize;
  }

  public T add(T t) {
    list.add(t);
    return list.size() > maxSize ? list.remove() : null;
  }

  // add remaining methods...

}
</code>```

Is there either (a) an existing data structure that serves my needs, or (b) a better way of implementing this data structure?

答:
Unless you want to use an actual array, I don't believe there is a list type data structure you can use.

Personally I would extend one of the existing list classes to get the functionality, and override the add methods.  This way you get all the other list operations for free. ie something like the following...

```<code>public class FixedSizeArrayList<T> extends ArrayList<T> {
    private final int maxSize;
    public FixedSizeArrayList(int maxSize) {
        super();
        this.maxSize = maxSize
    }

    public boolean add(T t) {
        if (size() >= maxSize) {
            remove(0);
        }
        return super.add(t);
    }

    // implementation of remaining add methods....
}
</code>```

Title: Maximum Size List in Java

Body:
It's useful to me to have a data structure in Java that has all the functionality of a List, but has a maximum storage capacity, and drops older data when newer data is added. Conceivably at some point I might want to implement a fixed size Queue which keeps a more general ordering of the data, and drops the old data lowest in that ordering, but that's the for the future.

At the moment I'm implementing it like this:

public class FixedSizeList<T> {

  private final int maxSize;
  private final LinkedList<T> list = new LinkedList<T>();

  public FixedSizeQueue(int maxSize) {
    this.maxSize = maxSize < 0 ? 0 : maxSize;
  }

  public T add(T t) {
    list.add(t);
    return list.size() > maxSize ? list.remove() : null;
  }

  // add remaining methods...

}

Is there either (a) an existing data structure that serves my needs, or (b) a better way of implementing this data structure?

Body:
Unless you want to use an actual array, I don't believe there is a list type data structure you can use.

Personally I would extend one of the existing list classes to get the functionality, and override the add methods.  This way you get all the other list operations for free. ie something like the following...

public class FixedSizeArrayList<T> extends ArrayList<T> {
    private final int maxSize;
    public FixedSizeArrayList(int maxSize) {
        super();
        this.maxSize = maxSize
    }

    public boolean add(T t) {
        if (size() >= maxSize) {
            remove(0);
        }
        return super.add(t);
    }

    // implementation of remaining add methods....
}


问:
How can I add an empty row in a for loop based on a previous for loop?
I'm trying to make a comparison report that displays sales for two time periods, in this scenario i've selected 1-31 October and 1-30th November. I am loading the data from the same Json file but as two seperate queries, the first uses the October period and the second uses the November period.

This is the code I have currently:

```<code>// October 1-31
<div class="col-6" *ngFor="let periods of reportData">
    <div *ngFor="let reportVal of periods.groupedTransactions">
        <div class="row" *ngIf="reportData.length > 0">
            <div class="col-12">
                <h6>Customer: {{reportVal.name}}</h6>
            </div>
            <div class="col">
                <h6>Total Sales: {{reportVal.totalSales | number}}</h6>
            </div>
        </div>
    </div>
</div>
// November 1-30
<div class="col-6" *ngFor="let comPeriods of comReportData">
    <div *ngFor="let reportVal of comPeriods.groupedTransactions">
        <div class="row" *ngIf="comReportData.length > 0">
            <div class="col-12">
                <h6>Customer: {{reportVal.name}}</h6>
            </div>
            <div class="col">
                <h6>Total Sales: {{reportVal.totalSales | number}}</h6>
            </div>
        </div>
    </div>
</div>
</code>```

And this is the result:

Is there a way to add a function that will add an empty row in the November if there is no sales from that customer? I want to have all the Customers vertically aligned.

Because the periods for loop is based on the selected dates, putting the columns in the same loop will only get data from one date.

If anyone can help me out or tell me where to look to solve this it would be greatly appreciated!

答:
One solution would be to align the two periods. For example adding an entry with the name of the missing customer and a total sales of 0.I don't know how your json likes like but maybe you should also assume that the order of the customers might not be the same for different periods. Sorting both by name might be a solution.

You could come up with something like this to align both periods:

```<code>interface CustomerReport {
  name: string;
  totalSales: number;
}

alignPeriods(firstPeriod: CustomerReport[], secondPeriod: CustomerReport[]) {
    const alignedFirstPeriod: CustomerReport[] = Object.assign([], firstPeriod);
    const alignedSecondPeriod: CustomerReport[] = [];

    firstPeriod.forEach(customer => {
      const secondCustomer = secondPeriod.find(secCustomer => secCustomer.name === customer.name);
      if (!secondCustomer) {
        alignedSecondPeriod.push({name: customer.name, totalSales: 0});
      } else {
        alignedSecondPeriod.push(secondCustomer);
      }
    });

    secondPeriod.forEach(customer => {
      const firstCustomer = firstPeriod.find(fstCustomer => fstCustomer.name === customer.name);
      if (!firstCustomer) {
        alignedFirstPeriod.push({name: customer.name, totalSales: 0});
        alignedSecondPeriod.push(customer);
      }
    });

    const alignedCustomers = [alignedFirstPeriod, alignedSecondPeriod];
    return alignedCustomers;
  }
</code>```

This function makes sure both arrays are in the same order and adds a new entry with totalSales:0 for all customers which are not in the other period. This assumes the names of your customers are unique ids.

Now you can loop over both aligned arrays in your template.

This will work but it is not a clean solution, you should consider changing your data model like Kurt Hamilton mentioned in his answer.

Body:
I'm trying to make a comparison report that displays sales for two time periods, in this scenario i've selected 1-31 October and 1-30th November. I am loading the data from the same Json file but as two seperate queries, the first uses the October period and the second uses the November period.

This is the code I have currently:

// October 1-31

 0">

Customer: {{reportVal.name}}

Total Sales: {{reportVal.totalSales | number}}

// November 1-30

 0">

Customer: {{reportVal.name}}

Total Sales: {{reportVal.totalSales | number}}

And this is the result:

Is there a way to add a function that will add an empty row in the November if there is no sales from that customer? I want to have all the Customers vertically aligned.

Because the periods for loop is based on the selected dates, putting the columns in the same loop will only get data from one date.

If anyone can help me out or tell me where to look to solve this it would be greatly appreciated!

Body:
One solution would be to align the two periods. For example adding an entry with the name of the missing customer and a total sales of 0.I don't know how your json likes like but maybe you should also assume that the order of the customers might not be the same for different periods. Sorting both by name might be a solution.

You could come up with something like this to align both periods:

interface CustomerReport {
  name: string;
  totalSales: number;
}

alignPeriods(firstPeriod: CustomerReport[], secondPeriod: CustomerReport[]) {
    const alignedFirstPeriod: CustomerReport[] = Object.assign([], firstPeriod);
    const alignedSecondPeriod: CustomerReport[] = [];

    firstPeriod.forEach(customer => {
      const secondCustomer = secondPeriod.find(secCustomer => secCustomer.name === customer.name);
      if (!secondCustomer) {
        alignedSecondPeriod.push({name: customer.name, totalSales: 0});
      } else {
        alignedSecondPeriod.push(secondCustomer);
      }
    });

    secondPeriod.forEach(customer => {
      const firstCustomer = firstPeriod.find(fstCustomer => fstCustomer.name === customer.name);
      if (!firstCustomer) {
        alignedFirstPeriod.push({name: customer.name, totalSales: 0});
        alignedSecondPeriod.push(customer);
      }
    });

    const alignedCustomers = [alignedFirstPeriod, alignedSecondPeriod];
    return alignedCustomers;
  }

This function makes sure both arrays are in the same order and adds a new entry with totalSales:0 for all customers which are not in the other period. This assumes the names of your customers are unique ids.

Now you can loop over both aligned arrays in your template.

This will work but it is not a clean solution, you should consider changing your data model like Kurt Hamilton mentioned in his answer.


问:
What is the swift way of converting this string into PGN notation?
I have the following string

```<code>let a:String = "r0bqkb0r/pppppppp/00n00n00/00000000/000P0000/0000B000/PPP0PPPP/RN0QKBNR/"
</code>```

and want to convert this to PGN notation so the final result should be

```<code>result = "r1bqkb1r/pppppppp/2n2n2/8/3P4/4B3/PPP1PPPP/RN1QKBNR/"
</code>```

The PGN notation converts the zeros to counts found.  Normally in python, I would just use

import chess.pgn

Before deep diving into python library, is there is a succinct and 'Swift' way to do this?

答:
Here is a solution using reduce and a separate counter

Update, rewrote it as an extension to String

```<code>extension String {
    func pgpNotation() -> String {
        var zeroCounter = 0
        var result = self.reduce(into: "") {
            if $1 == "0" {
                zeroCounter += 1
                return
            }

            if zeroCounter > 0 {
                $0.append("\(zeroCounter)")
                zeroCounter = 0
            }
            $0.append($1)
        }
        if zeroCounter > 0 { result.append("\(zeroCounter)")}
        return result
    }
}
</code>```

Examples

```<code>let x = "r00d00"
print(x.pgpNotation())

let a:String = "r0bqkb0r/pppppppp/00n00n00/00000000/000P0000/0000B000/PPP0PPPP/RN0QKBNR/"
print(a.pgpNotation())
</code>```

r2d2

  r1bqkb1r/pppppppp/2n2n2/8/3P4/4B3/PPP1PPPP/RN1QKBNR/

Body:
I have the following string

let a:String = "r0bqkb0r/pppppppp/00n00n00/00000000/000P0000/0000B000/PPP0PPPP/RN0QKBNR/"

and want to convert this to PGN notation so the final result should be

result = "r1bqkb1r/pppppppp/2n2n2/8/3P4/4B3/PPP1PPPP/RN1QKBNR/"

The PGN notation converts the zeros to counts found.  Normally in python, I would just use

import chess.pgn

Before deep diving into python library, is there is a succinct and 'Swift' way to do this?

Body:
Here is a solution using reduce and a separate counter

Update, rewrote it as an extension to String

extension String {
    func pgpNotation() -> String {
        var zeroCounter = 0
        var result = self.reduce(into: "") {
            if $1 == "0" {
                zeroCounter += 1
                return
            }

            if zeroCounter > 0 {
                $0.append("\(zeroCounter)")
                zeroCounter = 0
            }
            $0.append($1)
        }
        if zeroCounter > 0 { result.append("\(zeroCounter)")}
        return result
    }
}

Examples

let x = "r00d00"
print(x.pgpNotation())

let a:String = "r0bqkb0r/pppppppp/00n00n00/00000000/000P0000/0000B000/PPP0PPPP/RN0QKBNR/"
print(a.pgpNotation())

r2d2

  r1bqkb1r/pppppppp/2n2n2/8/3P4/4B3/PPP1PPPP/RN1QKBNR/


问:
Defining Custom GroupBy Aggregation Function Using Pandas Results in an AttributeError
I have a Pandas data frame -

```<code>data = {'year':[1990, 1990, 1990,
                1990, 1990, 1990,
                1990, 1990, 1990],
        'zip':['22204', '22204', '22204',
               '20194', '20194', '20194',
               '24060', '24060', '24060'],
        'education':[0, 0, 1,
                     1, 0, 1,
                     0, 1, 0]}
df = pd.DataFrame(data = data)
</code>```

And I would like to calculate the percent of each outcome in the education variable education using the groupby function -

```<code>df = df.groupby(['zip', 'year'])['education'].value_counts(normalize = True, dropna = False).unstack().fillna(0)
</code>```

However, I would like to call the line of code within a custom aggregation function. When I run the lines of code below, I get this error message - AttributeError: 'Float64Index' object has no attribute 'remove_unused_levels'.

```<code>def percent_by_category(group):
    return group.value_counts(normalize = True, dropna = False).unstack().fillna(0)
df = df.groupby(['zip', 'year']).agg({'education':percent_by_category})
</code>```

Is it possible to create a custom aggregation function that calculates the percent of each outcome on the groupby groups? Ideally, I would like to call several other built-in and custom aggregation functions. For example -

```<code>df = df.groupby(['zip', 'year']).agg({'education':percent_by_category,
                                      'education':sum,
                                      'education':another_custom_function,
                                       another_variable:another_custom_function})
</code>```

答:
No, if use agg function is necessary scalar output of aggregation function.

If test how working .value_counts(), there are Series, so not possible unstack them.

```<code>def percent_by_category(group):
    print (group.value_counts(normalize = True, dropna = False))

df = df.groupby(['zip', 'year']).agg({'education':percent_by_category})
print (df)
1    0.666667
0    0.333333
Name: education, dtype: float64
0    0.666667
1    0.333333
Name: education, dtype: float64
0    0.666667
1    0.333333
Name: education, dtype: float64
           education
zip   year
20194 1990      None
22204 1990      None
24060 1990      None
</code>```

So if want return non scalar output it raise error:

```<code>def percent_by_category(group):
    return group.value_counts(normalize = True, dropna = False)

df = df.groupby(['zip', 'year']).agg({'education':percent_by_category})
print (df)
</code>```

ValueError: Function does not reduce

Body:
I have a Pandas data frame -

data = {'year':[1990, 1990, 1990,
                1990, 1990, 1990,
                1990, 1990, 1990],
        'zip':['22204', '22204', '22204',
               '20194', '20194', '20194',
               '24060', '24060', '24060'],
        'education':[0, 0, 1,
                     1, 0, 1,
                     0, 1, 0]}
df = pd.DataFrame(data = data)

And I would like to calculate the percent of each outcome in the education variable education using the groupby function -

df = df.groupby(['zip', 'year'])['education'].value_counts(normalize = True, dropna = False).unstack().fillna(0)

However, I would like to call the line of code within a custom aggregation function. When I run the lines of code below, I get this error message - AttributeError: 'Float64Index' object has no attribute 'remove_unused_levels'.

def percent_by_category(group):
    return group.value_counts(normalize = True, dropna = False).unstack().fillna(0)
df = df.groupby(['zip', 'year']).agg({'education':percent_by_category})

Is it possible to create a custom aggregation function that calculates the percent of each outcome on the groupby groups? Ideally, I would like to call several other built-in and custom aggregation functions. For example -

df = df.groupby(['zip', 'year']).agg({'education':percent_by_category,
                                      'education':sum,
                                      'education':another_custom_function,
                                       another_variable:another_custom_function})

Body:
No, if use agg function is necessary scalar output of aggregation function.

If test how working .value_counts(), there are Series, so not possible unstack them.

def percent_by_category(group):
    print (group.value_counts(normalize = True, dropna = False))

df = df.groupby(['zip', 'year']).agg({'education':percent_by_category})
print (df)
1    0.666667
0    0.333333
Name: education, dtype: float64
0    0.666667
1    0.333333
Name: education, dtype: float64
0    0.666667
1    0.333333
Name: education, dtype: float64
           education
zip   year
20194 1990      None
22204 1990      None
24060 1990      None

So if want return non scalar output it raise error:

def percent_by_category(group):
    return group.value_counts(normalize = True, dropna = False)

df = df.groupby(['zip', 'year']).agg({'education':percent_by_category})
print (df)

ValueError: Function does not reduce