问:
Import multiple delimited text files into a SQL Server database and automatically create tables
I have multiple delimited text files (e.g. .csv files), each containing columns, rows and a header.

I want to import all of these input files into SQL Server with as much ease as possible. Specifically, I want to create the output tables into which I will import these files on the fly.

Some of these input files will need to be imported into one and the same output table, while others will need to be imported to different tables. You can assume that all files which will be imported into the same table have the same header.

SQL Server Management Studio has an Import Wizard which allows you to import delimited text files (and other formats) and automatically create the output table. However, this does not allow you to import multiple files at the same time. Furthermore, it requires a lot of manual work and is not replicable.

One can find many scripts online which import multiple text files into a table. However, most of these require the output table to be created first. This too, requires additional work per table.

Is there a way to list all relevant input files and their corresponding output table, such that the tables are created automatically followed by the importing of the data?

答:
 Inserting whole folder with delimited .txt or .csv files into SQL server

Note: Don't be scared of lenghty script you'll see here. There is only 3 variables that needs changing and whole script should work fine.

This solution is upgrade from accepted answer (@LBogaardt) and it also implement suggestion from @Chendur Mar for getting all files from folder.

My additions:

this solution works with UTF-8 files

imports in NVARCHAR(MAX) instead in NVARCHAR(255) - you can change that if you wish

has error logging implemented so you can see on which row import breaks in case that happens

STEP 1 - ENABLE xp_cmdshell

See here on how to do that.

STEP 2 - ENABLE permissions for everyone on Import folder

Keep on your mind - Import folder is remote folder on server. So you need to create folder on server and upload your files there.
Set permissions on that folder following this.

STEP 3 - Edit script parameters and execute it

You only have to change first 4 lines:

Line - instead of yourDatabase, put name of your database

Line - define location of your Import folder where your .txt .csv files are

Line - define row terminator which is most likely new line(\n) so keep it as is

Line - define separator for your files - if you use comma than put CHAR(44) or ','. CHAR(9) is TAB.

Script:

```<code>USE yourDatabase
DECLARE @Location NVARCHAR(MAX) = 'C:\Users\username\Desktop\Import\';
DECLARE @RowTerminator NVARCHAR(5) = '\n';
DECLARE @ColumnTerminator NVARCHAR(5) = CHAR(9);

DECLARE @SQLINSERT NVARCHAR(MAX);

-- 1.2  Define the list of input and output in a temporary table

/*
**  In this section, a temporary table is created which lists all the filenames of the delimited
**  files which need to be imported, as well as the names of the tables which are created and into
**  which the data is imported. Multiple files may be imported into the same output table. Each row
**  is prepended with an integer which increments up starting from 1. It is essential that this
**  number follows this logic. The temporary table is deleted at the end of this script.
*/

IF OBJECT_ID('[dbo].[Files_Temporary]', 'U') IS NOT NULL
DROP TABLE [dbo].[Files_Temporary];
CREATE TABLE [dbo].[Files_Temporary]
(
    [ID] INT identity (1,1) primary key
    , [FileName] NVARCHAR(max)
    , [TableName] NVARCHAR(max)
);

--insert names into  [dbo].[Files_Temporary]
SET @SQLINSERT = 'INSERT INTO [dbo].[Files_Temporary] (filename) exec master.dbo.xp_cmdshell' + char(39) + ' dir ' + @Location + ' /b /a-d' + char(39)
EXEC(@SQLINSERT)
------Update table names eliminating the file extension-------
update [dbo].[Files_Temporary] set [TableName]= SUBSTRING(filename,0, CHARINDEX('.',filename))

-- 1.3  Loop over the list of input and output and import each file to the correct table

/*
**  In this section, the 'WHILE' statement is used to loop over all input files. A counter is defined
**  which starts at '1' and increments with each iteration. The filename and tablename are retrieved
**  from the previously defined temporary table. The next step of the script is to check whether the
**  output table already exists or not.
*/

DECLARE @Counter INT = 1

WHILE @Counter <= (SELECT COUNT(*) FROM [dbo].[Files_Temporary])
BEGIN
    PRINT 'Counter is ''' + CONVERT(NVARCHAR(5), @Counter) + '''.'

    DECLARE @FileName NVARCHAR(MAX)
    DECLARE @TableName NVARCHAR(MAX)
    DECLARE @Header NVARCHAR(MAX)
    DECLARE @SQL_Header NVARCHAR(MAX)
    DECLARE @CreateHeader NVARCHAR(MAX) = ''
    DECLARE @SQL_CreateHeader NVARCHAR(MAX)

    SELECT @FileName = [FileName], @TableName = [TableName] FROM [dbo].[Files_Temporary] WHERE [ID] = @Counter

    IF OBJECT_ID('[dbo].[' + @TableName + ']', 'U') IS NULL
    BEGIN
/*
**  If the output table does not yet exist, it needs to be created. This requires the list of all
**  columnnames for that table to be retrieved from the first line of the text file, which includes
**  the header. A piece of SQL code is generated and executed which imports the header of the text
**  file. A second temporary table is created which stores this header as a single string.
*/
        PRINT 'Creating new table with name ''' + @TableName + '''.'

        IF OBJECT_ID('[dbo].[Header_Temporary]', 'U') IS NOT NULL
        DROP TABLE [dbo].[Header_Temporary];
        CREATE TABLE [dbo].[Header_Temporary]
        (
            [Header] NVARCHAR(MAX)
        );

        SET @SQL_Header = '
            BULK INSERT [dbo].[Header_Temporary]
            FROM ''' + @Location + @FileName + '''
            WITH
            (
                FIRSTROW = 1,
                LASTROW = 1,
                MAXERRORS = 0,
                FIELDTERMINATOR = ''' + @RowTerminator + ''',
                ROWTERMINATOR = ''' + @RowTerminator + '''
            )'
        EXEC(@SQL_Header)

        SET @Header = (SELECT TOP 1 [Header] FROM [dbo].[Header_Temporary])
        PRINT 'Extracted header ''' + @Header + ''' for table ''' + @TableName + '''.'
/*
**  The columnnames in the header are separated using the column-terminator. This can be used to loop
**  over each columnname. A new piece of SQL code is generated which will create the output table
**  with the correctly named columns.
*/
        WHILE CHARINDEX(@ColumnTerminator, @Header) > 0
        BEGIN
            SET @CreateHeader = @CreateHeader + '[' + LTRIM(RTRIM(SUBSTRING(@Header, 1, CHARINDEX(@ColumnTerminator, @Header) - 1))) + '] NVARCHAR(MAX), '
            SET @Header = SUBSTRING(@Header, CHARINDEX(@ColumnTerminator, @Header) + 1, LEN(@Header))
        END
        SET @CreateHeader = @CreateHeader + '[' + @Header + '] NVARCHAR(MAX)'

        SET @SQL_CreateHeader = 'CREATE TABLE [ESCO].[' + @TableName + '] (' + @CreateHeader + ')'
        EXEC(@SQL_CreateHeader)
    END

/*
**  Finally, the data from the text file is imported into the newly created table. The first line,
**  including the header information, is skipped. If multiple text files are imported into the same
**  output table, it is essential that the number and the order of the columns is identical, as the
**  table will only be created once, using the header information of the first text file.
*/
    --bulk insert

    PRINT 'Inserting data from ''' + @FileName + ''' to ''' + @TableName + '''.'
    DECLARE @SQL NVARCHAR(MAX)
    SET @SQL = '
        BULK INSERT [dbo].[' + @TableName + ']
        FROM ''' + @Location + @FileName + '''
        WITH
        (
            FIRSTROW = 2,
            MAXERRORS = 0,
            FIELDTERMINATOR = ''' + @ColumnTerminator + ''',
            ROWTERMINATOR = ''' + @RowTerminator + ''',
            CODEPAGE = ''65001'',
            DATAFILETYPE = ''Char'',
            ERRORFILE = ''' + @Location + 'ImportLog.log''
        )'
    EXEC(@SQL)

    SET @Counter = @Counter + 1
END;

-- 1.4  Cleanup temporary tables

/*
**  In this section, the temporary tables which were created and used by this script are deleted.
**  Alternatively, the script could have used 'real' temporary table (identified by the '#' character
**  in front of the name) or a table variable. These would have deleted themselves once they were no
**  longer in use. However, the end result is the same.
*/

IF OBJECT_ID('[dbo].[Files_Temporary]', 'U') IS NOT NULL
DROP TABLE [dbo].[Files_Temporary];

IF OBJECT_ID('[dbo].[Header_Temporary]', 'U') IS NOT NULL
DROP TABLE [dbo].[Header_Temporary];
</code>```

On the end disable xp_cmdshell and delete Import folder.

Body:
 Inserting whole folder with delimited .txt or .csv files into SQL server

Note: Don't be scared of lenghty script you'll see here. There is only 3 variables that needs changing and whole script should work fine.

This solution is upgrade from accepted answer (@LBogaardt) and it also implement suggestion from @Chendur Mar for getting all files from folder.

My additions:

this solution works with UTF-8 files

imports in NVARCHAR(MAX) instead in NVARCHAR(255) - you can change that if you wish

has error logging implemented so you can see on which row import breaks in case that happens

STEP 1 - ENABLE xp_cmdshell

See here on how to do that.

STEP 2 - ENABLE permissions for everyone on Import folder

Keep on your mind - Import folder is remote folder on server. So you need to create folder on server and upload your files there.
Set permissions on that folder following this.

STEP 3 - Edit script parameters and execute it

You only have to change first 4 lines:

Line - instead of yourDatabase, put name of your database

Line - define location of your Import folder where your .txt .csv files are

Line - define row terminator which is most likely new line(\n) so keep it as is

Line - define separator for your files - if you use comma than put CHAR(44) or ','. CHAR(9) is TAB.

Script:

USE yourDatabase
DECLARE @Location NVARCHAR(MAX) = 'C:\Users\username\Desktop\Import\';
DECLARE @RowTerminator NVARCHAR(5) = '\n';
DECLARE @ColumnTerminator NVARCHAR(5) = CHAR(9);

DECLARE @SQLINSERT NVARCHAR(MAX);

-- 1.2  Define the list of input and output in a temporary table

/*
**  In this section, a temporary table is created which lists all the filenames of the delimited
**  files which need to be imported, as well as the names of the tables which are created and into
**  which the data is imported. Multiple files may be imported into the same output table. Each row
**  is prepended with an integer which increments up starting from 1. It is essential that this
**  number follows this logic. The temporary table is deleted at the end of this script.
*/

IF OBJECT_ID('[dbo].[Files_Temporary]', 'U') IS NOT NULL
DROP TABLE [dbo].[Files_Temporary];
CREATE TABLE [dbo].[Files_Temporary]
(
    [ID] INT identity (1,1) primary key
    , [FileName] NVARCHAR(max)
    , [TableName] NVARCHAR(max)
);

--insert names into  [dbo].[Files_Temporary]
SET @SQLINSERT = 'INSERT INTO [dbo].[Files_Temporary] (filename) exec master.dbo.xp_cmdshell' + char(39) + ' dir ' + @Location + ' /b /a-d' + char(39)
EXEC(@SQLINSERT)
------Update table names eliminating the file extension-------
update [dbo].[Files_Temporary] set [TableName]= SUBSTRING(filename,0, CHARINDEX('.',filename))

