问:
PL/SQL call from JDBC resulting in "SQLSyntaxErrorException: ORA-00900"
I'm trying to use the following code to run a PL/SQL statement on my database server.

```<code>public class Main {
    public static void main(String[] args) {
        String jdbcURL = "jdbc:oracle:thin:@172.22.88.9:1521/xavier.i.com";

        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;

        String user = "bigdb";
        String password = "fakepassword";
        String result = null;
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
            conn = DriverManager.getConnection(jdbcURL, user, password);

            result = runStatement(conn,
              "{begin ANALYZE TABLE BIGDB.scr_fct_exact_access
              ESTIMATE STATISTICS; end}");

        } catch (Exception ex) {
            System.out.println(ex.getMessage());
            ex.printStackTrace();
        }
    }

    private static String runStatement(Connection con, String statement)
      throws Exception {
        PreparedStatement cstmt = con.prepareStatement(statement);
        cstmt.execute(); // this is line 58
        cstmt.close();

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

On running the code, I get the following exception:

java.sql.SQLSyntaxErrorException: ORA-00900: invalid SQL statement

at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:440)

          at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:396)

          at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:837)

          at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:445)

          at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:191)

          at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:523)

          at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:207)

          at oracle.jdbc.driver.T4CPreparedStatement.executeForRows(T4CPreparedStatement.java:1010)Time : -1307015416548

at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1315)

          at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3576)

          at oracle.jdbc.driver.OraclePreparedStatement.execute(OraclePreparedStatement.java:3677)

          at oracle.jdbc.driver.OraclePreparedStatementWrapper.execute(OraclePreparedStatementWrapper.java:1374)

          at Main.prepareStatement(Main.java:58)

          at Main.main(Main.java:29)

What is going wrong, and how can I fix it?

答:
ANALYZE TABLE is a DDL (data definition language) statement. It's not valid within a BEGIN/END block in PL/SQL. If you wanted to execute it in PL/SQL, you'd need to use EXECUTE IMMEDIATE.

To run the statement from JDBC, just create a Statement instance and use executeUpdate:

```<code>Statement stmt = con.createStatement();
stmt.executeUpdate("ANALYZE TABLE BIGDB.scr_fct_exact_access ESTIMATE STATISTICS");
stmt.close();
</code>```

But a even better idea is to use the DBMS_STATS package to analyze your tables. Then you can use your approach with BEGIN/END.

Body:
I'm trying to use the following code to run a PL/SQL statement on my database server.

public class Main {
    public static void main(String[] args) {
        String jdbcURL = "jdbc:oracle:thin:@172.22.88.9:1521/xavier.i.com";

        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;

        String user = "bigdb";
        String password = "fakepassword";
        String result = null;
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
            conn = DriverManager.getConnection(jdbcURL, user, password);

            result = runStatement(conn,
              "{begin ANALYZE TABLE BIGDB.scr_fct_exact_access
              ESTIMATE STATISTICS; end}");

        } catch (Exception ex) {
            System.out.println(ex.getMessage());
            ex.printStackTrace();
        }
    }

    private static String runStatement(Connection con, String statement)
      throws Exception {
        PreparedStatement cstmt = con.prepareStatement(statement);
        cstmt.execute(); // this is line 58
        cstmt.close();

        return count;
    }
}

On running the code, I get the following exception:

java.sql.SQLSyntaxErrorException: ORA-00900: invalid SQL statement

at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:440)

          at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:396)

          at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:837)

          at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:445)

          at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:191)

          at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:523)

          at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:207)

          at oracle.jdbc.driver.T4CPreparedStatement.executeForRows(T4CPreparedStatement.java:1010)Time : -1307015416548

at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1315)

          at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3576)

          at oracle.jdbc.driver.OraclePreparedStatement.execute(OraclePreparedStatement.java:3677)

          at oracle.jdbc.driver.OraclePreparedStatementWrapper.execute(OraclePreparedStatementWrapper.java:1374)

          at Main.prepareStatement(Main.java:58)

          at Main.main(Main.java:29)

What is going wrong, and how can I fix it?

Body:
ANALYZE TABLE is a DDL (data definition language) statement. It's not valid within a BEGIN/END block in PL/SQL. If you wanted to execute it in PL/SQL, you'd need to use EXECUTE IMMEDIATE.

To run the statement from JDBC, just create a Statement instance and use executeUpdate:

Statement stmt = con.createStatement();
stmt.executeUpdate("ANALYZE TABLE BIGDB.scr_fct_exact_access ESTIMATE STATISTICS");
stmt.close();

But a even better idea is to use the DBMS_STATS package to analyze your tables. Then you can use your approach with BEGIN/END.


来源: stackexchange

问:
How can I convert a column with datetime format to just a year?
I have a column of datetime with values like 10/10/49 20:30, but need to mutate the dataframe to have a column of just the date in format 1949. The code below is just bringing me a column of NA. How can I extract the year? I need to use dplyr to solve this!</p>
```<code>df %>%
  mutate(., year = format(as.Date(x = datetime, format="%d/%m/%y %I:%M:%S %p"),"%Y"))
</code>```

答:
2 digit years are confusing. Looking at the date "10/10/49" how do you know whether it is 1949 or 2049?

R prefixes 2 digit year from 00-68 with 20 (2000-2068) and 69-99 with 19 (1969-1999) so based on your data you need to come up with a condition that will adjust the year based on your requirement.

For example, let's say you know that you don't have any dates greater than the current year in your data in that case you can do :

```<code>library(dplyr)
library(lubridate)

df %>%
  mutate(datetime = dmy_hm(datetime),
         year = year(datetime),
         rev_year = if_else(year > 2020, year - 100, year))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a column of datetime with values like 10/10/49 20:30, but need to mutate the dataframe to have a column of just the date in format 1949. The code below is just bringing me a column of NA. How can I extract the year? I need to use dplyr to solve this!

df %>%
  mutate(., year = format(as.Date(x = datetime, format="%d/%m/%y %I:%M:%S %p"),"%Y"))

Body:
2 digit years are confusing. Looking at the date "10/10/49" how do you know whether it is 1949 or 2049?

R prefixes 2 digit year from 00-68 with 20 (2000-2068) and 69-99 with 19 (1969-1999) so based on your data you need to come up with a condition that will adjust the year based on your requirement.

For example, let's say you know that you don't have any dates greater than the current year in your data in that case you can do :

library(dplyr)
library(lubridate)

df %>%
  mutate(datetime = dmy_hm(datetime),
         year = year(datetime),
         rev_year = if_else(year > 2020, year - 100, year))


问:
Get S3 Objects With Apache Camel
I am trying to expose a rest endpoint with camel. It will show a json data which is inside some .json files stored in s3 bucket. Also, it will filter by a date range.

First, I got some s3 objects informations in my Camel routes. (I am using kotlin)

```<code>//expose the endpoint
        from("jetty:http://0.0.0.0:8080/getObjects")
                .routeId("list-objects-on-bucket")
                .to("aws-s3://[bucket-name]?amazonS3Client=#s3Client&operation=listObjects")
                .process(ListObjects())
                .to("direct:filter-list-from-s3")
</code>```

then, I filter the data. (Till here everything is alright)

```<code>from("direct:filter-list-from-s3")
                .routeId("filter-list-from-s3")
                .process(FilterObjects())
                .to("log:info")
</code>```

But in my FilterObject class I do not know how to download every files that matches (look the if  statement) and pass it to the next route that will treat them

```<code>class SaoMateusFilterObjects : Processor {
    override fun process(exchange: Exchange?) {

        val start_date = exchange!!.getIn().getHeader("start_date") as String
        val end_date = exchange.getIn().getHeader("end_date") as String

        val formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy")
        val start = LocalDate.parse(start_date).format(formatter)
        val end = LocalDate.parse(end_date).format(formatter)

        val objectsNames = exchange!!.getIn().body as LinkedList<String>
        for (objectName in objectsNames) {
            if(objectName.contains(start) && objectName.contains(end) && objectName.contains(".json")) {
                exchange.getIn() to "aws-s3://[bucket-name]?amazonS3Client=#s3Client&operation=getObject&fileName=$objectName"
            }
        }
    }

}
</code>```

Some problems are:

1 - I want to read. By I think I can't use the from() method. Because it can be use just once. So, the to() method is used to read.

2 - exchange.getIn().to("[s3-uri]") maybe/must be converted in S3Object(). How??

Can Someone help me with this?

Thank you

答:
Instead of .to route, use .bean() and use the s3.getObject method to get the S3Object.

always Prefer using .bean() over .processor().

offical_s3_java_object operation sample.

Title: Get S3 Objects With Apache Camel

Body:
I am trying to expose a rest endpoint with camel. It will show a json data which is inside some .json files stored in s3 bucket. Also, it will filter by a date range.

First, I got some s3 objects informations in my Camel routes. (I am using kotlin)

//expose the endpoint
        from("jetty:http://0.0.0.0:8080/getObjects")
                .routeId("list-objects-on-bucket")
                .to("aws-s3://[bucket-name]?amazonS3Client=#s3Client&operation=listObjects")
                .process(ListObjects())
                .to("direct:filter-list-from-s3")

then, I filter the data. (Till here everything is alright)

from("direct:filter-list-from-s3")
                .routeId("filter-list-from-s3")
                .process(FilterObjects())
                .to("log:info")

But in my FilterObject class I do not know how to download every files that matches (look the if  statement) and pass it to the next route that will treat them

class SaoMateusFilterObjects : Processor {
    override fun process(exchange: Exchange?) {

        val start_date = exchange!!.getIn().getHeader("start_date") as String
        val end_date = exchange.getIn().getHeader("end_date") as String

        val formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy")
        val start = LocalDate.parse(start_date).format(formatter)
        val end = LocalDate.parse(end_date).format(formatter)

        val objectsNames = exchange!!.getIn().body as LinkedList<String>
        for (objectName in objectsNames) {
            if(objectName.contains(start) && objectName.contains(end) && objectName.contains(".json")) {
                exchange.getIn() to "aws-s3://[bucket-name]?amazonS3Client=#s3Client&operation=getObject&fileName=$objectName"
            }
        }
    }

}

Some problems are:

1 - I want to read. By I think I can't use the from() method. Because it can be use just once. So, the to() method is used to read.

2 - exchange.getIn().to("[s3-uri]") maybe/must be converted in S3Object(). How??

Can Someone help me with this?

Thank you


问:
can I reinstall npm in a angular project to fix it?
I have an angular 9 project. I have installed different libraries on it and after installing ngx-gallery and some issues for Rendere2 and etc, I edited some file in node-Module/angular/core like core.d.ts. I am very new to angular. now my project does not running, then I tried to delete node_module to install it again but I couldn't.
I wanna know Do I have any chance to fix all these with reinstalling npm or not.
Thanks so much

update:I attached an image of errors that I have now.

答:
You could uninstall the specific package by running npm uninstall <package>, and then reinstall it again (npm install <package>).

Since you've already deleted all packages (if I got it right) and if all the packages that you used are saved in package.json, then you should just run npm install and it will reinstall all of the dependencies over there.


问:
create a new column from existing multiple columns in R
can someone guide me how to create new 4 variables in R? I want to create new 4 variables from the below data in R something like;</p>