-- 1.3  Loop over the list of input and output and import each file to the correct table

/*
**  In this section, the 'WHILE' statement is used to loop over all input files. A counter is defined
**  which starts at '1' and increments with each iteration. The filename and tablename are retrieved
**  from the previously defined temporary table. The next step of the script is to check whether the
**  output table already exists or not.
*/

DECLARE @Counter INT = 1

WHILE @Counter <= (SELECT COUNT(*) FROM [dbo].[Files_Temporary])
BEGIN
    PRINT 'Counter is ''' + CONVERT(NVARCHAR(5), @Counter) + '''.'

    DECLARE @FileName NVARCHAR(MAX)
    DECLARE @TableName NVARCHAR(MAX)
    DECLARE @Header NVARCHAR(MAX)
    DECLARE @SQL_Header NVARCHAR(MAX)
    DECLARE @CreateHeader NVARCHAR(MAX) = ''
    DECLARE @SQL_CreateHeader NVARCHAR(MAX)

    SELECT @FileName = [FileName], @TableName = [TableName] FROM [dbo].[Files_Temporary] WHERE [ID] = @Counter

    IF OBJECT_ID('[dbo].[' + @TableName + ']', 'U') IS NULL
    BEGIN
/*
**  If the output table does not yet exist, it needs to be created. This requires the list of all
**  columnnames for that table to be retrieved from the first line of the text file, which includes
**  the header. A piece of SQL code is generated and executed which imports the header of the text
**  file. A second temporary table is created which stores this header as a single string.
*/
        PRINT 'Creating new table with name ''' + @TableName + '''.'

        IF OBJECT_ID('[dbo].[Header_Temporary]', 'U') IS NOT NULL
        DROP TABLE [dbo].[Header_Temporary];
        CREATE TABLE [dbo].[Header_Temporary]
        (
            [Header] NVARCHAR(MAX)
        );

        SET @SQL_Header = '
            BULK INSERT [dbo].[Header_Temporary]
            FROM ''' + @Location + @FileName + '''
            WITH
            (
                FIRSTROW = 1,
                LASTROW = 1,
                MAXERRORS = 0,
                FIELDTERMINATOR = ''' + @RowTerminator + ''',
                ROWTERMINATOR = ''' + @RowTerminator + '''
            )'
        EXEC(@SQL_Header)

        SET @Header = (SELECT TOP 1 [Header] FROM [dbo].[Header_Temporary])
        PRINT 'Extracted header ''' + @Header + ''' for table ''' + @TableName + '''.'
/*
**  The columnnames in the header are separated using the column-terminator. This can be used to loop
**  over each columnname. A new piece of SQL code is generated which will create the output table
**  with the correctly named columns.
*/
        WHILE CHARINDEX(@ColumnTerminator, @Header) > 0
        BEGIN
            SET @CreateHeader = @CreateHeader + '[' + LTRIM(RTRIM(SUBSTRING(@Header, 1, CHARINDEX(@ColumnTerminator, @Header) - 1))) + '] NVARCHAR(MAX), '
            SET @Header = SUBSTRING(@Header, CHARINDEX(@ColumnTerminator, @Header) + 1, LEN(@Header))
        END
        SET @CreateHeader = @CreateHeader + '[' + @Header + '] NVARCHAR(MAX)'

        SET @SQL_CreateHeader = 'CREATE TABLE [ESCO].[' + @TableName + '] (' + @CreateHeader + ')'
        EXEC(@SQL_CreateHeader)
    END

/*
**  Finally, the data from the text file is imported into the newly created table. The first line,
**  including the header information, is skipped. If multiple text files are imported into the same
**  output table, it is essential that the number and the order of the columns is identical, as the
**  table will only be created once, using the header information of the first text file.
*/
    --bulk insert

    PRINT 'Inserting data from ''' + @FileName + ''' to ''' + @TableName + '''.'
    DECLARE @SQL NVARCHAR(MAX)
    SET @SQL = '
        BULK INSERT [dbo].[' + @TableName + ']
        FROM ''' + @Location + @FileName + '''
        WITH
        (
            FIRSTROW = 2,
            MAXERRORS = 0,
            FIELDTERMINATOR = ''' + @ColumnTerminator + ''',
            ROWTERMINATOR = ''' + @RowTerminator + ''',
            CODEPAGE = ''65001'',
            DATAFILETYPE = ''Char'',
            ERRORFILE = ''' + @Location + 'ImportLog.log''
        )'
    EXEC(@SQL)

    SET @Counter = @Counter + 1
END;

-- 1.4  Cleanup temporary tables

/*
**  In this section, the temporary tables which were created and used by this script are deleted.
**  Alternatively, the script could have used 'real' temporary table (identified by the '#' character
**  in front of the name) or a table variable. These would have deleted themselves once they were no
**  longer in use. However, the end result is the same.
*/

IF OBJECT_ID('[dbo].[Files_Temporary]', 'U') IS NOT NULL
DROP TABLE [dbo].[Files_Temporary];

IF OBJECT_ID('[dbo].[Header_Temporary]', 'U') IS NOT NULL
DROP TABLE [dbo].[Header_Temporary];

On the end disable xp_cmdshell and delete Import folder.


来源: stackexchange

问:
Python merge list intervals
I have started to practice questions on leetcode and being a beginner I am facing some minor issues with the approach. The task at hand is to merge all overlapping intervals.

```<code>Input: [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
</code>```

I know there are better approaches to solve this problem with much better time complexities but my aim here is to identify the flaw in my approach.

Here is what I have tried:

```<code>def merge(self, intervals: List[List[int]]) -> List[List[int]]:
        if len(intervals) == 1:
            return intervals
        intervals = sorted(intervals)
        i = 0
        k = 0
        while i < len(intervals)-1:
            k = k + 1
            for j in range(i+1,len(intervals)):
                if intervals[i][1] >= intervals[j][0]:
                    intervals[i] = [intervals[i][0],max(intervals[i][1],intervals[j][1])]
                    del intervals[j]
                    i = i + 1
                else:
                    intervals[i] = [intervals[j-1][0],intervals[j-1][1]]
                    i = j
                    break

            print(intervals,k)
        return intervals[:k+1]
</code>```

I thing the point where I am struggling is the else statement where I update the list if no overlapping intervals is found. Any help in pointing out where I am wrong would be great.

Link to the problem if required : Merge Intervals

答:
One problem is

```<code>del intervals[j]
</code>```

Modifying a container while iterating over it is generally a bad idea. It often results in skipped or duplicated values.

Consider the inner loop, when i=0 and j=1:

```<code>  i=0   j=1
[[1,3],[2,6],[8,10],[15,18]]
</code>```

The intervals overlap, so the if block is executed:

```<code>intervals[i] = [intervals[i][0],max(intervals[i][1],intervals[j][1])]
</code>```

resulting in:

```<code>  i=0   j=1
[[1,6],[2,6],[8,10],[15,18]]
</code>```

then

```<code>del intervals[j]
</code>```

resulting in:

```<code>  i=0   j=1
[[1,6],[8,10],[15,18]]
</code>```

then:

```<code>i = i + 1
</code>```

resulting in:

```<code>        i=j=1
[[1,6],[8,10],[15,18]]
</code>```

But now the for-loop increments j:

```<code>        i=1     j=2
[[1,6],[8,10],[15,18]]
</code>```

Notice how j skips over the interval [8,10]?

It is better to create a new list of the merger intervals. If you must do it in place, work backwards from the end of the list. That way, any indexes that are changed are ones that have already been processed.

ContentLicense: CC BY-SA 4.0

Title: Python merge list intervals

Body:
I have started to practice questions on leetcode and being a beginner I am facing some minor issues with the approach. The task at hand is to merge all overlapping intervals.

Input: [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].

I know there are better approaches to solve this problem with much better time complexities but my aim here is to identify the flaw in my approach.

Here is what I have tried:

def merge(self, intervals: List[List[int]]) -> List[List[int]]:
        if len(intervals) == 1:
            return intervals
        intervals = sorted(intervals)
        i = 0
        k = 0
        while i < len(intervals)-1:
            k = k + 1
            for j in range(i+1,len(intervals)):
                if intervals[i][1] >= intervals[j][0]:
                    intervals[i] = [intervals[i][0],max(intervals[i][1],intervals[j][1])]
                    del intervals[j]
                    i = i + 1
                else:
                    intervals[i] = [intervals[j-1][0],intervals[j-1][1]]
                    i = j
                    break

            print(intervals,k)
        return intervals[:k+1]

I thing the point where I am struggling is the else statement where I update the list if no overlapping intervals is found. Any help in pointing out where I am wrong would be great.

Link to the problem if required : Merge Intervals

Body:
One problem is

del intervals[j]

Modifying a container while iterating over it is generally a bad idea. It often results in skipped or duplicated values.

Consider the inner loop, when i=0 and j=1:

  i=0   j=1
[[1,3],[2,6],[8,10],[15,18]]

The intervals overlap, so the if block is executed:

intervals[i] = [intervals[i][0],max(intervals[i][1],intervals[j][1])]

resulting in:

  i=0   j=1
[[1,6],[2,6],[8,10],[15,18]]

then

del intervals[j]

resulting in:

  i=0   j=1
[[1,6],[8,10],[15,18]]

then:

i = i + 1

resulting in:

        i=j=1
[[1,6],[8,10],[15,18]]

But now the for-loop increments j:

        i=1     j=2
[[1,6],[8,10],[15,18]]

Notice how j skips over the interval [8,10]?

It is better to create a new list of the merger intervals. If you must do it in place, work backwards from the end of the list. That way, any indexes that are changed are ones that have already been processed.


问:
Storing List Variable on change
I am learning Flutter currently and was making a personal finance app. I have the option to bookmark my guides and then view them on the bookmark tab. Right now, I am using a list to simply store names of guides and display them as list tiles.

The issue I am having is that whenever the bookmark list is updated WHILE the app is running, the Bookmarks page loads the right info but then when I close and restart the app, it goes back to it's initial state of being empty. How can I fix it so that the app saves bookmarked tabs?

main.dart

```<code>List<String> bookmarked = [];

String introInfo = """ <h1>Introduction!</h1>
<p><strong><em>NOTE: The guides are U.S. specific but most information can be applied in most countries outside the U.S.</em></strong></p>
<p>The guides in this app will teach you the basics of personal finance.</p>
<p>Financial knowledge is something that is invaluable but the U.S. education system does not put much emphasis on it. If you are looking to get into personal finance, you're at the right place.</p>""";

void main() {
  runApp(MaterialApp(
    initialRoute: '/',
    routes: {
      '/': (context) => MyApp(),
      '/finTable': (context) => FinNav(),
      '/disclaimer': (context) => Disclaimer(),
      '/intro': (context) => GuideStyle(guideName: 'introduction',guideInfo: introInfo, isFav: bookmarked.contains('introduction'),),
      '/budget': (context) => GuideStyle(guideName: 'budget',guideInfo: introInfo, isFav: bookmarked.contains('budget'),),
      '/bookmark': (context) => Bookmarks(),
    },
    theme: ThemeData(fontFamily: 'Raleway'),
  ));
}

/* I have a stateless widget that shows all pages and navigates to one the user selects */
</code>```

guidestyle.dart