```<code>data$VarApple = var1 through var6 = "apple"
data$varBerry = var1 through var6 = "berry"
data$varPear = var1 through var6 = "pear"
data$varBanana = var1 through var6 = "banana"

data = data.frame(var1 = c("apple","pear","berry","apple","pear","banana","berry"),
       var2 = c("banana","apple","berry","apple","banana","banana","berry"),
       var3 = c("berry","pear","pear","apple","berry","banana","apple"),
       var4 = c("apple","banana","apple","pear","berry","pear","berry"),
       var5 = c("banana","pear","pear","apple","apple","banana","berry"),
       var6 = c("pear","berry","apple","apple","banana","banana","apple"))
</code>```

答:
We can use table to create frequency count on the unlisted dataset and cbind with the original data

```<code>cbind(data, +(table(seq_len(nrow(data))[row(data)], unlist(data)) >0))
#      var1   var2   var3   var4   var5   var6 apple banana berry pear
#1  apple banana  berry  apple banana   pear     1      1     1    1
#2   pear  apple   pear banana   pear  berry     1      1     1    1
#3  berry  berry   pear  apple   pear  apple     1      0     1    1
#4  apple  apple  apple   pear  apple  apple     1      0     0    1
#5   pear banana  berry  berry  apple banana     1      1     1    1
#6 banana banana banana   pear banana banana     0      1     0    1
#7  berry  berry  apple  berry  berry  apple     1      0     1    0
</code>```

Or with mtabulate from qdapTools

```<code>library(qdapTools)
cbind(data, +(mtabulate(as.data.frame(t(data))) > 0))
</code>```

Or a variant of the above

```<code>cbind(data, +(mtabulate(asplit(data, 1)) > 0))
</code>```

Or an option with cSplit

```<code>library(tidyr)
library(splitstackshape)
data %>%
  unite(newcol, everything(), remove = FALSE) %>%
  cSplit_e('newcol', '_', mode = 'binary', type = 'character', drop = TRUE)
</code>```

Body:
can someone guide me how to create new 4 variables in R? I want to create new 4 variables from the below data in R something like;

data$VarApple = var1 through var6 = "apple"
data$varBerry = var1 through var6 = "berry"
data$varPear = var1 through var6 = "pear"
data$varBanana = var1 through var6 = "banana"

data = data.frame(var1 = c("apple","pear","berry","apple","pear","banana","berry"),
       var2 = c("banana","apple","berry","apple","banana","banana","berry"),
       var3 = c("berry","pear","pear","apple","berry","banana","apple"),
       var4 = c("apple","banana","apple","pear","berry","pear","berry"),
       var5 = c("banana","pear","pear","apple","apple","banana","berry"),
       var6 = c("pear","berry","apple","apple","banana","banana","apple"))

Body:
We can use table to create frequency count on the unlisted dataset and cbind with the original data

cbind(data, +(table(seq_len(nrow(data))[row(data)], unlist(data)) >0))
#      var1   var2   var3   var4   var5   var6 apple banana berry pear
#1  apple banana  berry  apple banana   pear     1      1     1    1
#2   pear  apple   pear banana   pear  berry     1      1     1    1
#3  berry  berry   pear  apple   pear  apple     1      0     1    1
#4  apple  apple  apple   pear  apple  apple     1      0     0    1
#5   pear banana  berry  berry  apple banana     1      1     1    1
#6 banana banana banana   pear banana banana     0      1     0    1
#7  berry  berry  apple  berry  berry  apple     1      0     1    0

Or with mtabulate from qdapTools

library(qdapTools)
cbind(data, +(mtabulate(as.data.frame(t(data))) > 0))

Or a variant of the above

cbind(data, +(mtabulate(asplit(data, 1)) > 0))

Or an option with cSplit

library(tidyr)
library(splitstackshape)
data %>%
  unite(newcol, everything(), remove = FALSE) %>%
  cSplit_e('newcol', '_', mode = 'binary', type = 'character', drop = TRUE)


问:
jQuery UI resizable handles don't stay in the middle of the line
In this jsFiddle I have a jQuery UI resizable rectangle with handles. The problem is that when I resize the rect, sometimes the handles don't stay in the middle, see in the picture below that the line divides the handle 75% instead of 50%. Why does this happen and how to fix it?

```<code>#elementResizable {
    border: 1px solid #000000;
    width: 300px;
    height: 40px;

}
#nwgrip, #negrip, #swgrip, #segrip, #ngrip, #egrip, #sgrip, #wgrip {
    width: 6px;
    height: 6px;
    background-color: red;
}
#nwgrip {
    left: -3px;
    top: -3px;
}
#negrip{
     top: -3px;
     right: -3px;
}
#swgrip{
    bottom: -3px;
    left: -3px;
}
#segrip{
     bottom: -3px;
     right:-3px;
}
#ngrip{
     top: -3px;
    left: calc(50% - 3px);
}
#sgrip{
     bottom: -3px;
    left: calc(50% - 3px);
}
#wgrip{
     left:-3px;
     top:calc(50% - 3px);
}
#egrip{
     right:-3px;
     top:calc(50% - 3px);
}

<div id='elementResizable'>
    <div class="ui-resizable-handle ui-resizable-nw" id="nwgrip"></div>
    <div class="ui-resizable-handle ui-resizable-ne" id="negrip"></div>
    <div class="ui-resizable-handle ui-resizable-sw" id="swgrip"></div>
    <div class="ui-resizable-handle ui-resizable-se" id="segrip"></div>
    <div class="ui-resizable-handle ui-resizable-n" id="ngrip"></div>
    <div class="ui-resizable-handle ui-resizable-s" id="sgrip"></div>
    <div class="ui-resizable-handle ui-resizable-e" id="egrip"></div>
    <div class="ui-resizable-handle ui-resizable-w" id="wgrip"></div>
</div>

$('#elementResizable').resizable({
    handles: {
        'nw': '#nwgrip',
        'ne': '#negrip',
        'sw': '#swgrip',
        'se': '#segrip',
        'n': '#ngrip',
        'e': '#egrip',
        's': '#sgrip',
        'w': '#wgrip'
    }
});
</code>```

答:
I suspect this is only a rendering / visual issue. When I inspect the element, I can see if the height is 40 px, the South Grip is at a position of 37 px.

Example: https://jsfiddle.net/Twisty/u5pv79ga/13/

JavaScript

```<code>$('#elementResizable').resizable({
  handles: {
    'nw': '#nwgrip',
    'ne': '#negrip',
    'sw': '#swgrip',
    'se': '#segrip',
    'n': '#ngrip',
    'e': '#egrip',
    's': '#sgrip',
    'w': '#wgrip',
  },
  resize: function(e, ui) {
    $(".log").html("W: " + ui.size.width + ", H: " + ui.size.height + ", L: " + $("#sgrip").offset().left + ", T: " + $("#sgrip").position().top);
  }
});
</code>```

I did notice, that sometimes, the handles will hit a half pixel when being resized. This might contribute to the minor visual difference that is seen.

Body:
In this jsFiddle I have a jQuery UI resizable rectangle with handles. The problem is that when I resize the rect, sometimes the handles don't stay in the middle, see in the picture below that the line divides the handle 75% instead of 50%. Why does this happen and how to fix it?

#elementResizable {
    border: 1px solid #000000;
    width: 300px;
    height: 40px;

}
#nwgrip, #negrip, #swgrip, #segrip, #ngrip, #egrip, #sgrip, #wgrip {
    width: 6px;
    height: 6px;
    background-color: red;
}
#nwgrip {
    left: -3px;
    top: -3px;
}
#negrip{
     top: -3px;
     right: -3px;
}
#swgrip{
    bottom: -3px;
    left: -3px;
}
#segrip{
     bottom: -3px;
     right:-3px;
}
#ngrip{
     top: -3px;
    left: calc(50% - 3px);
}
#sgrip{
     bottom: -3px;
    left: calc(50% - 3px);
}
#wgrip{
     left:-3px;
     top:calc(50% - 3px);
}
#egrip{
     right:-3px;
     top:calc(50% - 3px);
}

$('#elementResizable').resizable({
    handles: {
        'nw': '#nwgrip',
        'ne': '#negrip',
        'sw': '#swgrip',
        'se': '#segrip',
        'n': '#ngrip',
        'e': '#egrip',
        's': '#sgrip',
        'w': '#wgrip'
    }
});

Body:
I suspect this is only a rendering / visual issue. When I inspect the element, I can see if the height is 40 px, the South Grip is at a position of 37 px.

Example: https://jsfiddle.net/Twisty/u5pv79ga/13/

JavaScript

$('#elementResizable').resizable({
  handles: {
    'nw': '#nwgrip',
    'ne': '#negrip',
    'sw': '#swgrip',
    'se': '#segrip',
    'n': '#ngrip',
    'e': '#egrip',
    's': '#sgrip',
    'w': '#wgrip',
  },
  resize: function(e, ui) {
    $(".log").html("W: " + ui.size.width + ", H: " + ui.size.height + ", L: " + $("#sgrip").offset().left + ", T: " + $("#sgrip").position().top);
  }
});

I did notice, that sometimes, the handles will hit a half pixel when being resized. This might contribute to the minor visual difference that is seen.


问:
create pip-installable single-module package with associated data
There are many variations on this question I've found, but none seem to address my exact situation where

The Python code for the project is contained in a single file

There are required data directories that must be included with the installation

I am trying to create a pip-installable version of the following Python project, where the project consists of a single Python script myscript, plus two different data directories, data and test_data. data contains required data files that are sourced by myscript.py at runtime:

```<code>myscript
|
├── myscript
│   ├── data
│   ├── __init__.py
│   ├── myscript.py
│   └── test_data
├── LICENSE
├── README.md
└── setup.py
</code>```

I've seen the recommendation to use py_modules in setup.py for similar issues, but that doesn't seem to allow for inclusion of the data directories upon install with pip, and I cannot find documentation that seems to cover this specific case.

I've also seen it recommended to just have users do a git clone of the repo instead of using pip, but it seems like a usability benefit to offer a way to pip-install with all dependencies while correctly adding the script to the PATH in an OS-dependent manner.

答:
This looks like a pretty standard Python package. To reproduce your situation, I have the following layout:

```<code>$ find * -type f
LICENSE
myscript/myscript.py
myscript/data/data_file_1
myscript/test_data/test_data_file_1
myscript/__init__.py
README.md
setup.cfg
setup.py
</code>```

To include the data directories, you can use the package_data option in your setup.cfg file (which is slowly replacing setup.py as the standard way to build Python packages).

We just need a stub setup.py:

```<code>from setuptools import setup

setup()
</code>```

Everything else is in setup.cfg:

```<code>[metadata]
name = myscript
version = 1.0
description = An example for glarue
long_description = file: README.md
long_description_content_type = text/markdown
url = https://github.com/larsks/so-example-glarue
author = Lars Kellogg-Stedman
author_email = lars@oddbit.com

[options]
packages = find:

[options.package_data]
myscript = data/*, test_data/*

[options.entry_points]
console_scripts =
    myscript = myscript.myscript:main
</code>```