```<code>class GuideStyle extends StatelessWidget {
  String guideName;
  String guideInfo;
  Widget previous;
  Widget next;
  bool isFav;
  GuideStyle({this.guideName,this.guideInfo, this.isFav });//this.next, this.previous});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          backgroundColor: Color.fromRGBO(220, 20, 60, 1.0),
          title: Text('Introduction'),
          centerTitle: true,
          elevation: 10.0,
          actions: <Widget>[
            Padding(
              padding: const EdgeInsets.fromLTRB(0.0,2.0,50.0,0.0),
              child: MyStatefulWidget(isFav: isFav,name: guideName,),
            ),
          ],
        ),
        body: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.all(10.0),
              child: RaisedButton(
                onPressed: () {
                  Navigator.pop(context);
                },
                child: Text('Back'),
                textColor: Colors.white,
                color: Color.fromRGBO(220, 20, 60, 0.8),
              ),
            ),
            Expanded(
              child: SingleChildScrollView(
                child: Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: HtmlWidget(
                    guideInfo,
                  )
                ),
              ),
            ),
          ],
        ));
  }
}

class MyStatefulWidget extends StatefulWidget {
  bool isFav;
  String name;
  MyStatefulWidget({Key key, this.isFav, this.name}) : super(key: key);

  @override
  _MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}

class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[
        IconButton(
          icon: widget.isFav ? Icon(Icons.bookmark, color: Colors.black) : Icon(Icons.bookmark_border),
          onPressed: () {
            setState(() {
              widget.isFav = !widget.isFav;
              if(widget.isFav){
                bookmarked.add(widget.name);
                bookmarked = bookmarked;
              }else{
                bookmarked.remove(widget.name);
                bookmarked = bookmarked;
              }
            });
          },
        ),
      ],
    );
  }
}
</code>```

As mentioned, the guidestyle.dart updates the list while the app is running but the list is reset when the app is restarted.

I was looking into using sqflite but it seems overkill so I am unsure about my other options. Any help would be appreciated!

答:
You can use the SharedPreferences package or any other method that is able to persist data between app launches. See this for options to persist data.

Options:

Persist data with SQLite (Though you don't want to use it, it is still an option)

Read and write files

Store key-value data on disk(SharedPreferences) - This is the simplest and will probably suit your needs just fine

If you are using SharedPreferences the setStringList method will suit your needs perfectly.

As a side note, the line bookmarked = bookmarked; is useless.

Title: Storing List Variable on change

Body:
I am learning Flutter currently and was making a personal finance app. I have the option to bookmark my guides and then view them on the bookmark tab. Right now, I am using a list to simply store names of guides and display them as list tiles.

The issue I am having is that whenever the bookmark list is updated WHILE the app is running, the Bookmarks page loads the right info but then when I close and restart the app, it goes back to it's initial state of being empty. How can I fix it so that the app saves bookmarked tabs?

main.dart

List<String> bookmarked = [];

String introInfo = """
Introduction!

NOTE: The guides are U.S. specific but most information can be applied in most countries outside the U.S.

The guides in this app will teach you the basics of personal finance.

Financial knowledge is something that is invaluable but the U.S. education system does not put much emphasis on it. If you are looking to get into personal finance, you're at the right place.
""";

void main() {
  runApp(MaterialApp(
    initialRoute: '/',
    routes: {
      '/': (context) => MyApp(),
      '/finTable': (context) => FinNav(),
      '/disclaimer': (context) => Disclaimer(),
      '/intro': (context) => GuideStyle(guideName: 'introduction',guideInfo: introInfo, isFav: bookmarked.contains('introduction'),),
      '/budget': (context) => GuideStyle(guideName: 'budget',guideInfo: introInfo, isFav: bookmarked.contains('budget'),),
      '/bookmark': (context) => Bookmarks(),
    },
    theme: ThemeData(fontFamily: 'Raleway'),
  ));
}

/* I have a stateless widget that shows all pages and navigates to one the user selects */

guidestyle.dart

class GuideStyle extends StatelessWidget {
  String guideName;
  String guideInfo;
  Widget previous;
  Widget next;
  bool isFav;
  GuideStyle({this.guideName,this.guideInfo, this.isFav });//this.next, this.previous});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          backgroundColor: Color.fromRGBO(220, 20, 60, 1.0),
          title: Text('Introduction'),
          centerTitle: true,
          elevation: 10.0,
          actions: <Widget>[
            Padding(
              padding: const EdgeInsets.fromLTRB(0.0,2.0,50.0,0.0),
              child: MyStatefulWidget(isFav: isFav,name: guideName,),
            ),
          ],
        ),
        body: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.all(10.0),
              child: RaisedButton(
                onPressed: () {
                  Navigator.pop(context);
                },
                child: Text('Back'),
                textColor: Colors.white,
                color: Color.fromRGBO(220, 20, 60, 0.8),
              ),
            ),
            Expanded(
              child: SingleChildScrollView(
                child: Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: HtmlWidget(
                    guideInfo,
                  )
                ),
              ),
            ),
          ],
        ));
  }
}

class MyStatefulWidget extends StatefulWidget {
  bool isFav;
  String name;
  MyStatefulWidget({Key key, this.isFav, this.name}) : super(key: key);

  @override
  _MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}

class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[
        IconButton(
          icon: widget.isFav ? Icon(Icons.bookmark, color: Colors.black) : Icon(Icons.bookmark_border),
          onPressed: () {
            setState(() {
              widget.isFav = !widget.isFav;
              if(widget.isFav){
                bookmarked.add(widget.name);
                bookmarked = bookmarked;
              }else{
                bookmarked.remove(widget.name);
                bookmarked = bookmarked;
              }
            });
          },
        ),
      ],
    );
  }
}

As mentioned, the guidestyle.dart updates the list while the app is running but the list is reset when the app is restarted.

I was looking into using sqflite but it seems overkill so I am unsure about my other options. Any help would be appreciated!


问:
sending mail in Laravel 5.4 using Mailgun get error code " 401 UNAUTHORIZED` response: Forbidden "
I'm trying to send mail in Laravel 5.4 project with Mailgun. I think I set the configuration correctly. But, I got this error message such as

ClientException in RequestException.php line 111:
  Client error: POST https://api.mailgun.net/v3/sandboxfeb88d58f18841738b2fc81d7cbc7631.mailgun.org/messages.mime >resulted in a 401 UNAUTHORIZED response:
  Forbidden

Here is my configuration:

in .env file

```<code>MAIL_DRIVER=mailgun
MAILGUN_DOMAIN=sandboxfeb88d58f18841738b2fc81d7cbc7631.mailgun.org
MAILGUN_SECRET=pubkey-1767e**********
</code>```

in mail.php file

```<code>'driver' => env('MAIL_DRIVER', 'smtp'),
'host' => env('MAIL_HOST', 'smtp.mailgun.org'),
'port' => env('MAIL_PORT', 587),
'from' => [
    'address' => env('MAIL_FROM_ADDRESS', 'richi.htoo@gmail.com'),
    'name' => env('MAIL_FROM_NAME', 'Richi Htoo'),
],
</code>```

in services.php file

```<code>'mailgun' => [
    'domain' => env('MAILGUN_DOMAIN'),
    'secret' => env('MAILGUN_SECRET'),
],
</code>```

and I wrote mail sending code in default route such as

```<code>Route::get('/', function () {
//return view('welcome');

    $data = [
        'title' => 'Hi student I hope you like the course',
        'content' => 'This laravel course was created with a lot of love and dedication for you'
    ];

    Mail::send('emails.test', $data, function($message){
        $message->to('white.nuzzle@gmail.com', 'White Nuzzle')->subject('Hello student how are you?');
    });
});
</code>```

And I also installed Laravel Package "guzzlehttp/guzzle" version 6.2 to send mail.

But when I call that default home route, I got an error message as I mention above.

I can't find any solution for my error in any where including this forum "stackoverflow.com".

Can anyone help me please?

答:
Default Mail Driver: Mailgun

```<code>MAILGUN_DOMAIN=*your-domain*.mailgun.org

MAILGUN_SECRET=pubkey-*your-public-key*
</code>```

Default Mail Driver: SMTP

```<code>MAIL_USERNAME=postmaster@*your-domain*.mailgun.org

MAIL_PASSWORD=*your-password*
</code>```

Don't forget to php artisan config:clear

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to send mail in Laravel 5.4 project with Mailgun. I think I set the configuration correctly. But, I got this error message such as

ClientException in RequestException.php line 111:
  Client error: POST https://api.mailgun.net/v3/sandboxfeb88d58f18841738b2fc81d7cbc7631.mailgun.org/messages.mime >resulted in a 401 UNAUTHORIZED response:
  Forbidden

Here is my configuration:

in .env file

MAIL_DRIVER=mailgun
MAILGUN_DOMAIN=sandboxfeb88d58f18841738b2fc81d7cbc7631.mailgun.org
MAILGUN_SECRET=pubkey-1767e**********

in mail.php file

'driver' => env('MAIL_DRIVER', 'smtp'),
'host' => env('MAIL_HOST', 'smtp.mailgun.org'),
'port' => env('MAIL_PORT', 587),
'from' => [
    'address' => env('MAIL_FROM_ADDRESS', 'richi.htoo@gmail.com'),
    'name' => env('MAIL_FROM_NAME', 'Richi Htoo'),
],

in services.php file

'mailgun' => [
    'domain' => env('MAILGUN_DOMAIN'),
    'secret' => env('MAILGUN_SECRET'),
],

and I wrote mail sending code in default route such as

Route::get('/', function () {
//return view('welcome');

    $data = [
        'title' => 'Hi student I hope you like the course',
        'content' => 'This laravel course was created with a lot of love and dedication for you'
    ];

    Mail::send('emails.test', $data, function($message){
        $message->to('white.nuzzle@gmail.com', 'White Nuzzle')->subject('Hello student how are you?');
    });
});

And I also installed Laravel Package "guzzlehttp/guzzle" version 6.2 to send mail.

But when I call that default home route, I got an error message as I mention above.

I can't find any solution for my error in any where including this forum "stackoverflow.com".

Can anyone help me please?

Body:
Default Mail Driver: Mailgun

MAILGUN_DOMAIN=*your-domain*.mailgun.org

MAILGUN_SECRET=pubkey-*your-public-key*

Default Mail Driver: SMTP

MAIL_USERNAME=postmaster@*your-domain*.mailgun.org

MAIL_PASSWORD=*your-password*

Don't forget to php artisan config:clear


问:
how to search through a json response and compare a variable to existing key - value and get results of a different key - value
I want to display a polygon in a bing map. I've got this part down. I'm wondering how I would go about accessing a value from a different key in my json response once I've identified which key's sibling i'm trying to access?

I have this variable on the page:

var = 273972;

I want to match that variable to polygons.sections.id[] in my json response and grab the sibling COORDS value then store that value in a new varaible.

I have jquery and _underscore.js available.

Here is my JSON

```
"polygons":[
    {
        "id":46327,
        "name":"first set",
        "sections":[
            {
            "id":"273971",
            "name":"202",
            "coords":[[-63.675505883656555,-90.3515625],[-63.908396220031165,-90.439453125]]
            },
            {
            "id":"273972",
            "name":"203",
            "coords":[[-63.675505883656555,-90.3515625],[-63.908396220031165,-90.439453125]]
            },
            {
            "id":"273973",
            "name":"204",
            "coords":[[-63.675505883656555,-90.3515625],[-63.908396220031165,-90.439453125]]
            }
        ]
    }
]
```

Body:
I want to display a polygon in a bing map. I've got this part down. I'm wondering how I would go about accessing a value from a different key in my json response once I've identified which key's sibling i'm trying to access?

I have this variable on the page:

var = 273972;

I want to match that variable to polygons.sections.id[] in my json response and grab the sibling COORDS value then store that value in a new varaible.

I have jquery and _underscore.js available.

Here is my JSON

"polygons":[
    {
        "id":46327,
        "name":"first set",
        "sections":[
            {
            "id":"273971",
            "name":"202",
            "coords":[[-63.675505883656555,-90.3515625],[-63.908396220031165,-90.439453125]]
            },
            {
            "id":"273972",
            "name":"203",
            "coords":[[-63.675505883656555,-90.3515625],[-63.908396220031165,-90.439453125]]
            },
            {
            "id":"273973",
            "name":"204",
            "coords":[[-63.675505883656555,-90.3515625],[-63.908396220031165,-90.439453125]]
            }
        ]
    }
]

Body:
I'm not sure if this is what you are looking for or not.

var jsonObj = $.parseJSON('{"polygons":[{"id":46327,"name":"first set","sections":[{"id":"273971","name":"202","coords":[[-63.675505883656555,-90.3515625],[-63.908396220031165,-90.439453125]]},{"id":"273972","name":"203","coords":[[-63.675505883656555,-90.3515625],[-63.908396220031165,-90.439453125]]},{"id":"273973","name":"204","coords":[[-63.675505883656555,-90.3515625],[-63.908396220031165,-90.439453125]]}]}]}');

var sections = jsonObj.polygons[0].sections;
for (var i = 0; i < sections.length; i++) {
    if (sections[i].id == "273972") {
        alert(sections[i].coords);
    }
}


问:
libtbb.so.2 library does not exist when sourcing `compilervars.sh intel64`
I am trying to run a file using the make command. But when I do this, I get the message:

make: ifort: Command not found

I know that I must set the ifort environment using the following command:

/opt/intel/parallel_studio_xe_2020.1.102/compilers_and_libraries_2020/linux/bin/compilervars.sh intel64

But when I do this, I get the message:

ERROR: libtbb.so.2 library does not exist in SUBSTITUTE_INSTALL_DIR_HERE/lib/intel64/gcc4.8.

Does anyone know what should I do? It looks to me that I must somehow modify the usual variable LD_LIBRARY_PATH to inform where gcc4.8 is.

I can manually find it at:/opt/intel/tbb/lib/intel64/gcc4.8

Where should I put this information?

I am currently using Parallel Studio XE 2020.

答:
Open

/opt/intel/parallel_studio_xe_2020.1.102/compilers_and_libraries_2020/linux/bin/compilervars.sh

with your favorite editor, and look for the line with tbb/bin/tbbvars.sh.

Find the full path for that script. It should be something like

/opt/intel/parallel_studio_xe_2020.1.102/compilers_and_libraries_2020/linux/tbb/bin/tbbvars.sh.

Open that, and look for the line

TBBROOT=SUBSTITUTE_INSTALL_DIR_HERE

and replace with

TBBROOT="/opt/intel/tbb"


问:
How to dbms_output record variable
```<code>set serveroutput on;
DECLARE
  PI_STARTDATE DATE;
  PO_STATUS NUMBER;
  PO_HEADER VARCHAR2(200);
  PO_LABEL VARCHAR2(200);
  PO_RECORD SYS_REFCURSOR;
  PO_NEXTINCSTARTDATE DATE;
BEGIN
  PI_STARTDATE := to_date('2020-05-01','yyyy-MM-dd');
  PCK_FAB_REPORTS.PRC_MONTHLY_WRTOFF_REPORT(
    PI_STARTDATE => PI_STARTDATE,
    PO_STATUS => PO_STATUS,
    PO_HEADER => PO_HEADER,
    PO_LABEL => PO_LABEL,
    PO_RECORD => PO_RECORD,
    PO_NEXTINCSTARTDATE => PO_NEXTINCSTARTDATE);
DBMS_OUTPUT.PUT_LINE('PO_STATUS = ' || PO_STATUS);
DBMS_OUTPUT.PUT_LINE('PO_HEADER = ' || PO_HEADER);
DBMS_OUTPUT.PUT_LINE('PO_LABEL = ' || PO_LABEL);
DBMS_OUTPUT.PUT_LINE('PO_NEXTINCSTARTDATE = ' || PO_NEXTINCSTARTDATE);
END;
</code>```

I want to unit test the procedure and want to display the ref cursor variable as well. How to display ref cursor using dbms?

答:
Here's an example based on Scott's EMP table:

```<code>SQL> set serveroutput on
SQL>
SQL> declare
  2    l_ename   emp.ename%type;
  3    l_job     emp.job%type;
  4    l_rc      sys_refcursor;
  5  begin
  6    open l_rc for select ename, job from emp
  7                  where deptno = 10;
  8
  9    loop
 10      fetch l_rc into l_ename, l_job;
 11      exit when l_rc%notfound;
 12
 13      dbms_output.put_line(l_ename ||' '|| l_job);
 14    end loop;
 15    close l_rc;
 16  end;
 17  /
CLARK MANAGER
KING PRESIDENT
MILLER CLERK

PL/SQL procedure successfully completed.

SQL>
</code>```

So: you have to fetch refcursor into variables and then display contents of those variables.

Title: How to dbms_output record variable

Body:
set serveroutput on;
DECLARE
  PI_STARTDATE DATE;
  PO_STATUS NUMBER;
  PO_HEADER VARCHAR2(200);
  PO_LABEL VARCHAR2(200);
  PO_RECORD SYS_REFCURSOR;
  PO_NEXTINCSTARTDATE DATE;
BEGIN
  PI_STARTDATE := to_date('2020-05-01','yyyy-MM-dd');
  PCK_FAB_REPORTS.PRC_MONTHLY_WRTOFF_REPORT(
    PI_STARTDATE => PI_STARTDATE,
    PO_STATUS => PO_STATUS,
    PO_HEADER => PO_HEADER,
    PO_LABEL => PO_LABEL,
    PO_RECORD => PO_RECORD,
    PO_NEXTINCSTARTDATE => PO_NEXTINCSTARTDATE);
DBMS_OUTPUT.PUT_LINE('PO_STATUS = ' || PO_STATUS);
DBMS_OUTPUT.PUT_LINE('PO_HEADER = ' || PO_HEADER);
DBMS_OUTPUT.PUT_LINE('PO_LABEL = ' || PO_LABEL);
DBMS_OUTPUT.PUT_LINE('PO_NEXTINCSTARTDATE = ' || PO_NEXTINCSTARTDATE);
END;

I want to unit test the procedure and want to display the ref cursor variable as well. How to display ref cursor using dbms?

Body:
Here's an example based on Scott's EMP table:

SQL> set serveroutput on
SQL>
SQL> declare
  2    l_ename   emp.ename%type;
  3    l_job     emp.job%type;
  4    l_rc      sys_refcursor;
  5  begin
  6    open l_rc for select ename, job from emp
  7                  where deptno = 10;
  8
  9    loop
 10      fetch l_rc into l_ename, l_job;
 11      exit when l_rc%notfound;
 12
 13      dbms_output.put_line(l_ename ||' '|| l_job);
 14    end loop;
 15    close l_rc;
 16  end;
 17  /
CLARK MANAGER
KING PRESIDENT
MILLER CLERK

PL/SQL procedure successfully completed.

SQL>

So: you have to fetch refcursor into variables and then display contents of those variables.


问:
How can I share the screen using Cefsharp.wpf?
I want to allow screen sharing feature from my WPF app. I am using Cefsharp.WPF package.

I tried the below command line argument from my code

```<code>var settings = new CefSettings();
settings.CefCommandLineArgs.Add("use-fake-ui-for-media-stream", "1");
</code>```

But this shared the default screen and did not asked any options to share.
Also, the argument - "use-fake-ui-for-media-stream" is used I guess for automation testing, what argument do I need to use for development?

Can anyone help me with this?

答:
There is no support yet provided for this package.
Alternative is to use command line argument - use-fake-ui-for-media-stream
This will share default screen.</p>

Body:
I want to allow screen sharing feature from my WPF app. I am using Cefsharp.WPF package.

I tried the below command line argument from my code

var settings = new CefSettings();
settings.CefCommandLineArgs.Add("use-fake-ui-for-media-stream", "1");

But this shared the default screen and did not asked any options to share.
Also, the argument - "use-fake-ui-for-media-stream" is used I guess for automation testing, what argument do I need to use for development?

Can anyone help me with this?


问:
Add users` extra data to firestore when they sign in first time with web Firebase firestore
```<code>unsubscribeFromAuth = null; //memory leak

  componentDidMount() {
    this.unsubscribeFromAuth = auth.onAuthStateChanged(user => {
      this.setState({ currentUser: user });
      if (user === null)
        return;

      // user data
      const uid = user.uid;
      const photoURL = user.photoURL;
      const name = user.displayName;

      const userRef = firestore.collection('Users');
      userRef.where('uid','==',uid).get().then((querySnapshot) => {
        console.log("uid size : ",querySnapshot.size);
        // add user extra data when first sign in.
        if (querySnapshot.size === 0) {
          firestore.collection('Users').add({
            uid: uid,
            photoURL: photoURL,
            name: name,
          })
          .then((docRef) => {
            console.log("Document written with ID: ", docRef.id);
          })
          .catch((error) => {
            console.error("Error adding document: ", error);
          });
        }
      });
    });
  }
</code>```

My code is like this.
But when I sign in, querySnapshot.size is 0 and it add user`s data again and again even though there are already user data.

enter image description here
enter image description here

Like these, they have same uids but signing in made again and again.
Is there any problem when I program like this?

答:
I solved problem by result.additionalUserInfo.isNewUser.
This can check the user is first sign in.

```<code>auth.signInWithPopup(provider).then(result => {
        const user = result.user;
        const uid = user.uid;
        const name = user.displayName;
        const photoURL = user.photoURL;

        // push data when first sign in.
        console.log("first sign in user", result.additionalUserInfo.isNewUser);
        if (result.additionalUserInfo.isNewUser) {
            firestore.collection('Users').add({
                uid: uid,
                photoURL: photoURL,
                name: name,
            })
            .then((docRef) => {
                console.log("Document written with ID: ", docRef.id);
            })
            .catch((error) => {
                console.error("Error adding document: ", error);
            });
        }
    });
</code>```

Body:
unsubscribeFromAuth = null; //memory leak

  componentDidMount() {
    this.unsubscribeFromAuth = auth.onAuthStateChanged(user => {
      this.setState({ currentUser: user });
      if (user === null)
        return;

      // user data
      const uid = user.uid;
      const photoURL = user.photoURL;
      const name = user.displayName;

      const userRef = firestore.collection('Users');
      userRef.where('uid','==',uid).get().then((querySnapshot) => {
        console.log("uid size : ",querySnapshot.size);
        // add user extra data when first sign in.
        if (querySnapshot.size === 0) {
          firestore.collection('Users').add({
            uid: uid,
            photoURL: photoURL,
            name: name,
          })
          .then((docRef) => {
            console.log("Document written with ID: ", docRef.id);
          })
          .catch((error) => {
            console.error("Error adding document: ", error);
          });
        }
      });
    });
  }