The key part is the options.package_data` section, which, for each package, lists the glob patterns that should be included as part of the package.

If we build a source distribution from this:

```<code>$ python setup.py sdist
running sdist
...
Creating tar archive
removing 'myscript-1.0' (and everything under it)
</code>```

We can see that the data files are included in the archive:

```<code>$ tar tf dist/myscript-1.0.tar.gz
myscript-1.0/
myscript-1.0/PKG-INFO
myscript-1.0/README.md
myscript-1.0/myscript/
myscript-1.0/myscript/__init__.py
myscript-1.0/myscript/data/
myscript-1.0/myscript/data/data_file_1
myscript-1.0/myscript/myscript.py
myscript-1.0/myscript/test_data/
myscript-1.0/myscript/test_data/test_data_file_1
myscript-1.0/myscript.egg-info/
myscript-1.0/myscript.egg-info/PKG-INFO
myscript-1.0/myscript.egg-info/SOURCES.txt
myscript-1.0/myscript.egg-info/dependency_links.txt
myscript-1.0/myscript.egg-info/entry_points.txt
myscript-1.0/myscript.egg-info/top_level.txt
myscript-1.0/setup.cfg
myscript-1.0/setup.py
</code>```

The same holds true if you build a binary distribution with bdist.

You can find this entire example online at https://github.com/larsks/so-example-glarue.

Body:
There are many variations on this question I've found, but none seem to address my exact situation where

The Python code for the project is contained in a single file

There are required data directories that must be included with the installation

I am trying to create a pip-installable version of the following Python project, where the project consists of a single Python script myscript, plus two different data directories, data and test_data. data contains required data files that are sourced by myscript.py at runtime:

myscript
|
├── myscript
│   ├── data
│   ├── __init__.py
│   ├── myscript.py
│   └── test_data
├── LICENSE
├── README.md
└── setup.py

I've seen the recommendation to use py_modules in setup.py for similar issues, but that doesn't seem to allow for inclusion of the data directories upon install with pip, and I cannot find documentation that seems to cover this specific case.

I've also seen it recommended to just have users do a git clone of the repo instead of using pip, but it seems like a usability benefit to offer a way to pip-install with all dependencies while correctly adding the script to the PATH in an OS-dependent manner.

Body:
This looks like a pretty standard Python package. To reproduce your situation, I have the following layout:

$ find * -type f
LICENSE
myscript/myscript.py
myscript/data/data_file_1
myscript/test_data/test_data_file_1
myscript/__init__.py
README.md
setup.cfg
setup.py

To include the data directories, you can use the package_data option in your setup.cfg file (which is slowly replacing setup.py as the standard way to build Python packages).

We just need a stub setup.py:

from setuptools import setup

setup()

Everything else is in setup.cfg:

[metadata]
name = myscript
version = 1.0
description = An example for glarue
long_description = file: README.md
long_description_content_type = text/markdown
url = https://github.com/larsks/so-example-glarue
author = Lars Kellogg-Stedman
author_email = lars@oddbit.com

[options]
packages = find:

[options.package_data]
myscript = data/*, test_data/*

[options.entry_points]
console_scripts =
    myscript = myscript.myscript:main

The key part is the options.package_data` section, which, for each package, lists the glob patterns that should be included as part of the package.

If we build a source distribution from this:

$ python setup.py sdist
running sdist
...
Creating tar archive
removing 'myscript-1.0' (and everything under it)

We can see that the data files are included in the archive:

$ tar tf dist/myscript-1.0.tar.gz
myscript-1.0/
myscript-1.0/PKG-INFO
myscript-1.0/README.md
myscript-1.0/myscript/
myscript-1.0/myscript/__init__.py
myscript-1.0/myscript/data/
myscript-1.0/myscript/data/data_file_1
myscript-1.0/myscript/myscript.py
myscript-1.0/myscript/test_data/
myscript-1.0/myscript/test_data/test_data_file_1
myscript-1.0/myscript.egg-info/
myscript-1.0/myscript.egg-info/PKG-INFO
myscript-1.0/myscript.egg-info/SOURCES.txt
myscript-1.0/myscript.egg-info/dependency_links.txt
myscript-1.0/myscript.egg-info/entry_points.txt
myscript-1.0/myscript.egg-info/top_level.txt
myscript-1.0/setup.cfg
myscript-1.0/setup.py

The same holds true if you build a binary distribution with bdist.

You can find this entire example online at https://github.com/larsks/so-example-glarue.


问:
REPLACE VIEW alternative in clickhouse?
Is there REPLACE VIEW alternative in clickhouse?
If I drop view and create it again, could I get some queries failed due to downtime?

答:
create or replace?

```<code>create or replace view testv as select 1;
create or replace view testv as select 2;
select * from testv
┌─2─┐
│ 2 │
└───┘
</code>```

https://github.com/ClickHouse/ClickHouse/blob/master/docs/en/whats-new/changelog/2019.md

```<code>ClickHouse Release 19.5.2.6, 2019-04-15
   Support for CREATE OR REPLACE VIEW.
   Allow to create a view or set a new definition in a
   single statement. #4654 (Boris Granveaud)
</code>```

Title: REPLACE VIEW alternative in clickhouse?

Body:
create or replace?

create or replace view testv as select 1;
create or replace view testv as select 2;
select * from testv
┌─2─┐
│ 2 │
└───┘

https://github.com/ClickHouse/ClickHouse/blob/master/docs/en/whats-new/changelog/2019.md

ClickHouse Release 19.5.2.6, 2019-04-15
   Support for CREATE OR REPLACE VIEW.
   Allow to create a view or set a new definition in a
   single statement. #4654 (Boris Granveaud)


问:
Do a for each loop in a folder in flutter
I have a folder with csv files. For now I have to go manually and write manually each file. Is it somehow to get all the files and do a for loop? This is the current code I have and thank you so much!</p>

```<code>static List<Widget> getPlates(String file) {
    List<Widget> listWidgets = [];
    loadAsset('assets/$file.csv').then((dynamic output) {
      List<String> list = output.split('\n');
      for (int i = 1; i < list.length - 1; i++) {
        List<String> sublist = list[i].split(';');
        listWidgets.add(CardPlate(
          name: sublist[0],
          ingredients: sublist[1],
          price: sublist[2],
        ));
      }
    });

    return listWidgets;
  }

  static Future<String> loadAsset(String path) async {
    return await rootBundle.loadString(path);
  }
</code>```

答:
```<code>import 'dart:convert';

static final reg = RegExp(r'assets/\w+\.csv'); //check for all files within assets, not including subfolders

static List<Widget> getPlater() async{
  List<Widget> listWidgets = [];

  var myAssets = await rootBundle.loadString('AssetManifest.json'); //file generated by flutter which you can read up through the default bundle
  Map<String, dynamic> map = json.decode(myAssets);
  map.removeWhere((key, value) => !key.contains(reg)); //remove all keys that aren't csv files
  for(String path in map.keys){
    var output = await rootBundle.loadString(path);
    List<String> list = output.split('\n');
    for (int i = 1; i < list.length - 1; i++) {
       List<String> sublist = list[i].split(';');
       listWidgets.add(CardPlate(
         name: sublist[0],
         ingredients: sublist[1],
           price: sublist[2],
       ));
    }
  }

  return listWidgets;
}
</code>```

Body:
I have a folder with csv files. For now I have to go manually and write manually each file. Is it somehow to get all the files and do a for loop? This is the current code I have and thank you so much!

static List<Widget> getPlates(String file) {
    List<Widget> listWidgets = [];
    loadAsset('assets/$file.csv').then((dynamic output) {
      List<String> list = output.split('\n');
      for (int i = 1; i < list.length - 1; i++) {
        List<String> sublist = list[i].split(';');
        listWidgets.add(CardPlate(
          name: sublist[0],
          ingredients: sublist[1],
          price: sublist[2],
        ));
      }
    });

    return listWidgets;
  }

  static Future<String> loadAsset(String path) async {
    return await rootBundle.loadString(path);
  }


问:
How to find latest rows in my msql using a specific column value
I have a table called Access_Status containing values such as below:

I would like the table to only return the Active users which are Tom Sullivan and John Martin.

It should NOT return the Active row for Marta Jenkins since Marta is actually suspended.

What's the best approach for this?

答:
One of the way to get ACTIVE users:</p>

```<code>select A.* from Access_Status A where A.Access = 'ACTIVE'
and A.Name not in (select Name from Access_Status WHERE Access != 'ACTIVE');
</code>```

Body:
One of the way to get ACTIVE users:

select A.* from Access_Status A where A.Access = 'ACTIVE'
and A.Name not in (select Name from Access_Status WHERE Access != 'ACTIVE');


问:
Index was out of range on an ADOQuery - Very Random
I am getting Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index randomly emailed through to me on my website. I cannot reproduce this error either by force or general testing and it is somewhat confusing.

From what I can see in the stack trace, it happens randomly when opening a dataset and trying to get a value. The stack trace showed I got the error when calling this function:

```<code>function TDB.FGetLastInsertID: Integer;
const
  selSQL = 'select scope_identity() as LastID';
var
  selCursor: TDataSet;
begin
  selCursor := Cursor(selSQL); //Returns a DataSet from a TADOQuery
  try
     Result := selCursor.FieldByName('LASTID').AsInteger;
  finally
     selCursor.Close;
     selCursor.Free;
  end;
end;
</code>```

As I said, I cannot get this to reproduce the error and it seems to happen randomly on any query I run. I have tried closing the connection, setting it to inactive ect to reproduce the error but cannot.

Has anyone got any ideas?

EDIT: It seems its the close causing issues after examining the stack trace more closely:

```<code>Stack Trace: at
System.Collections.ArrayList.get_Item(Int32 index) at
Borland.Vcl.TList.Delete(Int32 Index) at Borland.Vcl.TList.Remove(Object Item) at
Borland.Vcl.TDBBufferList.FreeHGlobal(IntPtr Ptr) at
Borland.Vcl.TCustomADODataSet.FreeRecordBuffer(IntPtr& Buffer) at
Borland.Vcl.TDataSet.SetBufListSize(Int32 Value) at
Borland.Vcl.TDataSet.CloseCursor() at
Borland.Vcl.TDataSet.SetActive(Boolean Value) at Borland.Vcl.TDataSet.Close()
</code>```

EDIT2: I have put a check in the code to make sure the selCursor.Active before selCursor.Close. The stack trace suggests there is nothing to close.

答:
```<code>  selCursor := Cursor(selSQL); //Returns a DataSet from a TADOQuery
</code>```

Maybe problem is here, FieldByName is in exception handler so you have error on next line. You have to check if Cursor() is ok.

ContentLicense: CC BY-SA 3.0

Body:
I am getting Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index randomly emailed through to me on my website. I cannot reproduce this error either by force or general testing and it is somewhat confusing.

From what I can see in the stack trace, it happens randomly when opening a dataset and trying to get a value. The stack trace showed I got the error when calling this function:

function TDB.FGetLastInsertID: Integer;
const
  selSQL = 'select scope_identity() as LastID';
var
  selCursor: TDataSet;
begin
  selCursor := Cursor(selSQL); //Returns a DataSet from a TADOQuery
  try
     Result := selCursor.FieldByName('LASTID').AsInteger;
  finally
     selCursor.Close;
     selCursor.Free;
  end;
end;

As I said, I cannot get this to reproduce the error and it seems to happen randomly on any query I run. I have tried closing the connection, setting it to inactive ect to reproduce the error but cannot.

Has anyone got any ideas?

EDIT: It seems its the close causing issues after examining the stack trace more closely:

Stack Trace: at
System.Collections.ArrayList.get_Item(Int32 index) at
Borland.Vcl.TList.Delete(Int32 Index) at Borland.Vcl.TList.Remove(Object Item) at
Borland.Vcl.TDBBufferList.FreeHGlobal(IntPtr Ptr) at
Borland.Vcl.TCustomADODataSet.FreeRecordBuffer(IntPtr& Buffer) at
Borland.Vcl.TDataSet.SetBufListSize(Int32 Value) at
Borland.Vcl.TDataSet.CloseCursor() at
Borland.Vcl.TDataSet.SetActive(Boolean Value) at Borland.Vcl.TDataSet.Close()

EDIT2: I have put a check in the code to make sure the selCursor.Active before selCursor.Close. The stack trace suggests there is nothing to close.

Body:
  selCursor := Cursor(selSQL); //Returns a DataSet from a TADOQuery

Maybe problem is here, FieldByName is in exception handler so you have error on next line. You have to check if Cursor() is ok.


问:
Empty post value : CodeIgniter
While uploading the file through codeigniter, I am getting the following error:
My file upload result is:

My Controller function is below:

```<code>public function Upload files($data='')
    {
        ini_set("display_errors",1); // I added so it would help me show errors
        error_reporting(E_ALL);

        print_r($_POST);exit('I am in the tp');
        $config['upload_path']          = 'assets/images/uploads/';
        //$config['allowed_types']        = 'gif|jpg|png';
        //$config['max_size']             = 100;
        //$config['max_width']            = 1024;
        //$config['max_height']           = 768;

        $this->load->library('upload', $config);
        $this->upload->initialize($config);

        if ( ! $this->upload->do_upload('userfile'))
        {
        $error = array('error' => $this->upload->display_errors());
        print_r($error);exit('The first loop');
        $this->load->view('upload_form', $error);
                }
         else
        {

        $data = array('upload_data' => $this->upload->data());
        print_r($data);exit();
        $this->load->view('upload_success', $data);
        }
    }
</code>```

And my view file:

```<code>                                <div id="Upload_div">
                                <?php //echo $error;?>
                                <form action="<?php echo site_url() ?>/Admin/Upload_files/" method="POST" enctype="multipart/form-data">
                                  <label for="myfile">Select a file:</label>
                                  <input type="file" id="myfile" name="userfile"><br><br>
                                  <input type="submit" name="submit" value="submit">
                                </form>
                                </div>
</code>```

Can anyone help me figure out why post value is empty?
Thanks

答:
$_POST does not contain any file data.

Remove the line

```<code> print_r($_POST);exit('I am in the tp');
</code>```

And then tell us what happens.

Title: Empty post value : CodeIgniter

Body:
While uploading the file through codeigniter, I am getting the following error:
My file upload result is:

My Controller function is below:

public function Upload files($data='')
    {
        ini_set("display_errors",1); // I added so it would help me show errors
        error_reporting(E_ALL);

        print_r($_POST);exit('I am in the tp');
        $config['upload_path']          = 'assets/images/uploads/';
        //$config['allowed_types']        = 'gif|jpg|png';
        //$config['max_size']             = 100;
        //$config['max_width']            = 1024;
        //$config['max_height']           = 768;

        $this->load->library('upload', $config);
        $this->upload->initialize($config);

        if ( ! $this->upload->do_upload('userfile'))
        {
        $error = array('error' => $this->upload->display_errors());
        print_r($error);exit('The first loop');
        $this->load->view('upload_form', $error);
                }
         else
        {

        $data = array('upload_data' => $this->upload->data());
        print_r($data);exit();
        $this->load->view('upload_success', $data);
        }
    }

And my view file:

                                <?php //echo $error;?>
                                <form action="<?php echo site_url() ?>/Admin/Upload_files/" method="POST" enctype="multipart/form-data">
                                  Select a file:
                                  <input type="file" id="myfile" name="userfile">

                                  <input type="submit" name="submit" value="submit">
                                </form>

Can anyone help me figure out why post value is empty?
Thanks

Body:
$_POST does not contain any file data.

Remove the line

 print_r($_POST);exit('I am in the tp');

And then tell us what happens.


问:
AWS Beanstalk with Django: eb create complains about unknown config setting 'StaticFile'
I'm trying to deploy a django app with Elasticbeanstalk, following this setup

https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html

and this

https://www.1strategy.com/blog/2017/05/23/tutorial-django-elastic-beanstalk/

At the first attempt, in the .ebextension/django.config, I have

```<code>option_settings:
  "aws:elasticbeanstalk:application:environment":
    DJANGO_SETTINGS_MODULE: "my_django_path_name.settings"
    PYTHONPATH: "$PYTHONPATH"
  "aws:elasticbeanstalk:container:python":
    WSGIPath: "my_django_path_name/wsgi.py"
    StaticFiles: "/static/=www/static/"
</code>```

when calling eb create, it complains about

```<code>ERROR: ServiceError - Configuration validation exception: Invalid option specification (Namespace:
'aws:elasticbeanstalk:container:python', OptionName: 'StaticFiles'): Unknown configuration setting.
</code>```

So I took out the StaticFiles part, and eventually it becomes

```<code>option_settings:
  "aws:elasticbeanstalk:container:python":
    WSGIPath: "my_django_path_name/wsgi.py"
</code>```

and it STILL complains about the unknown OptionName: StaticFiles

Then I used the example in https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-container.html#python-namespaces with minor tweaking

```<code>option_settings:
  aws:elasticbeanstalk:application:environment:
    DJANGO_SETTINGS_MODULE: production.settings

  aws:elasticbeanstalk:container:python:
    WSGIPath: ebdjango.wsgi:application
    NumProcesses: 3
    NumThreads: 20
</code>```

yet it STILL complains about the same thing.

I don't know where the StaticFiles option name is being read. It doesn't exist in the .config file. Is it cached somewhere or something?

答:
There are two issues here:

As @Marcin mentioned above, eb CLI reads the files from git, so you need only to commit the changes to your local git repo before running eb deploy. No need to push to your remote repo.

As it seems that you are using the new Amazon Linux 2 platform in EB, serving static files is removed from its features. So, you have to serve your static files externally through S3 bucket for an instance.

Sources:

Amazon Linux 2 platforms limitations

Amazon Linux 2 platforms are missing some features compared to Amazon Linux AMI platforms (preceding Amazon Linux 2) : Serving static files and Custom platforms

https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/using-features.migration-al.html

staticfiles option is not supported

Configuring static files using the aws:elasticbeanstalk:container:python:staticfiles namespace is only supported on Amazon Linux AMI Python platform versions.

https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-container.html#python-namespaces

Body:
I'm trying to deploy a django app with Elasticbeanstalk, following this setup

https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html

and this

https://www.1strategy.com/blog/2017/05/23/tutorial-django-elastic-beanstalk/

At the first attempt, in the .ebextension/django.config, I have

option_settings:
  "aws:elasticbeanstalk:application:environment":
    DJANGO_SETTINGS_MODULE: "my_django_path_name.settings"
    PYTHONPATH: "$PYTHONPATH"
  "aws:elasticbeanstalk:container:python":
    WSGIPath: "my_django_path_name/wsgi.py"
    StaticFiles: "/static/=www/static/"

when calling eb create, it complains about

ERROR: ServiceError - Configuration validation exception: Invalid option specification (Namespace:
'aws:elasticbeanstalk:container:python', OptionName: 'StaticFiles'): Unknown configuration setting.

So I took out the StaticFiles part, and eventually it becomes

option_settings:
  "aws:elasticbeanstalk:container:python":
    WSGIPath: "my_django_path_name/wsgi.py"

and it STILL complains about the unknown OptionName: StaticFiles

Then I used the example in https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-container.html#python-namespaces with minor tweaking

option_settings:
  aws:elasticbeanstalk:application:environment:
    DJANGO_SETTINGS_MODULE: production.settings

  aws:elasticbeanstalk:container:python:
    WSGIPath: ebdjango.wsgi:application
    NumProcesses: 3
    NumThreads: 20

yet it STILL complains about the same thing.

I don't know where the StaticFiles option name is being read. It doesn't exist in the .config file. Is it cached somewhere or something?


问:
Image slider with multiple images needs movement on mouse flick
I am having this slider showing multiple images using HTML and CSS. I am trying to accomplish following:
1. Get rid of the scroll bar
2. Enable swipe using mouse flick (should as well work on mobile)
3. Make the image link