My code is like this.
But when I sign in, querySnapshot.size is 0 and it add user`s data again and again even though there are already user data.

enter image description here
enter image description here

Like these, they have same uids but signing in made again and again.
Is there any problem when I program like this?

Body:
I solved problem by result.additionalUserInfo.isNewUser.
This can check the user is first sign in.

auth.signInWithPopup(provider).then(result => {
        const user = result.user;
        const uid = user.uid;
        const name = user.displayName;
        const photoURL = user.photoURL;

        // push data when first sign in.
        console.log("first sign in user", result.additionalUserInfo.isNewUser);
        if (result.additionalUserInfo.isNewUser) {
            firestore.collection('Users').add({
                uid: uid,
                photoURL: photoURL,
                name: name,
            })
            .then((docRef) => {
                console.log("Document written with ID: ", docRef.id);
            })
            .catch((error) => {
                console.error("Error adding document: ", error);
            });
        }
    });


问:
Does PyTorch have implicit functions for element-wise product and sum?
I am trying to implement RCAN for super resolution in Tensorflow by Yulun Zhang et al (the original code published with paper is implemented in PyTorch: https://github.com/yulunzhang/RCAN).

I am trying to understand how they have implemented RCAB. By looking at the diagram they have published of their network architecture, it seems pretty straight forward how the nueral network is built. But the code doesn't seem to match it.

According to the diagram here: https://raw.githubusercontent.com/yulunzhang/RCAN/master/Figs/RCAB.PNG

Each RCAB should have following structure:

```<code>Residual Channel Attention Block(RCAB){

--0) Conv2D
--1) Relu
--2) Conv2D
--3) Channel Attention Layer{
----0)Global pooling
----1)Conv2D
----2)Relu
----3)Conv2D
----4)Sigmoid
----5)Element Wise Product (Input of this layer/function would be the output from the Conv2D layer 3)
--}
--4) Element Wise Sum (Input of this layer/function would be the input of layer 1)
}
</code>```

However, when I print the PyTorch model in the paper's GitHub repo, RCAB looks like this:
(see https://github.com/yulunzhang/RCAN/blob/master/RCAN_TrainCode/experiment/model/Network_RCAN_BIX2_G10R20P48-2018-07-15-20-14-55.txt for the full printed model)

```<code>(0)RCAB(
          (body): Sequential(
            (0): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
            (1): ReLU(inplace)
            (2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
            (3): CALayer(
              (avg_pool): AdaptiveAvgPool2d(output_size=1)
              (conv_du): Sequential(
                (0): Conv2d(64, 4, kernel_size=(1, 1), stride=(1, 1))
                (1): ReLU(inplace)
                (2): Conv2d(4, 64, kernel_size=(1, 1), stride=(1, 1))
                (3): Sigmoid()
              )
            )
          )
        )
</code>```

There seems to be no mention of Element Wise sum and Element Wise product in the RCABs of the models that are published along the paper. Signmoid layer is the last layer in each RCAB.

So my question is: does Pytorch have some implicit way of declaring thes element wise sum/product layers? or is it the case that the publishers of the code/model simply haven't added any such layer and therefore have not followed the model architecture diagram that they published?

答:
If you look at their actual model file you can find the elementwise sum (implemented as just +): https://github.com/yulunzhang/RCAN/blob/master/RCAN_TrainCode/code/model/rcan.py

I believe the elementwise product is handled the same way. These are not exactly "part of the model" in the PyTorch sense. They are not created in __init__ and are kind of dynamic, only revealing its behavior during the forward pass. Static model analysis could not have revealed them (and thus not show in the txt).

Body:
I am trying to implement RCAN for super resolution in Tensorflow by Yulun Zhang et al (the original code published with paper is implemented in PyTorch: https://github.com/yulunzhang/RCAN).

I am trying to understand how they have implemented RCAB. By looking at the diagram they have published of their network architecture, it seems pretty straight forward how the nueral network is built. But the code doesn't seem to match it.

According to the diagram here: https://raw.githubusercontent.com/yulunzhang/RCAN/master/Figs/RCAB.PNG

Each RCAB should have following structure:

Residual Channel Attention Block(RCAB){

--0) Conv2D
--1) Relu
--2) Conv2D
--3) Channel Attention Layer{
----0)Global pooling
----1)Conv2D
----2)Relu
----3)Conv2D
----4)Sigmoid
----5)Element Wise Product (Input of this layer/function would be the output from the Conv2D layer 3)
--}
--4) Element Wise Sum (Input of this layer/function would be the input of layer 1)
}

However, when I print the PyTorch model in the paper's GitHub repo, RCAB looks like this:
(see https://github.com/yulunzhang/RCAN/blob/master/RCAN_TrainCode/experiment/model/Network_RCAN_BIX2_G10R20P48-2018-07-15-20-14-55.txt for the full printed model)

(0)RCAB(
          (body): Sequential(
            (0): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
            (1): ReLU(inplace)
            (2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
            (3): CALayer(
              (avg_pool): AdaptiveAvgPool2d(output_size=1)
              (conv_du): Sequential(
                (0): Conv2d(64, 4, kernel_size=(1, 1), stride=(1, 1))
                (1): ReLU(inplace)
                (2): Conv2d(4, 64, kernel_size=(1, 1), stride=(1, 1))
                (3): Sigmoid()
              )
            )
          )
        )

There seems to be no mention of Element Wise sum and Element Wise product in the RCABs of the models that are published along the paper. Signmoid layer is the last layer in each RCAB.

So my question is: does Pytorch have some implicit way of declaring thes element wise sum/product layers? or is it the case that the publishers of the code/model simply haven't added any such layer and therefore have not followed the model architecture diagram that they published?


问:
How to return 'year' from the date if the date format is (dd-mm-yyyy) in mysql

I am trying to show the dates in (YYYY-MM-DD) format which is stored in (DD-MM-YYYY) format in the table.

Also please explain how to use year() function on (DD-MM-YYYY) date format.

答:
assuming your data type is a string then you could use

for format(DD-MM-YYYY)

```<code> select year(str_to_date(yourcol, '%d-%m-%Y'))
</code>```

or for format (YYYY-MM-DD)

```<code> select year(str_to_date(yourcol, '%Y-%m-%d'))
</code>```

Body:
assuming your data type is a string then you could use

for format(DD-MM-YYYY)

 select year(str_to_date(yourcol, '%d-%m-%Y'))

or for format (YYYY-MM-DD)

 select year(str_to_date(yourcol, '%Y-%m-%d'))


问:
Flutter: Change Tab text dynamically
I am using tabcontroller and it is showing properly. I need to change the text of Tabs dynamically.

I tried searching the solution on Google and SO but so far no luck.

Here is the code.

```<code>    TabController _controller;
     @override
        void initState(){
           _controller = TabController(vsync: this, length: 4);
          _controller.addListener(_handleTabSelection);
         deviceInfo();
        super.initState();
        });

     @override
      void dispose() {
        controller.dispose();
        super.dispose();
      }

    TabBar(
               //  isScrollable: true,
               controller: _controller,
               unselectedLabelColor: Colors.redAccent,
               indicatorSize: TabBarIndicatorSize.label,
                 indicator: BoxDecoration(
                        gradient: LinearGradient(
                            colors: [Colors.redAccent, Colors.orangeAccent]),
                        borderRadius: BorderRadius.circular(50),
                        color: Colors.redAccent),
     tabs: [
                Tab(
                      child: Container(
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(50),
                            border: Border.all(color: Colors.redAccent, width: 1)),
                        child: Align(
                          alignment: Alignment.center,
                          child: Text("Near You",
                          style: TextStyle(

                            fontSize: 12
                          ),
                          ),
                        ),
                      ),
                    ),
                Tab(

                      child: Container(
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(50),
                            border: Border.all(color: Colors.redAccent, width: 1)),
                        child: Align(
                          alignment: Alignment.center,
                          child: Text("My State",
                          style: TextStyle(
                            fontSize: 12
                          ),
                          ),
                        ),
                      ),
                    ),

body:TabBarView(
          controller: _controller,
          children: [
            Text("TAB ONE CONTENT"),
            Text("TAB TWO CONTENT"),

          ],
          ),