.slider{
 overflow: auto;
 white-space:nowrap;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="slider">
<img src="http://letsbefoodie.com/imagesforslider/manchow_recipe_slider.png" alt="Manchow Soup Recipe" />
<img src="http://letsbefoodie.com/imagesforslider/carrot_halwa_slider.png" alt="Microwave Carrot Halwa Recipe" />
<img src="http://letsbefoodie.com/imagesforslider/manchow_recipe_slider.png" alt="Manchow Soup Recipe" />
<img src="http://letsbefoodie.com/imagesforslider/carrot_halwa_slider.png" alt="Microwave Carrot Halwa Recipe" />
<img src="http://letsbefoodie.com/imagesforslider/manchow_recipe_slider.png" alt="Manchow Soup Recipe" />
<img src="http://letsbefoodie.com/imagesforslider/carrot_halwa_slider.png" alt="Microwave Carrot Halwa Recipe" />
<img src="http://letsbefoodie.com/imagesforslider/manchow_recipe_slider.png" alt="Manchow Soup Recipe" />
<img src="http://letsbefoodie.com/imagesforslider/carrot_halwa_slider.png" alt="Microwave Carrot Halwa Recipe" />
</div></code>```

答:
Try using slick

Try using plugin like : https://kenwheeler.github.io/slick/
You can add what ever you want in the slider and you have a lot of options

It's very simple! I have use it in lot of my project at work and it fonction perfectly!


问:
How to show dynamic content in @angular/google-maps infoWindow
Specifically, how do you show information related to the marker in the respective infoWindow?

By following the example on the repo here, the same information is opened for every marker. With the old angular google maps you could easily just insert the info window inside the marker with whatever data you wanted.

I saw a few examples of setting the content with {{ contentHere }} in the template, but that only allows for strings. I need to use all the angular template stuff like usual.

Let's say our template looks something like the repo example:

```<code><google-map height="400px"
        width="750px"
        [center]="center"
        [zoom]="zoom">
  <map-marker #marker
          *ngFor="let place of places"
          [position]="{ lat: place.latitude, lng: place.longitude }"
          [options]="markerOptions"
          (mapClick)="openInfoWindow(marker)">

      <map-info-window>
        <-- this is what i'm concerned with -->
        {{ place.description }}
      </map-info-window>
  </map-marker>
</google-map>
</code>```

And then we add viewchild like the repo example and open it in the same way:

```<code>@ViewChild(MapInfoWindow, {static: false}) infoWindow: MapInfoWindow;

openInfoWindow(marker: MapMarker) {
  this.infoWindow.open(marker);
}
</code>```

Although this does open the correct marker and the marker will reflect dynamic info, this will show the same content / place.description for every info window, which isn't really surprising since a single ViewChild is being used. I've come up with all kinds of convoluted ways to do this and had a look through the source code but there doesn't seem to be an obvious and/or built in solution for displaying content in the window that is related to what is being used by the marker. It just seems weird to not have that as a basic example.

How would any of you go about doing this?

答:
Use ViewChildren, use index in the for loop in the template, pass in the index when marker is clicked, loop through all ViewChildren using an index inside of a forEach (for loop with index will not open the window for some reason), then if the index of the loop matches the index passed in, open that window. It seems like there would be a better way than this but it's all I could come up with after trying many things:

In component:

```<code>@ViewChildren(MapInfoWindow) infoWindowsView: QueryList<MapInfoWindow>;

openInfoWindow(marker: MapMarker, windowIndex: number) {
  /// stores the current index in forEach
  let curIdx = 0;
  this.infoWindowsView.forEach((window: MapInfoWindow) => {
    if (windowIndex === curIdx) {
      window.open(marker);
      curIdx++;
    } else {
      curIdx++;
    }
  });
}
</code>```

In template:

```<code><google-map height="400px"
    width="750px"
    [center]="center"
    [zoom]="zoom">
  <map-marker #marker
      *ngFor="let place of places; let i = index" <-- added index -->
      [position]="{ lat: place.latitude, lng: place.longitude }"
      [options]="markerOptions"
      (mapClick)="openInfoWindow(marker, i)"> <-- pass in index -->

      <map-info-window>
        {{ place.description }}
      </map-info-window>
  </map-marker>
</google-map>
</code>```

This will open the info window with its respective marker.

Body:
Specifically, how do you show information related to the marker in the respective infoWindow?

By following the example on the repo here, the same information is opened for every marker. With the old angular google maps you could easily just insert the info window inside the marker with whatever data you wanted.

I saw a few examples of setting the content with {{ contentHere }} in the template, but that only allows for strings. I need to use all the angular template stuff like usual.

Let's say our template looks something like the repo example:

<google-map height="400px"
        width="750px"
        [center]="center"
        [zoom]="zoom">
  <map-marker #marker
          *ngFor="let place of places"
          [position]="{ lat: place.latitude, lng: place.longitude }"
          [options]="markerOptions"
          (mapClick)="openInfoWindow(marker)">

      <map-info-window>
        <-- this is what i'm concerned with -->
        {{ place.description }}
      </map-info-window>
  </map-marker>
</google-map>

And then we add viewchild like the repo example and open it in the same way:

@ViewChild(MapInfoWindow, {static: false}) infoWindow: MapInfoWindow;

openInfoWindow(marker: MapMarker) {
  this.infoWindow.open(marker);
}

Although this does open the correct marker and the marker will reflect dynamic info, this will show the same content / place.description for every info window, which isn't really surprising since a single ViewChild is being used. I've come up with all kinds of convoluted ways to do this and had a look through the source code but there doesn't seem to be an obvious and/or built in solution for displaying content in the window that is related to what is being used by the marker. It just seems weird to not have that as a basic example.

How would any of you go about doing this?

Body:
Use ViewChildren, use index in the for loop in the template, pass in the index when marker is clicked, loop through all ViewChildren using an index inside of a forEach (for loop with index will not open the window for some reason), then if the index of the loop matches the index passed in, open that window. It seems like there would be a better way than this but it's all I could come up with after trying many things:

In component:

@ViewChildren(MapInfoWindow) infoWindowsView: QueryList<MapInfoWindow>;

openInfoWindow(marker: MapMarker, windowIndex: number) {
  /// stores the current index in forEach
  let curIdx = 0;
  this.infoWindowsView.forEach((window: MapInfoWindow) => {
    if (windowIndex === curIdx) {
      window.open(marker);
      curIdx++;
    } else {
      curIdx++;
    }
  });
}

In template:

<google-map height="400px"
    width="750px"
    [center]="center"
    [zoom]="zoom">
  <map-marker #marker
      *ngFor="let place of places; let i = index" <-- added index -->
      [position]="{ lat: place.latitude, lng: place.longitude }"
      [options]="markerOptions"
      (mapClick)="openInfoWindow(marker, i)"> <-- pass in index -->

      <map-info-window>
        {{ place.description }}
      </map-info-window>
  </map-marker>
</google-map>

This will open the info window with its respective marker.


问:
How to call function in map loop (react native)?
This is my code. I am not sure what error exists.

When I click the image button, it calls proper function exactly.
If I click the first button, it calls toggleBooks() function correctly.
Then in that function, I want to use vidMute state value.

So I tried console.log('Video toggle', this.state.vidMute); then it gives me an error like the following image.

But if I print console.log('Video toggle'), then it works well.
How to use state value in that function?

```<code>export default class Video extends Component {
    constructor(props) {
        super(props)
        this.state = {
            vidMute: false,
            audioShow: false,
            callShow: false,
            btn: [
                { func: this.toggleAudio, url: magic, de_url: de_magic },
                { func: this.endCall, url: endcall, de_url: de_endcall },
                { func: this.toggleBooks, url: camerarotate, de_url: de_camerarotate },
            ],
        };
    this.toggleAudio = this.toggleAudio.bind(this)
    this.endCall = this.endCall.bind(this)
    this.toggleBooks = this.toggleBooks.bind(this)
    }

    toggleBooks() {
        console.log('Video toggle', this.state.vidMute);
    }
    endCall() {
        console.log('Call toggle', this.state.audioShow);
    }
    toggleAudio() {
        console.log('Audio toggle', this.state.callShow);
    }

    render() {
        return (
            <View>
                {
                    this.state.btn.map((item, index) => (
                        <TouchableOpacity key={index} style={styles.iconStyle} activeOpacity={0.4} onPress={item.func}>
                            <Image source={this.state.lockState ? item.de_url : item.url} style={{ width: 70, height: 70 }} />
                        </TouchableOpacity>
                    ))
                }
            </View>
        )
    }

}
</code>```

答:
this refers to the context of your function and not the context of your component. You can try to bind your method like this :

this.myMethod = this.myMethod.bind(this);

in your constructor.

Or use the fat arrow pattern (Highly recommanded) which automatically includes the binding to your component's context.

Here is a binding example on stackblitz

Here is the code :

```<code>import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';

class App extends Component {
  constructor() {
    super();
    this.state = {
      name: 'React',
      items:[
        {name:"item 1", func: () => this.test()},
        {name:"item 2", func: () => this.test2()}
      ]
    };

    this.test = this.test.bind(this);
  }

  test() {
    console.log('Hi', this.state.name);
  }

  test2() {
    console.log('Hello', this.state.name); // Note this is not binded
  }

  render() {
    return (
      <div>
        <Hello name={this.state.name} />
        <p onClick={this.test}>
          Start editing to see some magic happen :)
        </p>

        <div>
        {
          this.state.items.map(item => <div onClick={() => item.func()}>{item.name}</div>)
        }
        </div>
      </div>
    );
  }
}

render(<App />, document.getElementById('root'));
</code>```

Body:
This is my code. I am not sure what error exists.

When I click the image button, it calls proper function exactly.
If I click the first button, it calls toggleBooks() function correctly.
Then in that function, I want to use vidMute state value.

So I tried console.log('Video toggle', this.state.vidMute); then it gives me an error like the following image.

But if I print console.log('Video toggle'), then it works well.
How to use state value in that function?

export default class Video extends Component {
    constructor(props) {
        super(props)
        this.state = {
            vidMute: false,
            audioShow: false,
            callShow: false,
            btn: [
                { func: this.toggleAudio, url: magic, de_url: de_magic },
                { func: this.endCall, url: endcall, de_url: de_endcall },
                { func: this.toggleBooks, url: camerarotate, de_url: de_camerarotate },
            ],
        };
    this.toggleAudio = this.toggleAudio.bind(this)
    this.endCall = this.endCall.bind(this)
    this.toggleBooks = this.toggleBooks.bind(this)
    }

    toggleBooks() {
        console.log('Video toggle', this.state.vidMute);
    }
    endCall() {
        console.log('Call toggle', this.state.audioShow);
    }
    toggleAudio() {
        console.log('Audio toggle', this.state.callShow);
    }

    render() {
        return (
            <View>
                {
                    this.state.btn.map((item, index) => (
                        <TouchableOpacity key={index} style={styles.iconStyle} activeOpacity={0.4} onPress={item.func}>
                            <Image source={this.state.lockState ? item.de_url : item.url} style={{ width: 70, height: 70 }} />
                        </TouchableOpacity>
                    ))
                }
            </View>
        )
    }

}

Body:
this refers to the context of your function and not the context of your component. You can try to bind your method like this :

this.myMethod = this.myMethod.bind(this);

in your constructor.

Or use the fat arrow pattern (Highly recommanded) which automatically includes the binding to your component's context.

Here is a binding example on stackblitz

Here is the code :

import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';

class App extends Component {
  constructor() {
    super();
    this.state = {
      name: 'React',
      items:[
        {name:"item 1", func: () => this.test()},
        {name:"item 2", func: () => this.test2()}
      ]
    };

    this.test = this.test.bind(this);
  }

  test() {
    console.log('Hi', this.state.name);
  }

  test2() {
    console.log('Hello', this.state.name); // Note this is not binded
  }

  render() {
    return (
      <div>
        <Hello name={this.state.name} />
        <p onClick={this.test}>
          Start editing to see some magic happen :)
        </p>

        <div>
        {
          this.state.items.map(item => <div onClick={() => item.func()}>{item.name}</div>)
        }
        </div>
      </div>
    );
  }
}

render(<App />, document.getElementById('root'));


问:
Longest path in ordered graph pseudocode
I try to create an algorithm to find the longest path in an ordered graph.
The properties of the ordered graph are:

Each edge goes from a node with lower index to a node with a higher index. That is, every directed edge has the form (v_i, v_j) with i < j.

Each node except v_n has at least one edge leaving it. That is, for every node v_i, there is at least one edge of the form (v_i, v_j).

My first attempt is the following:

```<code>set w = v1 and L = 0
While there is edge that leaves from w
    Choose the edge (w, vj) with j as small as possible
    set w = vj and L = L + 1
return L
</code>```

I cant understand why this algorithm is wrong for some cases. Can you give me an example?

答:
My intuition tells me that just choosing the smallest j doesn't mean that somewhere else down the line the j will be continue to be the smallest.

Imagine you have a graph 1-> 3 and 1 -> 5, but 3 -> 9 and 5 -> 7 -> 9, where 9 is the last node. Your algorithm will go 1 -> 3 -> 9 which is shorter than 1 -> 5 -> 7 -> 9.

In fact, I don't think you can really just "pick" a branch and continue to follow it to the end and be correct in any case: you must check the other branches.

Recursive Approach

Here is an approach that uses a simple recursive algorithm where at each branch you calculate the length of the path and then at nodes where there are multiple branches you just return the longest.

Simple pseudocode example (in the style of Python)

class node:
    def longest_path(self):
        if len(self.children) == 0: # No children in this node
            return 1
        child_lengths = []
        for child in self.children:
            child_lengths.append(child.longest_path())
        return max(child_lengths) + 1
```

Body:
I try to create an algorithm to find the longest path in an ordered graph.
The properties of the ordered graph are:

Each edge goes from a node with lower index to a node with a higher index. That is, every directed edge has the form (v_i, v_j) with i < j.

Each node except v_n has at least one edge leaving it. That is, for every node v_i, there is at least one edge of the form (v_i, v_j).

My first attempt is the following:

set w = v1 and L = 0
While there is edge that leaves from w
    Choose the edge (w, vj) with j as small as possible
    set w = vj and L = L + 1
return L

I cant understand why this algorithm is wrong for some cases. Can you give me an example?


问:
How to model REST URL for which there is no equivalent HTTP method?
I have customers and I want to activate and cancel their plans. I am trying to be as RESTful as possible.

Should the action to perform 'active' or 'suspend' be part of URI ?

1) POST customers/{customerId}/activatePlan/{planName}
2) POST customers/{customerId}/suspendPlan/{planName}

My problem is that both activate and cancel are verbs or actions. They do not have any equivalent HTTP action ( GET, POST, PATCH etc.)

Are my URL's restful ? if not, how to make them REST ful.

答:
Are my URL's restful ?

All URI are RESTful -- REST doesn't care what spelling conventions you use for your resource identifiers.

Notice, please, that both of the following URI work exactly as you would expect them to:

https://www.merriam-webster.com/dictionary/activate

https://www.merriam-webster.com/dictionary/cancel

My problem is that both activate and cancel are verbs or actions. They do not have any equivalent HTTP action ( GET, POST, PATCH etc.)

There are a couple of different answers.  Perhaps the easiest is to think about how you would design a web site that allowed you to activate and cancel plans.  You would probably have a web page for this customers enrollment, and on that page might be a link with some hint, like "cancel".  Clicking the link would load a new web page, with a form on it, including a bunch of fields for the customer to fill in.  When the customer submits the form, the browser looks at the form, and its meta data, and figures out what request to send to the server.

A "REST API" isn't about putting your domain model on the web - it's about putting your interaction model on the web.  We create a collection of documents (resources) that describe the domain, and we get useful work done by moving those documents around the network.  See Jim Webber 2011.

Because we are working in the language of documents, REST interfaces are usually based on one of the following ideas

Here is a document; make local edits to your copy of the document, and send it back to the server (GET, PUT, PATCH, DELETE are the primary method tokens you see in this style)

Here is a form; fill in the details and submit it (GET and POST are the method tokens you see in these cases)

If you are unhappy with the use of POST, it may help to review Fielding 2009

POST serves many useful purposes in HTTP, including the general purpose of “this action isn’t worth standardizing.”


问:
Checkboxes on Rails
What's the correct way of making checkboxes that are related to a certain question in Ruby on Rails? At the moment I have:

```<code><div class="form_row">
    <label for="features[]">Features:</label>
    <br><%= check_box_tag 'features[]', 'scenarios' %> Scenarios
    <br><%= check_box_tag 'features[]', 'role_profiles' %> Role profiles
    <br><%= check_box_tag 'features[]', 'private_messages' %> Private messages
    <br><%= check_box_tag 'features[]', 'chatrooms' %> Chatrooms
    <br><%= check_box_tag 'features[]', 'forums' %> Forums
    <br><%= check_box_tag 'features[]', 'news' %> News
    <br><%= check_box_tag 'features[]', 'polls' %> Polls
</div>
</code>```

I also want to be able to automatically check the previously selected items (if this form was re-loaded). How would I load the params into the default value of these?

答:
You are looking at the following:

```<code><div class="form_row">
    <label for="features[]">Features:</label>
    <% [ 'scenarios', 'role_profiles', ... , 'polls' ].each do |feature| %>
      <br><%= check_box_tag 'features[]', feature,
              (params[:features] || {}).include?(feature) %>
      <%= feature.humanize %>
    <% end %>
</div>
</code>```

Although if you already have a Feature model, with a features table and a has_many :features relationship, you probably want this:

```<code><div class="form_row">
    <label for="feature_ids[]">Features:</label>
    <% for feature in Feature.find(:all) do %>
      <br><%= check_box_tag 'feature_ids[]', feature.id,
              @model.feature_ids.include?(feature.id) %>
      <%= feature.name.humanize %>
    <% end %>
</div>
</code>```

OwnerDisplayName: alamodey

ContentLicense: CC BY-SA 2.5

Title: Checkboxes on Rails

Body:
What's the correct way of making checkboxes that are related to a certain question in Ruby on Rails? At the moment I have:

    Features:

<%= check_box_tag 'features[]', 'scenarios' %> Scenarios

<%= check_box_tag 'features[]', 'role_profiles' %> Role profiles

<%= check_box_tag 'features[]', 'private_messages' %> Private messages

<%= check_box_tag 'features[]', 'chatrooms' %> Chatrooms

<%= check_box_tag 'features[]', 'forums' %> Forums

<%= check_box_tag 'features[]', 'news' %> News

<%= check_box_tag 'features[]', 'polls' %> Polls

I also want to be able to automatically check the previously selected items (if this form was re-loaded). How would I load the params into the default value of these?

Body:
You are looking at the following:

<div class="form_row">
    <label for="features[]">Features:</label>
    <% [ 'scenarios', 'role_profiles', ... , 'polls' ].each do |feature| %>
      <br><%= check_box_tag 'features[]', feature,
              (params[:features] || {}).include?(feature) %>
      <%= feature.humanize %>
    <% end %>
</div>

Although if you already have a Feature model, with a features table and a has_many :features relationship, you probably want this:

<div class="form_row">
    <label for="feature_ids[]">Features:</label>
    <% for feature in Feature.find(:all) do %>
      <br><%= check_box_tag 'feature_ids[]', feature.id,
              @model.feature_ids.include?(feature.id) %>
      <%= feature.name.humanize %>
    <% end %>
</div>

OwnerDisplayName: Vlad Romascanu

LastEditorDisplayName: Vlad Romascanu


问:
How to fix Parameter specified as non-null is null error in Android
In my application i should implement MultiDex dependency, and i added this in gradle.build file and write some codes into application class!

But after run application, show me force close error and not started application!

gradle.build :

```<code>implementation 'com.android.support:multidex:1.0.3'
implementation 'com.android.support:multidex-instrumentation:1.0.3'
</code>```

BaseActivity class :

```<code>abstract class BaseActivity : AppCompatActivity() {
    /**
     * Set your page layout when initialize `layoutId`, Ex. R.layout.activity_main
     */
    abstract var layoutId: Int

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(layoutId)
    }

    /**
     * With below method, we can set custom font to all of activities
     */
    override fun attachBaseContext(newBase: Context) {
        super.attachBaseContext(ViewPumpContextWrapper.wrap(newBase))
    }
}
</code>```

Application class :

```<code>import android.app.Activity
import android.app.Application
import android.content.Context
import android.os.Bundle
import androidx.multidex.MultiDex
import com.adjust.sdk.Adjust
import com.adjust.sdk.AdjustConfig
import com.adjust.sdk.LogLevel
import com.app.android.R
import com.app.android.utils.ADJUST_APP_TOKEN
import com.crashlytics.android.Crashlytics
import com.crashlytics.android.answers.Answers
import com.crashlytics.android.answers.ContentViewEvent
import com.google.android.gms.analytics.GoogleAnalytics
import com.google.android.gms.analytics.HitBuilders
import com.google.android.gms.analytics.Tracker
import io.fabric.sdk.android.Fabric
import io.github.inflationx.calligraphy3.CalligraphyConfig
import io.github.inflationx.calligraphy3.CalligraphyInterceptor
import io.github.inflationx.viewpump.ViewPump

class App : Application() {

    private var adjustEnvironment: String = ""
    private lateinit var adjustConfig: AdjustConfig
    private lateinit var analytics: GoogleAnalytics
    private lateinit var tracker: Tracker

    override fun onCreate() {
        super.onCreate()
        //Calligraphy
        ViewPump.init(
            ViewPump.builder().addInterceptor(
                CalligraphyInterceptor(
                    CalligraphyConfig.Builder().setDefaultFontPath("fonts/IranSans.ttf")
                        .setFontAttrId(R.attr.fontPath)
                        .build()
                )
            ).build()
        )
        //GoodPres
        GoodPrefs.init(applicationContext)
        //Fabric initialize kits
        val fabric = Fabric.Builder(this)
            .kits(Answers())
//            .kits(Crashlytics())
            .debuggable(true)
            .build()
        Fabric.with(fabric)
        //Adjust
        adjustEnvironment = AdjustConfig.ENVIRONMENT_PRODUCTION
        adjustConfig = AdjustConfig(this, ADJUST_APP_TOKEN, adjustEnvironment, true)
        adjustConfig.setSendInBackground(true)
        adjustConfig.setLogLevel(LogLevel.SUPRESS)
        Adjust.onCreate(adjustConfig)
        registerActivityLifecycleCallbacks(AdjustLifecycleCallbacks())
        //Google Analytics
        analytics = GoogleAnalytics.getInstance(this)
    }

    override fun attachBaseContext(base: Context) {
        super.attachBaseContext(base)
        MultiDex.install(this)
    }

    //Adjust lifecycle method
    private class AdjustLifecycleCallbacks : Application.ActivityLifecycleCallbacks {
        override fun onActivityResumed(activity: Activity) {
            Adjust.onResume()
        }

        override fun onActivityPaused(activity: Activity) {
            Adjust.onPause()
        }

        override fun onActivityStopped(activity: Activity) {}

        override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {}

        override fun onActivityDestroyed(activity: Activity) {}

        override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle) {}

        override fun onActivityStarted(activity: Activity) {}
    }

    @Synchronized
    fun getDefaultTracker(): Tracker {
        if (tracker == null) {
            tracker = analytics.newTracker(R.xml.global_tracker)
        }
        return tracker
    }

    fun anserTracker(name: String, type: String, id: String) {
        Answers.getInstance().logContentView(
            ContentViewEvent()
                .putContentName(name)
                .putContentType(type)
                .putContentId(id)
        )
    }

    fun googleTracker(category: String, action: String, label: String) {
        val tracker: Tracker = getDefaultTracker()
        tracker.send(
            HitBuilders.EventBuilder()
                .setCategory(category)
                .setAction(action)
                .setLabel(label)
                .build()
        )
    }
</code>```

Error message :

```<code>Caused by: java.lang.IllegalArgumentException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkParameterIsNotNull, parameter savedInstanceState
    at com.app.android.ui.App$AdjustLifecycleCallbacks.onActivityCreated(Unknown Source:7)
    at android.app.Application.dispatchActivityCreated(Application.java:221)
    at android.app.Activity.onCreate(Activity.java:1071)
    at androidx.activity.ComponentActivity.onCreate(ComponentActivity.java:147)
    at androidx.fragment.app.FragmentActivity.onCreate(FragmentActivity.java:317)
    at androidx.appcompat.app.AppCompatActivity.onCreate(AppCompatActivity.java:106)
    at com.app.android.ui.base.BaseActivity.onCreate(BaseActivity.kt:16)
</code>```

Show me error for this line : import androidx.multidex.MultiDex

How can i fix this issue?

答:
```<code>override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle)
</code>```

savedInstanceState parameter here should be nullable (Bundle?), also

Body:
In my application i should implement MultiDex dependency, and i added this in gradle.build file and write some codes into application class!

But after run application, show me force close error and not started application!

gradle.build :

implementation 'com.android.support:multidex:1.0.3'
implementation 'com.android.support:multidex-instrumentation:1.0.3'