_handleTabSelection() {

                   _currentIndex = _controller.index;
                    print(_currentIndex);

                     setState(() {
                  switch (_currentIndex) {
                    case 0:
                    ///Change the Tab Text

                      PrimaryColor= Color(0xffff5722);
                      SecColor= Color(0xff3f51b5);
                      break;
                      case 1:
                      PrimaryColor= Color(0xff3f51b5);
                      SecColor= Color(0xffff5722);
                      break;
</code>```

I have added the relevant code only in the question otherwise it would quite long.

I want to change the text of Tab dynamically like above you can see Near You and My State are the text. I need to change these. Any advise.

答:
Just Declare variables with default string which you want to show initially

```<code>String tab1 = "";
String tab2 = "";
</code>```

then used both string like

```<code>              Tab(
                  child: Container(
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(50),
                        border: Border.all(color: Colors.redAccent, width: 1)),
                    child: Align(
                      alignment: Alignment.center,
                      child: Text(tab1,
                      style: TextStyle(

                        fontSize: 12
                      ),
                      ),
                    ),
                  ),
                ),
            Tab(

                  child: Container(
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(50),
                        border: Border.all(color: Colors.redAccent, width: 1)),
                    child: Align(
                      alignment: Alignment.center,
                      child: Text(tab2,
                      style: TextStyle(
                        fontSize: 12
                      ),
                      ),
                    ),
                  ),
                ),
</code>```

Now, you can update the text dynamically with setState() whereever you want

```<code> setState(() {
          tab1 = "Change tab 1";
          tab2 = "Change tab 2";
    });
</code>```

Title: Flutter: Change Tab text dynamically

Body:
I am using tabcontroller and it is showing properly. I need to change the text of Tabs dynamically.

I tried searching the solution on Google and SO but so far no luck.

Here is the code.

    TabController _controller;
     @override
        void initState(){
           _controller = TabController(vsync: this, length: 4);
          _controller.addListener(_handleTabSelection);
         deviceInfo();
        super.initState();
        });

     @override
      void dispose() {
        controller.dispose();
        super.dispose();
      }

    TabBar(
               //  isScrollable: true,
               controller: _controller,
               unselectedLabelColor: Colors.redAccent,
               indicatorSize: TabBarIndicatorSize.label,
                 indicator: BoxDecoration(
                        gradient: LinearGradient(
                            colors: [Colors.redAccent, Colors.orangeAccent]),
                        borderRadius: BorderRadius.circular(50),
                        color: Colors.redAccent),
     tabs: [
                Tab(
                      child: Container(
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(50),
                            border: Border.all(color: Colors.redAccent, width: 1)),
                        child: Align(
                          alignment: Alignment.center,
                          child: Text("Near You",
                          style: TextStyle(

                            fontSize: 12
                          ),
                          ),
                        ),
                      ),
                    ),
                Tab(

                      child: Container(
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(50),
                            border: Border.all(color: Colors.redAccent, width: 1)),
                        child: Align(
                          alignment: Alignment.center,
                          child: Text("My State",
                          style: TextStyle(
                            fontSize: 12
                          ),
                          ),
                        ),
                      ),
                    ),

body:TabBarView(
          controller: _controller,
          children: [
            Text("TAB ONE CONTENT"),
            Text("TAB TWO CONTENT"),

          ],
          ),

_handleTabSelection() {

                   _currentIndex = _controller.index;
                    print(_currentIndex);

                     setState(() {
                  switch (_currentIndex) {
                    case 0:
                    ///Change the Tab Text

                      PrimaryColor= Color(0xffff5722);
                      SecColor= Color(0xff3f51b5);
                      break;
                      case 1:
                      PrimaryColor= Color(0xff3f51b5);
                      SecColor= Color(0xffff5722);
                      break;

I have added the relevant code only in the question otherwise it would quite long.

I want to change the text of Tab dynamically like above you can see Near You and My State are the text. I need to change these. Any advise.

Body:
Just Declare variables with default string which you want to show initially

String tab1 = "";
String tab2 = "";

then used both string like

              Tab(
                  child: Container(
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(50),
                        border: Border.all(color: Colors.redAccent, width: 1)),
                    child: Align(
                      alignment: Alignment.center,
                      child: Text(tab1,
                      style: TextStyle(

                        fontSize: 12
                      ),
                      ),
                    ),
                  ),
                ),
            Tab(

                  child: Container(
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(50),
                        border: Border.all(color: Colors.redAccent, width: 1)),
                    child: Align(
                      alignment: Alignment.center,
                      child: Text(tab2,
                      style: TextStyle(
                        fontSize: 12
                      ),
                      ),
                    ),
                  ),
                ),

Now, you can update the text dynamically with setState() whereever you want

 setState(() {
          tab1 = "Change tab 1";
          tab2 = "Change tab 2";
    });


问:
rel="canonical" html5 unable to validate
Should the link attribute rel="canonical" validate against html5?

It is the first time I am using this and I am getting the following validation errors:

"Bad value canonical for attribute rel on element link: Keyword canonical is not registered."

It kind of suggests it shouldnt although I cant find any concrete documentation on this.

Edit - Here is the line that is throwing the validator off:

```<code><link rel="canonical" href="http://dev.local/" />
</code>```

I have  tried it with and  without the closing slash

答:
There is no definition for the canonical rel in the HTML5 spec, but it does also say that:

The rel attribute has no default value. If the attribute is omitted or if none of the values in the attribute are recognized by the user agent, then the document has no particular relationship with the destination resource other than there being a hyperlink between the two.

So, it's not technically conforming HTML5, but it will simply be ignored by UAs which don't understand it.

Body:
Should the link attribute rel="canonical" validate against html5?

It is the first time I am using this and I am getting the following validation errors:

"Bad value canonical for attribute rel on element link: Keyword canonical is not registered."

It kind of suggests it shouldnt although I cant find any concrete documentation on this.

Edit - Here is the line that is throwing the validator off:

<link rel="canonical" href="http://dev.local/" />

I have  tried it with and  without the closing slash


问:
Find flutter sandwich menu button using flutter_driver
Find flutter sandwich menu button using flutter_driver

    Scaffold(
        key: widget.scaffoldKey,
        drawer: Observer(builder: (BuildContext context) {
          return DrawerMenu(
            user: controller.appStore.user,
            onTapLogout: controller.loginController.logout,
          );
        }),
        appBar: widget.appBar,
        body: widget.body);
```

<p>button to be identified</p>

<pre class="lang-dart prettyprint-override"><code>
 test('test by inserting valid username and login', () async {
      await driver.tap(buttonFinder);

      expect(await driver.getText(loginName), "LoginName");
    });
</code>```

答:
The sandwich menu you are referring to is called as Drawer, and you can tap on it using it's toolTip property.
If you long press on the drawer menu, it will show you a tooltip, as below:

Then, in your flutter driver test, you can identify this widget by declaring a finder using byToolTip method, as below:

final drawerFinder = find.byTooltip('Open navigation menu');

And then write your test as:

```<code>test('tap on drawer menu', () async {
        await driver.waitFor(drawerFinder);
        await driver.tap(drawerFinder);
        print('clicked on drawer');
      });
</code>```

Body:
Find flutter sandwich menu button using flutter_driver

    Scaffold(
        key: widget.scaffoldKey,
        drawer: Observer(builder: (BuildContext context) {
          return DrawerMenu(
            user: controller.appStore.user,
            onTapLogout: controller.loginController.logout,
          );
        }),
        appBar: widget.appBar,
        body: widget.body);

button to be identified

 test('test by inserting valid username and login', () async {
      await driver.tap(buttonFinder);

      expect(await driver.getText(loginName), "LoginName");
    });

Body:
The sandwich menu you are referring to is called as Drawer, and you can tap on it using it's toolTip property.
If you long press on the drawer menu, it will show you a tooltip, as below:

Then, in your flutter driver test, you can identify this widget by declaring a finder using byToolTip method, as below:

final drawerFinder = find.byTooltip('Open navigation menu');

And then write your test as:

test('tap on drawer menu', () async {
        await driver.waitFor(drawerFinder);
        await driver.tap(drawerFinder);
        print('clicked on drawer');
      });


问:
bash: g++: command not found in sublime text editor on mac
When I run the program so I get following text on my editor I set path but I did not get it whats I am doing wrong please provide the exact solution.

答:
The Sublime Text editor didn't find any G++ compiler in your machine.

You can install G++ compiler with the following command:

```<code>sudo apt-get install -y gcc-c++
</code>```

Body:
The Sublime Text editor didn't find any G++ compiler in your machine.

You can install G++ compiler with the following command:

sudo apt-get install -y gcc-c++


问:
Converting some text within an element to an element itself using JavaScript
Is this possible using JavaScript or JQuery, or anything else?

Say I have an HTML file like this

```<code><div>
    <p>Hello World</p>
</div>
</code>```

And I want to turn "World" into a span element itself, like so (so that I can style just "World")

```<code><div>
    <p>Hello <span>World</span></p>
</div>
</code>```

答:
Since there are a lot of unknowns in your question, so I am assuming that you already know the string/word around which you want to add the html tag.

So keeping that in mind, following solution should work:

HTML:

```<code><div>
    <p id="my-text">Hello World, Again!</p>
</div>
</code>```

JavaScript:

```<code>    const stringToBeReplaced = "World"; // what you want to replace
    const innerText = document.getElementById("my-text").innerText; //grab the text
    const beginIndex = innerText.indexOf(stringToBeReplaced); // get text where string begins

    // if string exists
    if (beginIndex >= 0) {
    const textWithTag =
              "<span style='color: red'>" + stringToBeReplaced + "</span>";
    const newString = innerText.replace(stringToBeReplaced, textWithTag);
    // replace the text with new string
    document.getElementById("my-text").innerHTML = newString;
   }
</code>```

Hope this is what you were asking and looking for.

Body:
Is this possible using JavaScript or JQuery, or anything else?

Say I have an HTML file like this

Hello World

And I want to turn "World" into a span element itself, like so (so that I can style just "World")

Hello World

Body:
Since there are a lot of unknowns in your question, so I am assuming that you already know the string/word around which you want to add the html tag.

So keeping that in mind, following solution should work:

HTML:

<div>
    <p id="my-text">Hello World, Again!</p>
</div>

JavaScript:

    const stringToBeReplaced = "World"; // what you want to replace
    const innerText = document.getElementById("my-text").innerText; //grab the text
    const beginIndex = innerText.indexOf(stringToBeReplaced); // get text where string begins

    // if string exists
    if (beginIndex >= 0) {
    const textWithTag =
              "<span style='color: red'>" + stringToBeReplaced + "</span>";
    const newString = innerText.replace(stringToBeReplaced, textWithTag);
    // replace the text with new string
    document.getElementById("my-text").innerHTML = newString;
   }

Hope this is what you were asking and looking for.


问:
Nuxt - Cannot remove Event Listener
I'm using nuxt.js and have a scroller that scrolls and stops at a fixed point on my page.

When I click to the next page, the method is still looking for the $ref=nav and is coming back undefined because it is not there anymore Cannot read property 'getBoundingClientRect' of undefined

I can add the eventListener but cannot remove the eventListener.

Listener

```<code>mounted(){
   window.addEventListener('scroll', this.stickyScroll);
},
beforeDestroy(){
   window.removeEventListener('scroll', this.stickyScroll);
}
</code>```

Scroller

```<code>stickyScroll(){
   window.document.onscroll = () => {
        let navBar = this.$refs.nav;
        let navBarXPosition = navBar.getBoundingClientRect().x;
        let navScrollSpy = this.$refs.navScrollSpy;
        let navScrollSpyXPosition = navScrollSpy.getBoundingClientRect().bottom;
        if(window.scrollY > navBarXPosition && navScrollSpyXPosition > 25){
             this.active = true;
         } else {
             this.active = false;
         }
    }
 },
</code>```

答:
window.document.onscroll = fn is effectively the same as window.addEventListener('scroll', fn), so stickyScroll() adds a new event listener for every scroll event.

The solution is to remove the setting of window.document.onscroll so that the contents of the arrow function becomes the contents of stickyScroll, which would allow the proper removal of the handler:

stickyScroll() {
  let navBar = this.$refs.nav;
  let navBarXPosition = navBar.getBoundingClientRect().x;
  let navScrollSpy = this.$refs.navScrollSpy;
  let navScrollSpyXPosition = navScrollSpy.getBoundingClientRect().bottom;
  if (window.scrollY > navBarXPosition && navScrollSpyXPosition > 25) {
    this.active = true;
  } else {
    this.active = false;
  }
}
```

Title: Nuxt - Cannot remove Event Listener

Body:
I'm using nuxt.js and have a scroller that scrolls and stops at a fixed point on my page.

When I click to the next page, the method is still looking for the $ref=nav and is coming back undefined because it is not there anymore Cannot read property 'getBoundingClientRect' of undefined

I can add the eventListener but cannot remove the eventListener.

Listener

mounted(){
   window.addEventListener('scroll', this.stickyScroll);
},
beforeDestroy(){
   window.removeEventListener('scroll', this.stickyScroll);
}

Scroller

stickyScroll(){
   window.document.onscroll = () => {
        let navBar = this.$refs.nav;
        let navBarXPosition = navBar.getBoundingClientRect().x;
        let navScrollSpy = this.$refs.navScrollSpy;
        let navScrollSpyXPosition = navScrollSpy.getBoundingClientRect().bottom;
        if(window.scrollY > navBarXPosition && navScrollSpyXPosition > 25){
             this.active = true;
         } else {
             this.active = false;
         }
    }
 },


问:
With set -e, exit status of command following ! is lost in an if block
```<code>set -e
if ! some_command; then
  RET=$?
  if [[ $RET == 255 ]]; then
    ...do something handling...
  fi
fi
</code>```

guess what happened?
the RET will always be 0, regardless the some_command returns non-zero value.

Is this by design? I can not believe it.

答:
As oguz ismail said, this is a result of ! -- since it converts failure status to success, and there's only one possible success status (zero), it necessarily loses the specific failure code. But you can do the equivalent of this without using !:

```<code>set -e
some_command || {
  RET=$?
  if [[ $RET == 255 ]]; then
    ...do something handling...
  fi
}
</code>```

Unlike the PIPESTATUS solution, this is portable to non-bash shells (it should work with any POSIX shell). (Although as oguz ismail pointed out, the [[ ]] conditional expression isn't portable -- the portable version would be if [ "$RET" = 255 ]; then.)

Body:
set -e
if ! some_command; then
  RET=$?
  if [[ $RET == 255 ]]; then
    ...do something handling...
  fi
fi

guess what happened?
the RET will always be 0, regardless the some_command returns non-zero value.

Is this by design? I can not believe it.

Body:
As oguz ismail said, this is a result of ! -- since it converts failure status to success, and there's only one possible success status (zero), it necessarily loses the specific failure code. But you can do the equivalent of this without using !:

set -e
some_command || {
  RET=$?
  if [[ $RET == 255 ]]; then
    ...do something handling...
  fi
}

Unlike the PIPESTATUS solution, this is portable to non-bash shells (it should work with any POSIX shell). (Although as oguz ismail pointed out, the [[ ]] conditional expression isn't portable -- the portable version would be if [ "$RET" = 255 ]; then.)


问:
Python - Iterating Through Multiple Dictionarys and Their Keys
I am attempting to create a program, where the user can input multiple lottery ticket numbers, and it will compare these numbers to a set of winning numbers. I know I can make it work by using several if statements, but I'm thinking there has to be a way to do this in a loop. I've tried a few loops that used "for key in ___", but I kept receiving errors.

amount = int(input('How many sets of numbers do you have?'))
tickets = {}
ticketMatch = {}
winingNumbers = {
    '1': '1',
    '2': '2',
    '3': '3',
    '4': '4',
    '5': '5',
    '6': '6',
}

for i in range (0, amount, 1):
    tickets[i] = {
        '1': input('Input #1 '),
        '2': input('Input #2 '),
        '3': input('Input #3 '),
        '4': input('Input #4 '),
        '5': input('Input #5 '),
        '6': input('Input Powerball '),
    }

for i in range (0, len(tickets), 1):
    ticketMatch[i] = 0
    if tickets[i]['1'] in winingNumbers.values():
        ticketMatch[i] += 1
    if tickets[i]['2'] in winingNumbers.values():
        ticketMatch[i] += 1
```

Any tips or hints would be greatly appreciated. Thanks!

答:
```<code>amount = int(input('How many sets of numbers do you have?'))
winingNumbers = {1, 2, 3, 4, 5, 6}
tickets = [set() for _ in range(amount)]
ticketMatch = []

for i in range(amount):
    for j in range(6):
        if j == 5:
            tickets[i].add(int(input("Input Powerball ")))
        else:
            tickets[i].add(int(input("Input #" + str(j + 1) + " ")))

for i in range(amount):
    ticketMatch.append(len(tickets[i] & winingNumbers))
</code>```

Body:
I am attempting to create a program, where the user can input multiple lottery ticket numbers, and it will compare these numbers to a set of winning numbers. I know I can make it work by using several if statements, but I'm thinking there has to be a way to do this in a loop. I've tried a few loops that used "for key in ___", but I kept receiving errors.

amount = int(input('How many sets of numbers do you have?'))
tickets = {}
ticketMatch = {}
winingNumbers = {
    '1': '1',
    '2': '2',
    '3': '3',
    '4': '4',
    '5': '5',
    '6': '6',
}

for i in range (0, amount, 1):
    tickets[i] = {
        '1': input('Input #1 '),
        '2': input('Input #2 '),
        '3': input('Input #3 '),
        '4': input('Input #4 '),
        '5': input('Input #5 '),
        '6': input('Input Powerball '),
    }

for i in range (0, len(tickets), 1):
    ticketMatch[i] = 0
    if tickets[i]['1'] in winingNumbers.values():
        ticketMatch[i] += 1
    if tickets[i]['2'] in winingNumbers.values():
        ticketMatch[i] += 1

Any tips or hints would be greatly appreciated. Thanks!


问:
Using Moq to verify calls are made in the correct order
I need to test the following method:

```<code>CreateOutput(IWriter writer)
{
    writer.Write(type);
    writer.Write(id);
    writer.Write(sender);

    // many more Write()s...
}
</code>```

I've created a Moq'd IWriter and I want to ensure that the Write() methods are called in the right order.

I have the following test code:

```<code>var mockWriter = new Mock<IWriter>(MockBehavior.Strict);
var sequence = new MockSequence();
mockWriter.InSequence(sequence).Setup(x => x.Write(expectedType));
mockWriter.InSequence(sequence).Setup(x => x.Write(expectedId));
mockWriter.InSequence(sequence).Setup(x => x.Write(expectedSender));
</code>```

However, the second call to Write() in CreateOutput() (to write the id value) throws a MockException with the message "IWriter.Write() invocation failed with mock behavior Strict. All invocations on the mock must have a corresponding setup.".

I'm also finding it hard to find any definitive, up-to-date documentation/examples of Moq sequences.

Am I doing something wrong, or can I not set up a sequence using the same method?
If not, is there an alternative I can use (preferably using Moq/NUnit)?

答:
My scenario was methods without parameters:

```<code>public interface IWriter
    {
    void WriteA ();
    void WriteB ();
    void WriteC ();
    }
</code>```

So I used Invocations property on the Mock to compare what was called:

```<code>var writer = new Mock<IWriter> ();

new SUT (writer.Object).Run ();

Assert.Equal (
    writer.Invocations.Select (invocation => invocation.Method.Name),
    new[]
        {
        nameof (IWriter.WriteB),
        nameof (IWriter.WriteA),
        nameof (IWriter.WriteC),
        });
</code>```

You could also append the invocation.Arguments to check method calls with parameters.

Also the failure message is more clear than just expected 1 but was 5:

```<code>    expected
["WriteB", "WriteA", "WriteC"]
    but was
["WriteA", "WriteB"]
</code>```

Body:
I need to test the following method:

CreateOutput(IWriter writer)
{
    writer.Write(type);
    writer.Write(id);
    writer.Write(sender);

    // many more Write()s...
}

I've created a Moq'd IWriter and I want to ensure that the Write() methods are called in the right order.

I have the following test code:

var mockWriter = new Mock<IWriter>(MockBehavior.Strict);
var sequence = new MockSequence();
mockWriter.InSequence(sequence).Setup(x => x.Write(expectedType));
mockWriter.InSequence(sequence).Setup(x => x.Write(expectedId));
mockWriter.InSequence(sequence).Setup(x => x.Write(expectedSender));

However, the second call to Write() in CreateOutput() (to write the id value) throws a MockException with the message "IWriter.Write() invocation failed with mock behavior Strict. All invocations on the mock must have a corresponding setup.".

I'm also finding it hard to find any definitive, up-to-date documentation/examples of Moq sequences.

Am I doing something wrong, or can I not set up a sequence using the same method?
If not, is there an alternative I can use (preferably using Moq/NUnit)?

Body:
My scenario was methods without parameters:

public interface IWriter
    {
    void WriteA ();
    void WriteB ();
    void WriteC ();
    }

So I used Invocations property on the Mock to compare what was called:

var writer = new Mock<IWriter> ();

new SUT (writer.Object).Run ();

Assert.Equal (
    writer.Invocations.Select (invocation => invocation.Method.Name),
    new[]
        {
        nameof (IWriter.WriteB),
        nameof (IWriter.WriteA),
        nameof (IWriter.WriteC),
        });

You could also append the invocation.Arguments to check method calls with parameters.

Also the failure message is more clear than just expected 1 but was 5:

    expected
["WriteB", "WriteA", "WriteC"]
    but was
["WriteA", "WriteB"]


问:
cocos2d coordinates system
```<code>        CCLabelTTF *label = [CCLabelTTF labelWithString:@"Score : #" fontName:@"Arial" fontSize:14];

        // ask director the the window size
        CGSize size = [[CCDirector sharedDirector] winSize];

        // position the label on the center of the screen
        label.position =  ccp( size.width + 0, size.height + 0 );

        // add the label as a child to this Layer
        [self addChild: label];

        label.position =  ccp( size.width + 0, size.height + 0 );
</code>```

how would i get that label in the bottom left corner. I do not understand the coordinates system very well. From what I understand Y is bottom. X is far left. so how come when I use that code, the position of the label is top right. My application is portrait.

Also would it better to have the label as a sprite, or just keep it like that. ( its to hold a score )

答:
In codos2d, the point (0,0) is the bottom left corner of the screen. Think of it as quadrant 1 on a x,y plane where x increases as you go right, and y increases as you go up.

So to get the label in the bottom left just do label.position = ccp(0, 0); but this might be the default so you might not have to do anything.

Title: cocos2d coordinates system

Body:
        CCLabelTTF *label = [CCLabelTTF labelWithString:@"Score : #" fontName:@"Arial" fontSize:14];

        // ask director the the window size
        CGSize size = [[CCDirector sharedDirector] winSize];

        // position the label on the center of the screen
        label.position =  ccp( size.width + 0, size.height + 0 );

        // add the label as a child to this Layer
        [self addChild: label];

        label.position =  ccp( size.width + 0, size.height + 0 );

how would i get that label in the bottom left corner. I do not understand the coordinates system very well. From what I understand Y is bottom. X is far left. so how come when I use that code, the position of the label is top right. My application is portrait.

Also would it better to have the label as a sprite, or just keep it like that. ( its to hold a score )


问:
Multiple NodeJS instance on Azure App Service
As captioned, can I run multiple NodeJS instances in a single Azure App Services?

e.g.:

```<code>wwwroot/node1/xxx
wwwroot/node2/yyy
</code>```

So, when I access xx.xx/note1/** it will go to node 1 instance.

As I don't want to huge NodeJS project and would like to break into multiple small projects, but using a single App Services.

From the Azure DevOps pipeline seems there is no way to allow me to deploy NodeJS other than the root folder, i.e. wwwroot/.

答:
You have two options.

First, deploy multiple apps to single web app using Virtual directory. In this case you will have https://yourdomain/app1, https://yourdomain/app2. Go to you App Service -> Configuration -> Path Mappings

When you deploy you will need to specify VirtualApplication for you application this will let to deploy in correct folder.

Second, you can have multiple Web Apps under single App Service Plan in this case it will be more isolated but still will pay same price as in first option. But you will have two different Web Apps, With two different url

Body:
As captioned, can I run multiple NodeJS instances in a single Azure App Services?

e.g.:

wwwroot/node1/xxx
wwwroot/node2/yyy

So, when I access xx.xx/note1/** it will go to node 1 instance.

As I don't want to huge NodeJS project and would like to break into multiple small projects, but using a single App Services.

From the Azure DevOps pipeline seems there is no way to allow me to deploy NodeJS other than the root folder, i.e. wwwroot/.


问:
For input string: "Mat [ 0*0*CV_32FC1, isCont=true, isSubmat=false, nativeObj=0x78a0dff700, dataAddr=0x0 ]" - Error filling matrix
I am working with opencv on android for the development of an image segmentation application, but with the watershed algorithm. I am opening an image and creating a mask with the same image size and passing 0 for all the rows and columns of that mask. However, in the next step, which is to go through an array of 0 and add as coordinates in that array, I have the error:

```<code>java.lang.NumberFormatException: For input string: "Mat [0 * 0 * CV_32FC1, isCont = true, isSubmat = false, nativeObj = 0x78a0dff700, dataAddr = 0x0] "
</code>```

With that, it is not possible to pass the new values to an array, can someone help me with this?

Code:

```<code>// Load the image
val srcOriginal = Imgcodecs.imread(currentPhotoPath)

// Create a blank image of zeros (same dimension as img)
val markers = Mat.zeros(srcOriginal.rows(), srcOriginal.cols(), CvType.CV_32F)

// Example assigning a new value to a matrix index
for (i in 0 until markers.toInt()) {
   markers.put(my_canvas.pointsToDrawY.get(i).toInt(), my_canvas.pointsToDrawY.get(i).toInt(), intArrayOf(0,0,255))
}
</code>```

Error:

答:
So I finally understood the problem. The line

Mat.zeros(srcOriginal.rows(), srcOriginal.cols(), CvType.CV_32F)
```

<p>says to create a Mat of <code>srcOriginal.rows()</code> by <code>srcOriginal.cols()</code> pixels.</p>

<p>Now you have to loop through it rows and columns to set their color values in RGB. In other words you have to set all the column values for 0th row, then all the column values for 1st row, and so on.</p>

<p>So you have to loop twice, one for row and one for column. You can either use two for loops. I'll extract them into an inline function so that they will be easier to manage afterwards.</p>

<pre class="lang-kotlin prettyprint-override"><code>// function declaration toplevel / or in class
inline fun loopThrough(rows: Int, cols: Int, block: (Int, Int) -> Unit) {
    for(r in 0 until rows) {
        for (c in 0 until cols) block(r, c)
    }
}

// code here
val rows = srcOriginal.rows()
val cols = srcOriginal.cols()
val markers = Mat.zeros(rows, cols, CvType.CV_32F)

loopThrough(rows, cols) { row, col ->
   markers.put(row, col, intArrayOf(0,0,255))
}
</code>```

Body:
I am working with opencv on android for the development of an image segmentation application, but with the watershed algorithm. I am opening an image and creating a mask with the same image size and passing 0 for all the rows and columns of that mask. However, in the next step, which is to go through an array of 0 and add as coordinates in that array, I have the error:

java.lang.NumberFormatException: For input string: "Mat [0 * 0 * CV_32FC1, isCont = true, isSubmat = false, nativeObj = 0x78a0dff700, dataAddr = 0x0] "

With that, it is not possible to pass the new values to an array, can someone help me with this?

Code:

// Load the image
val srcOriginal = Imgcodecs.imread(currentPhotoPath)

// Create a blank image of zeros (same dimension as img)
val markers = Mat.zeros(srcOriginal.rows(), srcOriginal.cols(), CvType.CV_32F)

// Example assigning a new value to a matrix index
for (i in 0 until markers.toInt()) {
   markers.put(my_canvas.pointsToDrawY.get(i).toInt(), my_canvas.pointsToDrawY.get(i).toInt(), intArrayOf(0,0,255))
}

Error:

Body:
So I finally understood the problem. The line

Mat.zeros(srcOriginal.rows(), srcOriginal.cols(), CvType.CV_32F)

says to create a Mat of srcOriginal.rows() by srcOriginal.cols() pixels.

Now you have to loop through it rows and columns to set their color values in RGB. In other words you have to set all the column values for 0th row, then all the column values for 1st row, and so on.

So you have to loop twice, one for row and one for column. You can either use two for loops. I'll extract them into an inline function so that they will be easier to manage afterwards.

// function declaration toplevel / or in class
inline fun loopThrough(rows: Int, cols: Int, block: (Int, Int) -> Unit) {
    for(r in 0 until rows) {
        for (c in 0 until cols) block(r, c)
    }
}

// code here
val rows = srcOriginal.rows()
val cols = srcOriginal.cols()
val markers = Mat.zeros(rows, cols, CvType.CV_32F)

loopThrough(rows, cols) { row, col ->
   markers.put(row, col, intArrayOf(0,0,255))
}


问:
Storing List Variable on change
I am learning Flutter currently and was making a personal finance app. I have the option to bookmark my guides and then view them on the bookmark tab. Right now, I am using a list to simply store names of guides and display them as list tiles.

The issue I am having is that whenever the bookmark list is updated WHILE the app is running, the Bookmarks page loads the right info but then when I close and restart the app, it goes back to it's initial state of being empty. How can I fix it so that the app saves bookmarked tabs?

main.dart

```<code>List<String> bookmarked = [];

String introInfo = """ <h1>Introduction!</h1>
<p><strong><em>NOTE: The guides are U.S. specific but most information can be applied in most countries outside the U.S.</em></strong></p>
<p>The guides in this app will teach you the basics of personal finance.</p>
<p>Financial knowledge is something that is invaluable but the U.S. education system does not put much emphasis on it. If you are looking to get into personal finance, you're at the right place.</p>""";

void main() {
  runApp(MaterialApp(
    initialRoute: '/',
    routes: {
      '/': (context) => MyApp(),
      '/finTable': (context) => FinNav(),
      '/disclaimer': (context) => Disclaimer(),
      '/intro': (context) => GuideStyle(guideName: 'introduction',guideInfo: introInfo, isFav: bookmarked.contains('introduction'),),
      '/budget': (context) => GuideStyle(guideName: 'budget',guideInfo: introInfo, isFav: bookmarked.contains('budget'),),
      '/bookmark': (context) => Bookmarks(),
    },
    theme: ThemeData(fontFamily: 'Raleway'),
  ));
}

/* I have a stateless widget that shows all pages and navigates to one the user selects */
</code>```

guidestyle.dart

```<code>class GuideStyle extends StatelessWidget {
  String guideName;
  String guideInfo;
  Widget previous;
  Widget next;
  bool isFav;
  GuideStyle({this.guideName,this.guideInfo, this.isFav });//this.next, this.previous});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          backgroundColor: Color.fromRGBO(220, 20, 60, 1.0),
          title: Text('Introduction'),
          centerTitle: true,
          elevation: 10.0,
          actions: <Widget>[
            Padding(
              padding: const EdgeInsets.fromLTRB(0.0,2.0,50.0,0.0),
              child: MyStatefulWidget(isFav: isFav,name: guideName,),
            ),
          ],
        ),
        body: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.all(10.0),
              child: RaisedButton(
                onPressed: () {
                  Navigator.pop(context);
                },
                child: Text('Back'),
                textColor: Colors.white,
                color: Color.fromRGBO(220, 20, 60, 0.8),
              ),
            ),
            Expanded(
              child: SingleChildScrollView(
                child: Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: HtmlWidget(
                    guideInfo,
                  )
                ),
              ),
            ),
          ],
        ));
  }
}