BaseActivity class :

abstract class BaseActivity : AppCompatActivity() {
    /**
     * Set your page layout when initialize `layoutId`, Ex. R.layout.activity_main
     */
    abstract var layoutId: Int

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(layoutId)
    }

    /**
     * With below method, we can set custom font to all of activities
     */
    override fun attachBaseContext(newBase: Context) {
        super.attachBaseContext(ViewPumpContextWrapper.wrap(newBase))
    }
}

Application class :

import android.app.Activity
import android.app.Application
import android.content.Context
import android.os.Bundle
import androidx.multidex.MultiDex
import com.adjust.sdk.Adjust
import com.adjust.sdk.AdjustConfig
import com.adjust.sdk.LogLevel
import com.app.android.R
import com.app.android.utils.ADJUST_APP_TOKEN
import com.crashlytics.android.Crashlytics
import com.crashlytics.android.answers.Answers
import com.crashlytics.android.answers.ContentViewEvent
import com.google.android.gms.analytics.GoogleAnalytics
import com.google.android.gms.analytics.HitBuilders
import com.google.android.gms.analytics.Tracker
import io.fabric.sdk.android.Fabric
import io.github.inflationx.calligraphy3.CalligraphyConfig
import io.github.inflationx.calligraphy3.CalligraphyInterceptor
import io.github.inflationx.viewpump.ViewPump

class App : Application() {

    private var adjustEnvironment: String = ""
    private lateinit var adjustConfig: AdjustConfig
    private lateinit var analytics: GoogleAnalytics
    private lateinit var tracker: Tracker

    override fun onCreate() {
        super.onCreate()
        //Calligraphy
        ViewPump.init(
            ViewPump.builder().addInterceptor(
                CalligraphyInterceptor(
                    CalligraphyConfig.Builder().setDefaultFontPath("fonts/IranSans.ttf")
                        .setFontAttrId(R.attr.fontPath)
                        .build()
                )
            ).build()
        )
        //GoodPres
        GoodPrefs.init(applicationContext)
        //Fabric initialize kits
        val fabric = Fabric.Builder(this)
            .kits(Answers())
//            .kits(Crashlytics())
            .debuggable(true)
            .build()
        Fabric.with(fabric)
        //Adjust
        adjustEnvironment = AdjustConfig.ENVIRONMENT_PRODUCTION
        adjustConfig = AdjustConfig(this, ADJUST_APP_TOKEN, adjustEnvironment, true)
        adjustConfig.setSendInBackground(true)
        adjustConfig.setLogLevel(LogLevel.SUPRESS)
        Adjust.onCreate(adjustConfig)
        registerActivityLifecycleCallbacks(AdjustLifecycleCallbacks())
        //Google Analytics
        analytics = GoogleAnalytics.getInstance(this)
    }

    override fun attachBaseContext(base: Context) {
        super.attachBaseContext(base)
        MultiDex.install(this)
    }

    //Adjust lifecycle method
    private class AdjustLifecycleCallbacks : Application.ActivityLifecycleCallbacks {
        override fun onActivityResumed(activity: Activity) {
            Adjust.onResume()
        }

        override fun onActivityPaused(activity: Activity) {
            Adjust.onPause()
        }

        override fun onActivityStopped(activity: Activity) {}

        override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {}

        override fun onActivityDestroyed(activity: Activity) {}

        override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle) {}

        override fun onActivityStarted(activity: Activity) {}
    }

    @Synchronized
    fun getDefaultTracker(): Tracker {
        if (tracker == null) {
            tracker = analytics.newTracker(R.xml.global_tracker)
        }
        return tracker
    }

    fun anserTracker(name: String, type: String, id: String) {
        Answers.getInstance().logContentView(
            ContentViewEvent()
                .putContentName(name)
                .putContentType(type)
                .putContentId(id)
        )
    }

    fun googleTracker(category: String, action: String, label: String) {
        val tracker: Tracker = getDefaultTracker()
        tracker.send(
            HitBuilders.EventBuilder()
                .setCategory(category)
                .setAction(action)
                .setLabel(label)
                .build()
        )
    }

Error message :

Caused by: java.lang.IllegalArgumentException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkParameterIsNotNull, parameter savedInstanceState
    at com.app.android.ui.App$AdjustLifecycleCallbacks.onActivityCreated(Unknown Source:7)
    at android.app.Application.dispatchActivityCreated(Application.java:221)
    at android.app.Activity.onCreate(Activity.java:1071)
    at androidx.activity.ComponentActivity.onCreate(ComponentActivity.java:147)
    at androidx.fragment.app.FragmentActivity.onCreate(FragmentActivity.java:317)
    at androidx.appcompat.app.AppCompatActivity.onCreate(AppCompatActivity.java:106)
    at com.app.android.ui.base.BaseActivity.onCreate(BaseActivity.kt:16)

Show me error for this line : import androidx.multidex.MultiDex

How can i fix this issue?

Body:
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle)

savedInstanceState parameter here should be nullable (Bundle?), also


问:
DynamoDB GSI based queries using Amplify Libraries
For Android applications, I used to use the AppSync client to query data from DynamoDB when I use GSIs. Nowadays, I am trying to use Amplify Libraries to utilize the DataStore features. After reading the documentation and code, I realized that the Amplify Libraries don't support these kinds of queries, unless I'm mistaken. The only way I have found so far is using list and applying a filter on the results but that is not ideal considering the Read Capacity. Does anyone find a document about this issue? are there any useful plugins can be used in this case?

For clarification please refer to the following schema from AWS doc:

```<code>type Item @model
  @key(fields: ["orderId", "status", "createdAt"])
  @key(name: "ByStatus", fields: ["status", "createdAt"], queryField: "itemsByStatus") {
  orderId: ID!
  status: Status!
  createdAt: AWSDateTime!
  name: String!
}

enum Status {
  DELIVERED
  IN_TRANSIT
  PENDING
  UNKNOWN
}
</code>```

With AppSync you can query the data based on ByStatus GSI this way:

appSyncClient.query(itemsByStatusQuery.builder().build())
```

Now, I am using Amplify API category. It seems to me that I can only use getItem or listItems queries.

I wonder if there is a way to do the same with Amplify libraries.

答:
As far as documentation goes, you can find information on querying the DataStore here. If you're also using the API category, you can find query documentation here.

One important thing to note is that GSIs are created/used based on your GraphQL model. The connection directive will generate the GSIs for you based on the relationship between the models in your schema. After doing that, you can use the generated model to issue your queries without having to explicitly specify the GSI.

Happy to help you out if you have further questions on this.

Body:
For Android applications, I used to use the AppSync client to query data from DynamoDB when I use GSIs. Nowadays, I am trying to use Amplify Libraries to utilize the DataStore features. After reading the documentation and code, I realized that the Amplify Libraries don't support these kinds of queries, unless I'm mistaken. The only way I have found so far is using list and applying a filter on the results but that is not ideal considering the Read Capacity. Does anyone find a document about this issue? are there any useful plugins can be used in this case?

For clarification please refer to the following schema from AWS doc:

type Item @model
  @key(fields: ["orderId", "status", "createdAt"])
  @key(name: "ByStatus", fields: ["status", "createdAt"], queryField: "itemsByStatus") {
  orderId: ID!
  status: Status!
  createdAt: AWSDateTime!
  name: String!
}

enum Status {
  DELIVERED
  IN_TRANSIT
  PENDING
  UNKNOWN
}

With AppSync you can query the data based on ByStatus GSI this way:

appSyncClient.query(itemsByStatusQuery.builder().build())

Now, I am using Amplify API category. It seems to me that I can only use getItem or listItems queries.

I wonder if there is a way to do the same with Amplify libraries.


问:
Allowing overflow:visible only for input or select fields
I'm having this issue with a Lightning Web Component in Salesforce, but I think the root of it is universal.

I have a container div which houses row divs showing select/combobox fields, which I need to have hang over the top/bottom of the container when selected. I can get this by setting overflow:visible on the container.

I can add more rows and the container expands normally:

But what I want to do is add y-axis scroll bars when the container reaches a max-height. By definition, overflow:visible doesn't add scroll bars and the contents flow out the bottom of the container

Any ideas would be appreciated.

答: Change your overflow to overflow: auto;

Body: Change your overflow to overflow: auto;


问:
How to use a time interval for each iteration of a for loop?
I want to show each word of a string of text in 60 seconds intervals on screen and came up with something like this:

```<code>let text = "Aliquam bibendum nulla et ligula vehicula semper. Nulla id posuere lorem, ac dignissim nunc. Quisque leo lorem, fringilla non ante ac, lobortis auctor leo. Fusce sit amet nibh vitae augue convallis iaculis eget ac erat.";

let mainId = document.getElementById("main");

function showWords() {
  // Print words to the screen one at a time.

  let textArray = text.split(" ");
  for(let i = 0; i < poemArray.length; i++) {
    mainId.textContent = poemArray[i];
  }
}
</code>```

I know that I should use a setInterval() method here, I'm not just sure how I should use it. I have tried to put the whole for loop as the function part of it and even tried to put the code inside the for loop as the function part and nothing works.

答:
You can use async/await to trigger a configurable delay:</p>

```<code>const delay = ms => new Promise(res => setTimeout(res, ms));

function updateText = async () => {
  var current = 0;
  var count = textArray.length;
  while (current < count) {
    mainId.textContent = poemArray[i];
    current++;
    await delay(60000);
  }
};
</code>```

Body:
I want to show each word of a string of text in 60 seconds intervals on screen and came up with something like this:

let text = "Aliquam bibendum nulla et ligula vehicula semper. Nulla id posuere lorem, ac dignissim nunc. Quisque leo lorem, fringilla non ante ac, lobortis auctor leo. Fusce sit amet nibh vitae augue convallis iaculis eget ac erat.";

let mainId = document.getElementById("main");

function showWords() {
  // Print words to the screen one at a time.

  let textArray = text.split(" ");
  for(let i = 0; i < poemArray.length; i++) {
    mainId.textContent = poemArray[i];
  }
}

I know that I should use a setInterval() method here, I'm not just sure how I should use it. I have tried to put the whole for loop as the function part of it and even tried to put the code inside the for loop as the function part and nothing works.

Body:
You can use async/await to trigger a configurable delay:

const delay = ms => new Promise(res => setTimeout(res, ms));

function updateText = async () => {
  var current = 0;
  var count = textArray.length;
  while (current < count) {
    mainId.textContent = poemArray[i];
    current++;
    await delay(60000);
  }
};


问:
SUMPRODUCT function with IF logic
I am attempting to multiple two arrays, but only if array 2 meets a greater than or equal to criteria. That criteria is >=243

| Array 1      | Array 2            |

| 5         | 200 |

| 5    | 240 |

| 5 | 280 |

| 5 | 320 |

I have attempted to use the following formula:
=SUMPRODUCT(--(Program!F4:F8>=(VLOOKUP(Results!$C$10,Start!$B$3:$H$8,4,0)*Results!E22)),Program!E4:E8)

Which is simplified to:
=SUMPRODUCT(--(Program!F4:F8>=243)),Program!E4:E8)

This returns the number 10, which I assume is because it returns the true values as 1, and then are multiplied by 5 and summed.

How may I fix this to return 3000?

答:
You're almost there. Just add the first array to your formula another time, </p>

```<code>=SUMPRODUCT((F2:F5>=243)*(E2:E5)*(F2:F5))
</code>```

<p>(F2:F5>=243) creates an array of 1 or 0, and the result of that must be multiplied with (F2:F5).</p>

Title: SUMPRODUCT function with IF logic

Body:
You're almost there. Just add the first array to your formula another time,

=SUMPRODUCT((F2:F5>=243)*(E2:E5)*(F2:F5))

(F2:F5>=243) creates an array of 1 or 0, and the result of that must be multiplied with (F2:F5).


问:
Retrieve version from maven pom.xml in code
What is the simplest way to retrieve version number from maven's pom.xml in code, i.e., programatically?</p>

答:
With reference to ketankk's answer:

Unfortunately, adding this messed with how my application dealt with resources:

```<code><build>
  <resources>
    <resource>
      <directory>src/main/resources</directory>
      <filtering>true</filtering>
    </resource>
  </resources>
</build>
</code>```

But using this inside maven-assemble-plugin's < manifest > tag did the trick:

```<code><addDefaultImplementationEntries>true</addDefaultImplementationEntries>
<addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
</code>```

So I was able to get version using

```<code>String version = getClass().getPackage().getImplementationVersion();
</code>```

Body:
With reference to ketankk's answer:

Unfortunately, adding this messed with how my application dealt with resources:

<build>
  <resources>
    <resource>
      <directory>src/main/resources</directory>
      <filtering>true</filtering>
    </resource>
  </resources>
</build>

But using this inside maven-assemble-plugin's < manifest > tag did the trick:

<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
<addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>

So I was able to get version using

String version = getClass().getPackage().getImplementationVersion();


问:
CakePHP Routing - [home]/slug as URL
I'm trying to get to grips with Cake's routing, but I'm having no luck finding a solution to my particular problem.

I want to map www.example.com/slug to www.example.com/venues/view/slug, where slug is the URL friendly name of a record for a particular venue.

I also want to then map www.example.com/slug/events to www.example.com/events/index/venue:slug.

After reading the CakePHP documentation on Routing, a few times over, I'm none the wiser.  I understand how I would create these routes for each individual venue, but I'm not sure how to get Cake to generate the routes on the fly.

答:
First off, you're not connecting www.example.com/slug to www.example.com/venues/view/slug, you're connecting /slug to a controller action. Like this:

```<code>Router::connect('/:slug',
                array('controller' => 'venues', 'action' => 'view'),
                array('pass' => array('slug'));
</code>```

To generate the appropriate link, you'd do the same in reverse:

```<code>$this->Html->link('Foo',
        array('controller' => 'venues', 'action' => 'view', 'slug' => 'bar'))
</code>```

That should result in the link /bar.

The problem with routing a /:slug URL is that it's a catch-all route. You need to carefully define all other routes you may want to use before this one.

Title: CakePHP Routing - [home]/slug as URL

Body:
First off, you're not connecting www.example.com/slug to www.example.com/venues/view/slug, you're connecting /slug to a controller action. Like this:

Router::connect('/:slug',
                array('controller' => 'venues', 'action' => 'view'),
                array('pass' => array('slug'));

To generate the appropriate link, you'd do the same in reverse:

$this->Html->link('Foo',
        array('controller' => 'venues', 'action' => 'view', 'slug' => 'bar'))

That should result in the link /bar.

The problem with routing a /:slug URL is that it's a catch-all route. You need to carefully define all other routes you may want to use before this one.


问:
Looping over Array of objects and returning random object value - JavaScript
I am trying to loop over an array of objects and display a random quote from the data, so far my code returns undefined. Any idea's why?

Code so far..

```<code>const quotesToUse = [{
    quote: "This was the biggest quote ever - Array Object",
    author: "Derek Bullshido",
  },
  {
    quote: "Hey hows it going - Array Object",
    author: "Paul Frank",
  },
  {
    quote: "Why can I say that - Array Object",
    author: "Derek Paul",
  },
]

function randomQuotes() {
    for (var i = 0; i < 1; i += 1 )  {
    const randomQuote = quotesToUse[i][Math.floor(Math.random() * quotesToUse[i].quote.length)];
    document.getElementById("container").appendChild(text).append(randomQuote);
}
</code>```

I am trying to display the quote (String) randomly.

答:
You probably want this to get the quote:

```<code>const randomQuote = quotesToUse[Math.floor(Math.random() * quotesToUse.length)].quote;
</code>```

I don't know what you're trying to do with the loop.

Body:
I am trying to loop over an array of objects and display a random quote from the data, so far my code returns undefined. Any idea's why?

Code so far..

const quotesToUse = [{
    quote: "This was the biggest quote ever - Array Object",
    author: "Derek Bullshido",
  },
  {
    quote: "Hey hows it going - Array Object",
    author: "Paul Frank",
  },
  {
    quote: "Why can I say that - Array Object",
    author: "Derek Paul",
  },
]

function randomQuotes() {
    for (var i = 0; i < 1; i += 1 )  {
    const randomQuote = quotesToUse[i][Math.floor(Math.random() * quotesToUse[i].quote.length)];
    document.getElementById("container").appendChild(text).append(randomQuote);
}

I am trying to display the quote (String) randomly.

Body:
You probably want this to get the quote:

const randomQuote = quotesToUse[Math.floor(Math.random() * quotesToUse.length)].quote;

I don't know what you're trying to do with the loop.


问:
Unable to install packages after R update: unable to access index for repository: internet routines cannot be loaded
I use RStudio, and I updated R yesterday to the following version:

```<code>R version 4.0.0 (2020-04-24) -- "Arbor Day"
Copyright (C) 2020 The R Foundation for Statistical Computing
Platform: x86_64-w64-mingw32/x64 (64-bit)
</code>```

Now, I can't connect to any CRAN mirrors (I've tried 4 different ones) or install packages. When I start RStudio, I get the following errors on start up:

```<code>Error in tools::startDynamicHelp() : internet routines cannot be loaded
Warning: namespace ‘lme4’ is not available and has been replaced
by .GlobalEnv when processing object ‘lmer1’
Warning: namespace ‘ggplot2’ is not available and has been replaced
by .GlobalEnv when processing object ‘plot1’
Warning: namespace ‘emmeans’ is not available and has been replaced
by .GlobalEnv when processing object ‘.Last.ref_grid’
Warning: namespace ‘pbkrtest’ is not available and has been replaced
by .GlobalEnv when processing object ‘.Last.ref_grid’
[Workspace loaded from C:/Users/xxx.RData]

Loading required package: lmerTest
Loading required package: lme4
Loading required package: Matrix
Error: package or namespace load failed for ‘lme4’:
 package ‘lme4’ was installed before R 4.0.0: please re-install it
Failed with error:  ‘package ‘lme4’ could not be loaded’
</code>```

Then, when I try to install a package, I get the following message:

```<code>Installing package into ‘C:/Users/xxx/R/win-library/4.0’
(as ‘lib’ is unspecified)
Warning in install.packages :
  unable to access index for repository https://cran.rstudio.com/src/contrib:
  internet routines cannot be loaded
Warning in install.packages :
  package ‘Rtools’ is not available (for R version 4.0.0)
Warning in install.packages :
  unable to access index for repository https://cran.rstudio.com/bin/windows/contrib/4.0:
  internet routines cannot be loaded
</code>```

I know there are multiple threads on these warnings, but I haven't found a solution to this problem on any of them.
Things I've tried already that haven't worked:

changing the CRAN mirror setting - I've tried 4 different ones, and the mirrors are working because it works on another computer

restarting the program

restarting the computer

changing the setting in Tools>Global options>Packages so that https is unchecked

updating RStudio (though it is also a problem in R as well)

uninstalling and reinstalling R 4.0

checking the library path - seems correct

making Internet Explorer the default browser

running the command options(repos='https://cran.rstudio.com/')

running the command line install.packages("package name", dependencies=TRUE, repos='http://cran.rstudio.com/')

running the command options(download.file.method="libcurl")

running the command Sys.getenv("LD_LIBRARY_PATH")

My partner downloaded R 4.0 and RStudio on to his computer and it works fine.

Any suggestions? I'm new to Stack Overflow and pretty new to R, so please, step by step instructions/suggestions where possible!

答:
So, after 4 phone calls and multiple attempts at fixing this problem, my institutional IT department were today able to disable the antivirus block that was preventing R and R Studio from working.

Apparently, to avoid this in the future, I need to run new programs from a specific folder. So it was the antivirus after all, but I couldn't change the settings from my end as I have a work computer.

Body:
I use RStudio, and I updated R yesterday to the following version:

R version 4.0.0 (2020-04-24) -- "Arbor Day"
Copyright (C) 2020 The R Foundation for Statistical Computing
Platform: x86_64-w64-mingw32/x64 (64-bit)

Now, I can't connect to any CRAN mirrors (I've tried 4 different ones) or install packages. When I start RStudio, I get the following errors on start up:

Error in tools::startDynamicHelp() : internet routines cannot be loaded
Warning: namespace ‘lme4’ is not available and has been replaced
by .GlobalEnv when processing object ‘lmer1’
Warning: namespace ‘ggplot2’ is not available and has been replaced
by .GlobalEnv when processing object ‘plot1’
Warning: namespace ‘emmeans’ is not available and has been replaced
by .GlobalEnv when processing object ‘.Last.ref_grid’
Warning: namespace ‘pbkrtest’ is not available and has been replaced
by .GlobalEnv when processing object ‘.Last.ref_grid’
[Workspace loaded from C:/Users/xxx.RData]

Loading required package: lmerTest
Loading required package: lme4
Loading required package: Matrix
Error: package or namespace load failed for ‘lme4’:
 package ‘lme4’ was installed before R 4.0.0: please re-install it
Failed with error:  ‘package ‘lme4’ could not be loaded’

Then, when I try to install a package, I get the following message:

Installing package into ‘C:/Users/xxx/R/win-library/4.0’
(as ‘lib’ is unspecified)
Warning in install.packages :
  unable to access index for repository https://cran.rstudio.com/src/contrib:
  internet routines cannot be loaded
Warning in install.packages :
  package ‘Rtools’ is not available (for R version 4.0.0)
Warning in install.packages :
  unable to access index for repository https://cran.rstudio.com/bin/windows/contrib/4.0:
  internet routines cannot be loaded

I know there are multiple threads on these warnings, but I haven't found a solution to this problem on any of them.
Things I've tried already that haven't worked:

changing the CRAN mirror setting - I've tried 4 different ones, and the mirrors are working because it works on another computer

restarting the program

restarting the computer

changing the setting in Tools>Global options>Packages so that https is unchecked

updating RStudio (though it is also a problem in R as well)

uninstalling and reinstalling R 4.0

checking the library path - seems correct

making Internet Explorer the default browser

running the command options(repos='https://cran.rstudio.com/')

running the command line install.packages("package name", dependencies=TRUE, repos='http://cran.rstudio.com/')

running the command options(download.file.method="libcurl")

running the command Sys.getenv("LD_LIBRARY_PATH")

My partner downloaded R 4.0 and RStudio on to his computer and it works fine.

Any suggestions? I'm new to Stack Overflow and pretty new to R, so please, step by step instructions/suggestions where possible!