class MyStatefulWidget extends StatefulWidget {
  bool isFav;
  String name;
  MyStatefulWidget({Key key, this.isFav, this.name}) : super(key: key);

  @override
  _MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}

class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[
        IconButton(
          icon: widget.isFav ? Icon(Icons.bookmark, color: Colors.black) : Icon(Icons.bookmark_border),
          onPressed: () {
            setState(() {
              widget.isFav = !widget.isFav;
              if(widget.isFav){
                bookmarked.add(widget.name);
                bookmarked = bookmarked;
              }else{
                bookmarked.remove(widget.name);
                bookmarked = bookmarked;
              }
            });
          },
        ),
      ],
    );
  }
}
</code>```

As mentioned, the guidestyle.dart updates the list while the app is running but the list is reset when the app is restarted.

I was looking into using sqflite but it seems overkill so I am unsure about my other options. Any help would be appreciated!

答:
List<String> bookmarked = []; this always init your data empty

First, You need store package shared_preferences or sqflite or etc..

You can find here => https://pub.dev/

and then check data exist.

After, if(hasData) bookmarked = "loaded data" else bookmarked = [];

Title: Storing List Variable on change

Body:
I am learning Flutter currently and was making a personal finance app. I have the option to bookmark my guides and then view them on the bookmark tab. Right now, I am using a list to simply store names of guides and display them as list tiles.

The issue I am having is that whenever the bookmark list is updated WHILE the app is running, the Bookmarks page loads the right info but then when I close and restart the app, it goes back to it's initial state of being empty. How can I fix it so that the app saves bookmarked tabs?

main.dart

List<String> bookmarked = [];

String introInfo = """
Introduction!

NOTE: The guides are U.S. specific but most information can be applied in most countries outside the U.S.

The guides in this app will teach you the basics of personal finance.

Financial knowledge is something that is invaluable but the U.S. education system does not put much emphasis on it. If you are looking to get into personal finance, you're at the right place.
""";

void main() {
  runApp(MaterialApp(
    initialRoute: '/',
    routes: {
      '/': (context) => MyApp(),
      '/finTable': (context) => FinNav(),
      '/disclaimer': (context) => Disclaimer(),
      '/intro': (context) => GuideStyle(guideName: 'introduction',guideInfo: introInfo, isFav: bookmarked.contains('introduction'),),
      '/budget': (context) => GuideStyle(guideName: 'budget',guideInfo: introInfo, isFav: bookmarked.contains('budget'),),
      '/bookmark': (context) => Bookmarks(),
    },
    theme: ThemeData(fontFamily: 'Raleway'),
  ));
}

/* I have a stateless widget that shows all pages and navigates to one the user selects */

guidestyle.dart

class GuideStyle extends StatelessWidget {
  String guideName;
  String guideInfo;
  Widget previous;
  Widget next;
  bool isFav;
  GuideStyle({this.guideName,this.guideInfo, this.isFav });//this.next, this.previous});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          backgroundColor: Color.fromRGBO(220, 20, 60, 1.0),
          title: Text('Introduction'),
          centerTitle: true,
          elevation: 10.0,
          actions: <Widget>[
            Padding(
              padding: const EdgeInsets.fromLTRB(0.0,2.0,50.0,0.0),
              child: MyStatefulWidget(isFav: isFav,name: guideName,),
            ),
          ],
        ),
        body: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.all(10.0),
              child: RaisedButton(
                onPressed: () {
                  Navigator.pop(context);
                },
                child: Text('Back'),
                textColor: Colors.white,
                color: Color.fromRGBO(220, 20, 60, 0.8),
              ),
            ),
            Expanded(
              child: SingleChildScrollView(
                child: Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: HtmlWidget(
                    guideInfo,
                  )
                ),
              ),
            ),
          ],
        ));
  }
}

class MyStatefulWidget extends StatefulWidget {
  bool isFav;
  String name;
  MyStatefulWidget({Key key, this.isFav, this.name}) : super(key: key);

  @override
  _MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}

class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[
        IconButton(
          icon: widget.isFav ? Icon(Icons.bookmark, color: Colors.black) : Icon(Icons.bookmark_border),
          onPressed: () {
            setState(() {
              widget.isFav = !widget.isFav;
              if(widget.isFav){
                bookmarked.add(widget.name);
                bookmarked = bookmarked;
              }else{
                bookmarked.remove(widget.name);
                bookmarked = bookmarked;
              }
            });
          },
        ),
      ],
    );
  }
}

As mentioned, the guidestyle.dart updates the list while the app is running but the list is reset when the app is restarted.

I was looking into using sqflite but it seems overkill so I am unsure about my other options. Any help would be appreciated!


问:
Adding hive jars permanently
Is there any way I can add hive jars permanently instead of adding at session level in hive shell?

Any help would be appreciated

答: create directory named auxlib in $HIVE_HOME, put all your jars in this directory and restart the hive server. run ps -ef | grep hive this command to list hive processes, search for hive.aux.jars.path and you will see that all your jars will be listed against this hiveconf.

Title: Adding hive jars permanently