问:
How to make this simple function more efficient?
I have data on wages and about 95% of them are given in hourly format, however some of them are given as an annual salary. So I made a function to convert the annual salaries to hourly, however it takes 1 min 40 sec to run, when my dataset is 43000 rows x 12 columns (which I didnt think would be too big) so I did not think it would take this long.

I am curious if there is a better way to do this than the current function I have created. I am new with dplyr and tidyverse so ideally an answer using those capabilities.

Here is some sample data:

```<code>NOC4  Region Region_Name Wage_2012 Wage_2013 Wage_2014
0011  ER10   National    28.1      65000     NA
0011  ER1010 Northern    NA        30.5      18
0011  ER1020 Southern    42.3      72000     22
0011  ER1030 Eastern     12        NA        45500
0011  ER1040 Western     8         NA        99000
0011  ER10   National    NA        65000     NA
</code>```

Here is what it should look like after the function:

```<code>NOC4  Region Region_Name Wage_2012 Wage_2013 Wage_2014
0011  ER10   National    28.1      33.33     NA
0011  ER1010 Northern    NA        30.5      18
0011  ER1020 Southern    42.3      36.92     22
0011  ER1030 Eastern     12        NA        23.33
0011  ER1040 Western     8         NA        50.77
0011  ER10   National    NA        33.33     NA
</code>```

Here is the function:

```<code>year_to_hour <- function(dataset, salary, startcol){
  # where "startcol" should be the first column containing the numeric
  # values that you are trying to convert.
  for(i in startcol:ncol(dataset)){

    for(j in 1:nrow(dataset)){

      if(is.na(dataset[j, i])){

        j = j+1

      }else if(as.numeric(dataset[j, i]) >= as.numeric(salary)){

        dataset[j, i] = dataset[j, i]/1950
      }
      else{

        dataset[j, i] = dataset[j, i]

      }

    }

  }

  return(as_tibble(dataset))

}

converted <- year_to_hour(wage_data_messy, 1000, 4)
</code>```

答:
Using dplyr I would use mutate_if

```<code>salary <- 1000
df %>% mutate_if(is.numeric, ~ifelse(. > salary, ./1950, .))
</code>```

Body:
I have data on wages and about 95% of them are given in hourly format, however some of them are given as an annual salary. So I made a function to convert the annual salaries to hourly, however it takes 1 min 40 sec to run, when my dataset is 43000 rows x 12 columns (which I didnt think would be too big) so I did not think it would take this long.

I am curious if there is a better way to do this than the current function I have created. I am new with dplyr and tidyverse so ideally an answer using those capabilities.

Here is some sample data:

NOC4  Region Region_Name Wage_2012 Wage_2013 Wage_2014
0011  ER10   National    28.1      65000     NA
0011  ER1010 Northern    NA        30.5      18
0011  ER1020 Southern    42.3      72000     22
0011  ER1030 Eastern     12        NA        45500
0011  ER1040 Western     8         NA        99000
0011  ER10   National    NA        65000     NA

Here is what it should look like after the function:

NOC4  Region Region_Name Wage_2012 Wage_2013 Wage_2014
0011  ER10   National    28.1      33.33     NA
0011  ER1010 Northern    NA        30.5      18
0011  ER1020 Southern    42.3      36.92     22
0011  ER1030 Eastern     12        NA        23.33
0011  ER1040 Western     8         NA        50.77
0011  ER10   National    NA        33.33     NA

Here is the function:

year_to_hour <- function(dataset, salary, startcol){
  # where "startcol" should be the first column containing the numeric
  # values that you are trying to convert.
  for(i in startcol:ncol(dataset)){

    for(j in 1:nrow(dataset)){

      if(is.na(dataset[j, i])){

        j = j+1

      }else if(as.numeric(dataset[j, i]) >= as.numeric(salary)){

        dataset[j, i] = dataset[j, i]/1950
      }
      else{

        dataset[j, i] = dataset[j, i]

      }

    }

  }

  return(as_tibble(dataset))

}

converted <- year_to_hour(wage_data_messy, 1000, 4)

Body:
Using dplyr I would use mutate_if

salary <- 1000
df %>% mutate_if(is.numeric, ~ifelse(. > salary, ./1950, .))


来源: stackexchange

问:
Python Toggle between two class implementations clean code
I would like toggle between two implementations of the same class depending on an environment variable in the os.
one of the cases I would like to use it, it to toggle between logging to a remote server and logging into a local disk.

what I have so far is the following implementation:

```<code>import abc
class AbstractLogger(object):

    @abc.abstractmethod
    def log(message):
        pass

class LocalLogger(AbstractLogger):

    def __init__(self):
     # open file here

    def log(self, message):
        print('write to file')

class RemoteLogger(AbstractLogger):

     def __init__(self):
        # open socket here

    def log(self, message):
        print('write to socket')

import os
class mode(object):
is_local=os.getenv('key')
    mylogger=None

@staticmethod
def get_logger():
  if mode.is_local and mode.logger is None:
      mode.mylogger=LocalLogger()
  else:
      mode.logger=RemoteLogger()
  return mode.mylogger
</code>```

then the usage of my code will be like this:

```<code>from mode import mode
mode.get_logger().log('write this')
</code>```

or

```<code>from mode import mode
logging=mode.get_logger()
logging.log('write this')
</code>```

That code is not clean especially when we consider I would write this every couple of rows at every class in my project, my best wish is to use it like this:

```<code>import mode
mode.log('joy')
</code>```

any ideas?

答:
So after research on how python logging works I come out with a solution.

all class stays the same but class mode which removed, and mode.py file is:

```<code>import os

mylogger=LocalLogger() if os.getenv('key')=='value' else RemoteLogger()

@staticmethod
def log(message):
    mylogger.log(message)
</code>```

then I can do:

```<code>import mode
mode.log('joy')
</code>```

any thoughts?

ContentLicense: CC BY-SA 4.0

Body:
I would like toggle between two implementations of the same class depending on an environment variable in the os.
one of the cases I would like to use it, it to toggle between logging to a remote server and logging into a local disk.

what I have so far is the following implementation:

import abc
class AbstractLogger(object):

    @abc.abstractmethod
    def log(message):
        pass

class LocalLogger(AbstractLogger):

    def __init__(self):
     # open file here

    def log(self, message):
        print('write to file')

class RemoteLogger(AbstractLogger):

     def __init__(self):
        # open socket here

    def log(self, message):
        print('write to socket')

import os
class mode(object):
is_local=os.getenv('key')
    mylogger=None

@staticmethod
def get_logger():
  if mode.is_local and mode.logger is None:
      mode.mylogger=LocalLogger()
  else:
      mode.logger=RemoteLogger()
  return mode.mylogger

then the usage of my code will be like this:

from mode import mode
mode.get_logger().log('write this')

or

from mode import mode
logging=mode.get_logger()
logging.log('write this')

That code is not clean especially when we consider I would write this every couple of rows at every class in my project, my best wish is to use it like this:

import mode
mode.log('joy')

any ideas?

Body:
So after research on how python logging works I come out with a solution.

all class stays the same but class mode which removed, and mode.py file is:

import os

mylogger=LocalLogger() if os.getenv('key')=='value' else RemoteLogger()

@staticmethod
def log(message):
    mylogger.log(message)

then I can do:

import mode
mode.log('joy')

any thoughts?


问:
Avoid table scan and use index instead in query
I am designing a new database and have noticed my queries are not scaling as well as they should be. When my aggregations involve hundreds of records I am seeing significant increases in response times. I am wondering if my query is deeply flawed or if I am just not using the right index.

I have done a lot of tweaking to my query but have not come up with a way to eliminate doing a full table scan and instead use an index. When I use a tool similar to EXPLAIN on my query I see the following:

Full table scans are generally inefficient, avoid using them.

Your query uses MySQL's 'filesort' operation. This tends to slow down queries.

Your query uses MySQL's temporary tables. This can require extra I/O and tends to slow down queries.

Table:

```<code>CREATE TABLE `indexTable` (
  `id` int(10) unsigned NOT NULL,
  `userId` int(10) unsigned NOT NULL,
  `col1` varbinary(320) NOT NULL,
  `col2` tinyint(3) unsigned NOT NULL,
  `col3` tinyint(3) unsigned NOT NULL,
  `createdAt` bigint(20) unsigned NOT NULL,
  `updatedAt` bigint(20) unsigned NOT NULL,
  `metadata` json NOT NULL,
  PRIMARY KEY (`id`,`userId`,`col1`,`col2`,`col3`),
  KEY `createdAt` (`createdAt`),
  KEY `id_userId_col1_col2_createdAt` (`id`,`userId`,`col1`,`col2`,`createdAt`),
  KEY `col1_col2_createdAt` (`col1`,`col2`,`createdAt`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ROW_FORMAT=COMPRESSED KEY_BLOCK_SIZE=8
</code>```

Query:

```<code>SELECT t1.id, t1.userId, t1.col1, t1.col2, t1.col3, t1.metadata
FROM indexTable as t1
INNER JOIN(
    SELECT col1, col2, MAX(createdAt) AS maxCreatedAt
    FROM indexTable
    WHERE id = ? AND userId = ?
    GROUP BY col1, col2
    ORDER BY maxCreatedAt
    LIMIT 10 OFFSET 0) AS sub
ON t1.col1 = sub.col1
AND t1.col2 = sub.col2
AND t1.createdAt = sub.maxCreatedAt
WHERE t1.id = ? AND t1.userId = ?
ORDER BY t1.createdAt;
</code>```

PK: id, userId, col1, col2, col3
Index: createdAt

Explain:

```<code>{
  "query_block": {
    "select_id": 1,
    "cost_info": {
      "query_cost": "34.50"
    },
    "ordering_operation": {
      "using_temporary_table": true,
      "using_filesort": true,
      "cost_info": {
        "sort_cost": "10.00"
      },
      "nested_loop": [
        {
          "table": {
            "table_name": "sub",
            "access_type": "ALL",
            "rows_examined_per_scan": 10,
            "rows_produced_per_join": 10,
            "filtered": "100.00",
            "cost_info": {
              "read_cost": "10.50",
              "eval_cost": "2.00",
              "prefix_cost": "12.50",
              "data_read_per_join": "3K"
            },
            "used_columns": [
              "col1",
              "col2",
              "maxCreatedAt"
            ],
            "attached_condition": "(`sub`.`maxCreatedAt` is not null)",
            "materialized_from_subquery": {
              "using_temporary_table": true,
              "dependent": false,
              "cacheable": true,
              "query_block": {
                "select_id": 2,
                "cost_info": {
                  "query_cost": "10.27"
                },
                "ordering_operation": {
                  "using_filesort": true,
                  "grouping_operation": {
                    "using_temporary_table": true,
                    "using_filesort": false,
                    "table": {
                      "table_name": "indexTable",
                      "access_type": "ref",
                      "possible_keys": [
                        "PRIMARY",
                        "createdAt",
                        "id_userId_col1_col2_createdAt",
                        "col1_col2_createdAt"
                      ],
                      "key": "PRIMARY",
                      "used_key_parts": [
                        "id",
                        "userId"
                      ],
                      "key_length": "8",
                      "ref": [
                        "const",
                        "const"
                      ],
                      "rows_examined_per_scan": 46,
                      "rows_produced_per_join": 46,
                      "filtered": "100.00",
                      "cost_info": {
                        "read_cost": "1.07",
                        "eval_cost": "9.20",
                        "prefix_cost": "10.27",
                        "data_read_per_join": "16K"
                      },
                      "used_columns": [
                        "id",
                        "userId",
                        "createdAt",
                        "col1",
                        "col2",
                        "col3"
                      ],
                      "attached_condition": "((`MyDB`.`indexTable`.`id` <=> 53) and (`MyDB`.`indexTable`.`userId` <=> 549814))"
                    }
                  }
                }
              }
            }
          }
        },
        {
          "table": {
            "table_name": "t1",
            "access_type": "ref",
            "possible_keys": [
              "PRIMARY",
              "createdAt",
              "id_userId_col1_col2_createdAt",
              "col1_col2_createdAt"
            ],
            "key": "id_userId_col1_col2_createdAt",
            "used_key_parts": [
              "id",
              "userId",
              "col1",
              "col2",
              "createdAt"
            ],
            "key_length": "339",
            "ref": [
              "const",
              "const",
              "sub.col1",
              "sub.col2",
              "sub.maxCreatedAt"
            ],
            "rows_examined_per_scan": 1,
            "rows_produced_per_join": 10,
            "filtered": "100.00",
            "cost_info": {
              "read_cost": "10.00",
              "eval_cost": "2.00",
              "prefix_cost": "24.50",
              "data_read_per_join": "3K"
            },
            "used_columns": [
              "id",
              "userId",
              "createdAt",
              "updatedAt",
              "col1",
              "col2",
              "col3",
              "metadata",
            ]
          }
        }
      ]
    }
  }
}
</code>```

This query finds the most recent record in the grouping of col1 and col2, orders by createdAt, and limits the entries to 10.

答: I was able to solve this issue by updating my query to include id and userId in the GROUP BY. I was then able to join on the two additional columns and for some reason that made MySQL use the right index.

Body:
I am designing a new database and have noticed my queries are not scaling as well as they should be. When my aggregations involve hundreds of records I am seeing significant increases in response times. I am wondering if my query is deeply flawed or if I am just not using the right index.

I have done a lot of tweaking to my query but have not come up with a way to eliminate doing a full table scan and instead use an index. When I use a tool similar to EXPLAIN on my query I see the following:

Full table scans are generally inefficient, avoid using them.

Your query uses MySQL's 'filesort' operation. This tends to slow down queries.

Your query uses MySQL's temporary tables. This can require extra I/O and tends to slow down queries.

Table:

CREATE TABLE `indexTable` (
  `id` int(10) unsigned NOT NULL,
  `userId` int(10) unsigned NOT NULL,
  `col1` varbinary(320) NOT NULL,
  `col2` tinyint(3) unsigned NOT NULL,
  `col3` tinyint(3) unsigned NOT NULL,
  `createdAt` bigint(20) unsigned NOT NULL,
  `updatedAt` bigint(20) unsigned NOT NULL,
  `metadata` json NOT NULL,
  PRIMARY KEY (`id`,`userId`,`col1`,`col2`,`col3`),
  KEY `createdAt` (`createdAt`),
  KEY `id_userId_col1_col2_createdAt` (`id`,`userId`,`col1`,`col2`,`createdAt`),
  KEY `col1_col2_createdAt` (`col1`,`col2`,`createdAt`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ROW_FORMAT=COMPRESSED KEY_BLOCK_SIZE=8

Query:

SELECT t1.id, t1.userId, t1.col1, t1.col2, t1.col3, t1.metadata
FROM indexTable as t1
INNER JOIN(
    SELECT col1, col2, MAX(createdAt) AS maxCreatedAt
    FROM indexTable
    WHERE id = ? AND userId = ?
    GROUP BY col1, col2
    ORDER BY maxCreatedAt
    LIMIT 10 OFFSET 0) AS sub
ON t1.col1 = sub.col1
AND t1.col2 = sub.col2
AND t1.createdAt = sub.maxCreatedAt
WHERE t1.id = ? AND t1.userId = ?
ORDER BY t1.createdAt;

PK: id, userId, col1, col2, col3
Index: createdAt

Explain:

{
  "query_block": {
    "select_id": 1,
    "cost_info": {
      "query_cost": "34.50"
    },
    "ordering_operation": {
      "using_temporary_table": true,
      "using_filesort": true,
      "cost_info": {
        "sort_cost": "10.00"
      },
      "nested_loop": [
        {
          "table": {
            "table_name": "sub",
            "access_type": "ALL",
            "rows_examined_per_scan": 10,
            "rows_produced_per_join": 10,
            "filtered": "100.00",
            "cost_info": {
              "read_cost": "10.50",
              "eval_cost": "2.00",
              "prefix_cost": "12.50",
              "data_read_per_join": "3K"
            },
            "used_columns": [
              "col1",
              "col2",
              "maxCreatedAt"
            ],
            "attached_condition": "(`sub`.`maxCreatedAt` is not null)",
            "materialized_from_subquery": {
              "using_temporary_table": true,
              "dependent": false,
              "cacheable": true,
              "query_block": {
                "select_id": 2,
                "cost_info": {
                  "query_cost": "10.27"
                },
                "ordering_operation": {
                  "using_filesort": true,
                  "grouping_operation": {
                    "using_temporary_table": true,
                    "using_filesort": false,
                    "table": {
                      "table_name": "indexTable",
                      "access_type": "ref",
                      "possible_keys": [
                        "PRIMARY",
                        "createdAt",
                        "id_userId_col1_col2_createdAt",
                        "col1_col2_createdAt"
                      ],
                      "key": "PRIMARY",
                      "used_key_parts": [
                        "id",
                        "userId"
                      ],
                      "key_length": "8",
                      "ref": [
                        "const",
                        "const"
                      ],
                      "rows_examined_per_scan": 46,
                      "rows_produced_per_join": 46,
                      "filtered": "100.00",
                      "cost_info": {
                        "read_cost": "1.07",
                        "eval_cost": "9.20",
                        "prefix_cost": "10.27",
                        "data_read_per_join": "16K"
                      },
                      "used_columns": [
                        "id",
                        "userId",
                        "createdAt",
                        "col1",
                        "col2",
                        "col3"
                      ],
                      "attached_condition": "((`MyDB`.`indexTable`.`id` <=> 53) and (`MyDB`.`indexTable`.`userId` <=> 549814))"
                    }
                  }
                }
              }
            }
          }
        },
        {
          "table": {
            "table_name": "t1",
            "access_type": "ref",
            "possible_keys": [
              "PRIMARY",
              "createdAt",
              "id_userId_col1_col2_createdAt",
              "col1_col2_createdAt"
            ],
            "key": "id_userId_col1_col2_createdAt",
            "used_key_parts": [
              "id",
              "userId",
              "col1",
              "col2",
              "createdAt"
            ],
            "key_length": "339",
            "ref": [
              "const",
              "const",
              "sub.col1",
              "sub.col2",
              "sub.maxCreatedAt"
            ],
            "rows_examined_per_scan": 1,
            "rows_produced_per_join": 10,
            "filtered": "100.00",
            "cost_info": {
              "read_cost": "10.00",
              "eval_cost": "2.00",
              "prefix_cost": "24.50",
              "data_read_per_join": "3K"
            },
            "used_columns": [
              "id",
              "userId",
              "createdAt",
              "updatedAt",
              "col1",
              "col2",
              "col3",
              "metadata",
            ]
          }
        }
      ]
    }
  }
}

This query finds the most recent record in the grouping of col1 and col2, orders by createdAt, and limits the entries to 10.


问:
How to avoid calling malloc for each node in a linked list
This question was inspired by

Prevent malloc function wrapping

I have written a program that allocates memory for individual nodes in a linked list by calling malloc.

There are speed tests in which malloc is wrapped by a function that causes malloc calls to take more time than normal. This allows the tests to detect frequent usage of malloc.

How do I avoid calling malloc for each node?

答:
A simple solution is to implement alternative dynamic memory functions using mmap().

```<code>void* alt_malloc( size_t size )
{
    void* mem = mmap( NULL, size + sizeof(size_t),
                      PROT_READ | PROT_WRITE,
                      MAP_PRIVATE | MAP_ANONYMOUS, -1, 0 ) ;

    if( mem != MAP_FAILED )
    {
        *(size_t*)mem = size ;
    }
    else
    {
        mem = NULL ;
    }

    return mem + sizeof( size_t) ;
}

void* alt_calloc( size_t nitems, size_t size)
{
    return alt_malloc( nitems * size ) ;
}

void alt_free( void* mem )
{
    if( mem != NULL) munmap( mem, *((size_t*)mem - 1) ) ;
}

void* alt_realloc( void *old_mem, size_t new_size )
{
    void* new_mem = alt_malloc( new_size ) ;
    if( new_mem != NULL )
    {
        size_t old_size = *((size_t*)old_mem - 1) ;
        size_t copy_size = old_size > new_size ? new_size : old_size ;
        memcpy( new_mem, old_mem, copy_size ) ;
        alt_free( old_mem ) ;
    }

    return new_mem ;
}
</code>```

The following test:

```<code>#define ALLOC_SIZE 1024 * 1024
int main()
{
    char* test = alt_malloc( ALLOC_SIZE ) ;
    memset( test, 'X', ALLOC_SIZE ) ;
    printf( "%p : %c %c\n", test, test[0], test[ALLOC_SIZE-1] ) ;
    test = alt_realloc( test, ALLOC_SIZE * 2 ) ;
    printf( "%p : %c %c\n", test, test[0], test[ALLOC_SIZE-1] ) ;
    alt_free( test ) ;

    return 0;
}
</code>```

Outputs:

```<code>0x7f102957d008 : X X
0x7f1028ea3008 : X X
</code>```

Demonstrating that the memset() covered the extent of the initial block, and that the realloc created a new block and copied the data.

A more efficient, though slightly more complex solution would be to use mmap() to allocate an alternative heap, and then implement a heap manager operating on that block as an alternative to the standard functions.  There is no shortage of heap management examples.

You could for example take the Newlib C library allocator with modified names and implement the sbrk() syscall (again renamed to prevent clash) using mmap() to provide memory to the alternate heap.

Body:
A simple solution is to implement alternative dynamic memory functions using mmap().

void* alt_malloc( size_t size )
{
    void* mem = mmap( NULL, size + sizeof(size_t),
                      PROT_READ | PROT_WRITE,
                      MAP_PRIVATE | MAP_ANONYMOUS, -1, 0 ) ;

    if( mem != MAP_FAILED )
    {
        *(size_t*)mem = size ;
    }
    else
    {
        mem = NULL ;
    }

    return mem + sizeof( size_t) ;
}

void* alt_calloc( size_t nitems, size_t size)
{
    return alt_malloc( nitems * size ) ;
}

void alt_free( void* mem )
{
    if( mem != NULL) munmap( mem, *((size_t*)mem - 1) ) ;
}

void* alt_realloc( void *old_mem, size_t new_size )
{
    void* new_mem = alt_malloc( new_size ) ;
    if( new_mem != NULL )
    {
        size_t old_size = *((size_t*)old_mem - 1) ;
        size_t copy_size = old_size > new_size ? new_size : old_size ;
        memcpy( new_mem, old_mem, copy_size ) ;
        alt_free( old_mem ) ;
    }

    return new_mem ;
}

The following test:

#define ALLOC_SIZE 1024 * 1024
int main()
{
    char* test = alt_malloc( ALLOC_SIZE ) ;
    memset( test, 'X', ALLOC_SIZE ) ;
    printf( "%p : %c %c\n", test, test[0], test[ALLOC_SIZE-1] ) ;
    test = alt_realloc( test, ALLOC_SIZE * 2 ) ;
    printf( "%p : %c %c\n", test, test[0], test[ALLOC_SIZE-1] ) ;
    alt_free( test ) ;

    return 0;
}

Outputs:

0x7f102957d008 : X X
0x7f1028ea3008 : X X

Demonstrating that the memset() covered the extent of the initial block, and that the realloc created a new block and copied the data.

A more efficient, though slightly more complex solution would be to use mmap() to allocate an alternative heap, and then implement a heap manager operating on that block as an alternative to the standard functions.  There is no shortage of heap management examples.

You could for example take the Newlib C library allocator with modified names and implement the sbrk() syscall (again renamed to prevent clash) using mmap() to provide memory to the alternate heap.


问:
Liquibase: Change column to an autoincrement column (identity) in DB2
I'm trying to change a BIGINT Column to an autoincremented column in DB2 but I can't seem find how.
I tried doing it like this:

```<code>    <changeSet id="08.01" author="...">
        <addColumn tableName="table_name">
            <column name="id" type="bigint">
                <constraints nullable="true"/>
            </column>

            <column name="member_type" type="varchar(100)">
                <constraints nullable="true"/>
            </column>
        </addColumn>
    </changeSet>

    <changeSet id="08.02" author="...">
        <addAutoIncrement tableName="table_name"
                          columnDataType="bigint"
                          columnName="id"/>
    </changeSet>
</code>```

and when it runs I get this error:

```<code>org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'liquibase' defined in class path resource [org/springframework/boot/autoconfigure/liquibase/LiquibaseAutoConfiguration$LiquibaseConfiguration.class]: Invocation of init method failed; nested exception is liquibase.exception.MigrationFailedException: Migration failed for change set classpath:db/changelog/08-separation.xml::08.01::author:
     Reason: liquibase.exception.DatabaseException: DB2 SQL Error: SQLCODE=-270, SQLSTATE=42997, SQLERRMC=72, DRIVER=4.13.127 [Failed SQL: ALTER TABLE SCHEMATEST.table_name ALTER COLUMN id SET GENERATED BY DEFAULT AS IDENTITY]
    at org.springframework.bean
...
...
...
Caused by: liquibase.exception.MigrationFailedException: Migration failed for change set classpath:db/changelog/08separation.xml::08.01::author:
     Reason: liquibase.exception.DatabaseException: DB2 SQL Error: SQLCODE=-270, SQLSTATE=42997, SQLERRMC=72, DRIVER=4.13.127 [Failed SQL: ALTER TABLE SCHEMATEST.table_name ALTER COLUMN id SET GENERATED BY DEFAULT AS IDENTITY]
...
...
...
Caused by: com.ibm.db2.jcc.am.SqlSyntaxErrorException: DB2 SQL Error: SQLCODE=-270, SQLSTATE=42997, SQLERRMC=72, DRIVER=4.13.127
</code>```

答:
An identity column cannot be nullable, this is what the error message tells you:

A nullable column cannot be changed to become an identity
           column.

Change the column constraint to nullable="false" I guess.

Body:
I'm trying to change a BIGINT Column to an autoincremented column in DB2 but I can't seem find how.
I tried doing it like this:

    <changeSet id="08.01" author="...">
        <addColumn tableName="table_name">
            <column name="id" type="bigint">
                <constraints nullable="true"/>
            </column>

            <column name="member_type" type="varchar(100)">
                <constraints nullable="true"/>
            </column>
        </addColumn>
    </changeSet>

    <changeSet id="08.02" author="...">
        <addAutoIncrement tableName="table_name"
                          columnDataType="bigint"
                          columnName="id"/>
    </changeSet>

and when it runs I get this error:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'liquibase' defined in class path resource [org/springframework/boot/autoconfigure/liquibase/LiquibaseAutoConfiguration$LiquibaseConfiguration.class]: Invocation of init method failed; nested exception is liquibase.exception.MigrationFailedException: Migration failed for change set classpath:db/changelog/08-separation.xml::08.01::author:
     Reason: liquibase.exception.DatabaseException: DB2 SQL Error: SQLCODE=-270, SQLSTATE=42997, SQLERRMC=72, DRIVER=4.13.127 [Failed SQL: ALTER TABLE SCHEMATEST.table_name ALTER COLUMN id SET GENERATED BY DEFAULT AS IDENTITY]
    at org.springframework.bean
...
...
...
Caused by: liquibase.exception.MigrationFailedException: Migration failed for change set classpath:db/changelog/08separation.xml::08.01::author:
     Reason: liquibase.exception.DatabaseException: DB2 SQL Error: SQLCODE=-270, SQLSTATE=42997, SQLERRMC=72, DRIVER=4.13.127 [Failed SQL: ALTER TABLE SCHEMATEST.table_name ALTER COLUMN id SET GENERATED BY DEFAULT AS IDENTITY]
...
...
...
Caused by: com.ibm.db2.jcc.am.SqlSyntaxErrorException: DB2 SQL Error: SQLCODE=-270, SQLSTATE=42997, SQLERRMC=72, DRIVER=4.13.127


问:
How can I query multiple columns from a drop down menu and a count of a certain column
I'm trying to generate a report for a user to select from a drop-down menu. I'd like to be able to pull multiple columns from a selected drop down. And, if possible, get a certain count for a certain column.

So far I've only been able to select one column and get a count from it.

```<code>=QUERY(A2:O20,"SELECT M, count(M) Where E ='" &B23 & "' group by M",0)
</code>```

I'd like to somehow to continue selecting certain columns and have them display when a user selects from the drop-down menu, as well as keeping my current work (The count from M)

答:
compact mode:

```<code>={"select Interface", L1;
 QUERY(A2:H, "select A,count(A) where D='"&L1&"' group by A label count(A)''");
 QUERY(A2:H, "select B,count(B) where D='"&L1&"' group by B label count(B)''");
 QUERY(A2:H, "select C,count(C) where D='"&L1&"' group by C label count(C)''");
 QUERY(A2:H, "select E,count(E) where D='"&L1&"' group by E label count(E)''");
 QUERY(A2:H, "select F,count(F) where D='"&L1&"' group by F label count(F)''");
 QUERY(A2:H, "select G,count(G) where D='"&L1&"' group by G label count(G)''");
 QUERY(A2:H, "select H,count(H) where D='"&L1&"' group by H label count(H)''")}
</code>```

labeled mode:

```<code>=IF(K1<>"", {
 QUERY(A1:H, "select A,count(A) where D='"&K1&"' group by A label count(A)''", 1);
 QUERY(A1:H, "select B,count(B) where D='"&K1&"' group by B label count(B)''", 1);
 QUERY(A1:H, "select C,count(C) where D='"&K1&"' group by C label count(C)''", 1);
 QUERY(A1:H, "select E,count(E) where D='"&K1&"' group by E label count(E)''", 1);
 QUERY(A1:H, "select F,count(F) where D='"&K1&"' group by F label count(F)''", 1);
 QUERY(A1:H, "select G,count(G) where D='"&K1&"' group by G label count(G)''", 1);
 QUERY(A1:H, "select H,count(H) where D='"&K1&"' group by H label count(H)''", 1)}, )
</code>```

note: green background and bold labels can be auto-set via conditional formatting

expanded mode:

```<code>=ARRAYFORMULA(REGEXREPLACE(TO_TEXT(QUERY(A1:H,
 "select A,count(A),B,count(B),C,count(C),D,count(D),
         E,count(E),F,count(F),G,count(G),H,count(H)
  where D='"&K1&"'
  group by A,B,C,D,E,F,G,H", 1)), "^count.*", ""))
</code>```

Body:
I'm trying to generate a report for a user to select from a drop-down menu. I'd like to be able to pull multiple columns from a selected drop down. And, if possible, get a certain count for a certain column.

So far I've only been able to select one column and get a count from it.

=QUERY(A2:O20,"SELECT M, count(M) Where E ='" &B23 & "' group by M",0)

I'd like to somehow to continue selecting certain columns and have them display when a user selects from the drop-down menu, as well as keeping my current work (The count from M)

Body:
compact mode:

={"select Interface", L1;
 QUERY(A2:H, "select A,count(A) where D='"&L1&"' group by A label count(A)''");
 QUERY(A2:H, "select B,count(B) where D='"&L1&"' group by B label count(B)''");
 QUERY(A2:H, "select C,count(C) where D='"&L1&"' group by C label count(C)''");
 QUERY(A2:H, "select E,count(E) where D='"&L1&"' group by E label count(E)''");
 QUERY(A2:H, "select F,count(F) where D='"&L1&"' group by F label count(F)''");
 QUERY(A2:H, "select G,count(G) where D='"&L1&"' group by G label count(G)''");
 QUERY(A2:H, "select H,count(H) where D='"&L1&"' group by H label count(H)''")}

labeled mode:

=IF(K1<>"", {
 QUERY(A1:H, "select A,count(A) where D='"&K1&"' group by A label count(A)''", 1);
 QUERY(A1:H, "select B,count(B) where D='"&K1&"' group by B label count(B)''", 1);
 QUERY(A1:H, "select C,count(C) where D='"&K1&"' group by C label count(C)''", 1);
 QUERY(A1:H, "select E,count(E) where D='"&K1&"' group by E label count(E)''", 1);
 QUERY(A1:H, "select F,count(F) where D='"&K1&"' group by F label count(F)''", 1);
 QUERY(A1:H, "select G,count(G) where D='"&K1&"' group by G label count(G)''", 1);
 QUERY(A1:H, "select H,count(H) where D='"&K1&"' group by H label count(H)''", 1)}, )

note: green background and bold labels can be auto-set via conditional formatting

expanded mode:

=ARRAYFORMULA(REGEXREPLACE(TO_TEXT(QUERY(A1:H,
 "select A,count(A),B,count(B),C,count(C),D,count(D),
         E,count(E),F,count(F),G,count(G),H,count(H)
  where D='"&K1&"'
  group by A,B,C,D,E,F,G,H", 1)), "^count.*", ""))


问:
FadeInImage in BoxDecoration
I love the FadeInImage

I can do this

```<code>child: FadeInImage.assetNetwork(
    image: 'https://placeimg.com/640/480/any',
    placeholder: 'assets/images/loading.gif',
  ),
</code>```

I want to use the FadeInImage in a BoxDecoration as below.

```<code>decoration: BoxDecoration(
  borderRadius: BorderRadius.circular(8.0),
  image: DecorationImage(
    image: FadeInImage.assetNetwork(
        '${document['image']}'),
    fit: BoxFit.cover,
  ),
),
</code>```

I get this error:

The argument type 'FadeInImage' can't be assigned to the parameter type 'ImageProvider'

How would I go about it?

Use Case

In a carousel, put in placeholder, before network loaded image comes in

Here's my carousel Widget (I'm using the carousel_slider package for Flutter)

```<code>  Widget _carouselSlider(BuildContext context) {
    return StreamBuilder<QuerySnapshot>(
      stream: Firestore.instance.collection('events').snapshots(),
      builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
        if (snapshot.hasError) return new Text('Error: ${snapshot.error}');
        switch (snapshot.connectionState) {
          case ConnectionState.waiting:
            return new Text('Loading...');
          default:
            return CarouselSlider(
              height: 150.0,
              enlargeCenterPage: true,
              enableInfiniteScroll: false,
              items: snapshot.data.documents.map((DocumentSnapshot document) {
                print('Listing the documents: $document');
                return Builder(
                  builder: (BuildContext context) {
                    return GestureDetector(
                      onTap: () {
                        print('I am clicked');
                        Navigator.pushNamed(context, '/detail');
                      },
                      child: Container(
                        width: MediaQuery.of(context).size.width,
                        margin: EdgeInsets.only(
                            left: 5.0, right: 5.0, bottom: 20.0),
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(8.0),
                          image: DecorationImage(
                            image: NetworkImage('${document['image']}'),
                            fit: BoxFit.cover,
                          ),
                        ),
                        child: Center(
                          child: Text(
                            '${document['name']}',
                            style: TextStyle(fontSize: 16.0),
                          ),
                        ),
                      ),
                    );
                  },
                );
              }).toList(),
            );
        }
      },
    );
  }
</code>```

So, for the part

```<code>image: DecorationImage(
                        image: NetworkImage('${document['image']}'),
                        fit: BoxFit.cover,
                      ),
</code>```

I wish to have a placeholder approach, instead of only the text until network loaded image arrives.

答:
It's because FadeInImage it not a type of ImageProvider widget, you need to use AssetImage, NetworkImage... inside DecorationImage.

Outside the DecorationImage, like in a Container's child, you can use it as well.

e.g.

```<code>       Container(
          child: FadeInImage.memoryNetwork(
            placeholder: kTransparentImage,
            image: product.thumbnail,
            fit: BoxFit.contain,
          ),
        ),
</code>```

To know more about this widget, check it this:

Flutter Widget of The Week - FadeIn Image

Title: FadeInImage in BoxDecoration

Body:
I love the FadeInImage

I can do this

child: FadeInImage.assetNetwork(
    image: 'https://placeimg.com/640/480/any',
    placeholder: 'assets/images/loading.gif',
  ),

I want to use the FadeInImage in a BoxDecoration as below.

decoration: BoxDecoration(
  borderRadius: BorderRadius.circular(8.0),
  image: DecorationImage(
    image: FadeInImage.assetNetwork(
        '${document['image']}'),
    fit: BoxFit.cover,
  ),
),

I get this error:

The argument type 'FadeInImage' can't be assigned to the parameter type 'ImageProvider'

How would I go about it?

Use Case

In a carousel, put in placeholder, before network loaded image comes in

Here's my carousel Widget (I'm using the carousel_slider package for Flutter)

  Widget _carouselSlider(BuildContext context) {
    return StreamBuilder<QuerySnapshot>(
      stream: Firestore.instance.collection('events').snapshots(),
      builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
        if (snapshot.hasError) return new Text('Error: ${snapshot.error}');
        switch (snapshot.connectionState) {
          case ConnectionState.waiting:
            return new Text('Loading...');
          default:
            return CarouselSlider(
              height: 150.0,
              enlargeCenterPage: true,
              enableInfiniteScroll: false,
              items: snapshot.data.documents.map((DocumentSnapshot document) {
                print('Listing the documents: $document');
                return Builder(
                  builder: (BuildContext context) {
                    return GestureDetector(
                      onTap: () {
                        print('I am clicked');
                        Navigator.pushNamed(context, '/detail');
                      },
                      child: Container(
                        width: MediaQuery.of(context).size.width,
                        margin: EdgeInsets.only(
                            left: 5.0, right: 5.0, bottom: 20.0),
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(8.0),
                          image: DecorationImage(
                            image: NetworkImage('${document['image']}'),
                            fit: BoxFit.cover,
                          ),
                        ),
                        child: Center(
                          child: Text(
                            '${document['name']}',
                            style: TextStyle(fontSize: 16.0),
                          ),
                        ),
                      ),
                    );
                  },
                );
              }).toList(),
            );
        }
      },
    );
  }

So, for the part

image: DecorationImage(
                        image: NetworkImage('${document['image']}'),
                        fit: BoxFit.cover,
                      ),

I wish to have a placeholder approach, instead of only the text until network loaded image arrives.

Body:
It's because FadeInImage it not a type of ImageProvider widget, you need to use AssetImage, NetworkImage... inside DecorationImage.

Outside the DecorationImage, like in a Container's child, you can use it as well.

e.g.

       Container(
          child: FadeInImage.memoryNetwork(
            placeholder: kTransparentImage,
            image: product.thumbnail,
            fit: BoxFit.contain,
          ),
        ),

To know more about this widget, check it this:

Flutter Widget of The Week - FadeIn Image


问:
Why is my command line giving different info then visual studio when checking status of git repo?
I am testing writing a script to pull down the latest version of the master and then merge or rebase my local branch based off the updated master.

While trying to do so I am running into an issue, where visual studio is seeing that there is a commit I need to pull down to get up to date but the command line states that I am current.

I have attached a screen shot showing an incoming commit showing in Visual Studio but the cli showing up to date.

答:
If git status is showing no changes in the remote (origin/master), but Visual Studio does show changes to pull, it might be that Git hasn't updated its remote tracking branches.  Only commands git fetch, git pull, and git remote update typically actually access the remote server to update its status.  This is part of what makes Git so fast -- it is normally working from the local repository.

Run git remote update to update the remote tracking branches.  Then git status will show accurately the changes to pull.

Example:

```<code>$ git status
On branch develop
Your branch is up to date with 'origin/develop'.

nothing to commit, working tree clean
✔ ~/myrepo [develop|✔]
$ git remote update
Fetching origin
✔ ~/myrepo [develop ↓·1|✔]
$ git status
On branch develop
Your branch is behind 'origin/develop' by 1 commit, and can be fast-forwarded.
  (use "git pull" to update your local branch)

nothing to commit, working tree clean
✔ ~/myrepo [develop ↓·1|✔]
$
</code>```

Body:
If git status is showing no changes in the remote (origin/master), but Visual Studio does show changes to pull, it might be that Git hasn't updated its remote tracking branches.  Only commands git fetch, git pull, and git remote update typically actually access the remote server to update its status.  This is part of what makes Git so fast -- it is normally working from the local repository.

Run git remote update to update the remote tracking branches.  Then git status will show accurately the changes to pull.

Example:

$ git status
On branch develop
Your branch is up to date with 'origin/develop'.

nothing to commit, working tree clean
✔ ~/myrepo [develop|✔]
$ git remote update
Fetching origin
✔ ~/myrepo [develop ↓·1|✔]
$ git status
On branch develop
Your branch is behind 'origin/develop' by 1 commit, and can be fast-forwarded.
  (use "git pull" to update your local branch)

nothing to commit, working tree clean
✔ ~/myrepo [develop ↓·1|✔]
$


问:
VBA to highlight cells based on current time of day
I have a row of cells repeating "1st shift", "2nd shift", and "3rd shift". The top row on the sheet is the dates throughout the year. I already have code to open the file to a specific date (always the day before the current day) and highlight the current day in a blue. I am trying to get the current shift to also highlight the same shade of blue. So if the sheet were being viewed at 7am, the cell with "1st shift" only under the current date would highlight, if viewed at 3pm the cell with "2nd shift" under the current date would highlight, and so on.

Any help is appreciated.

Private Sub Workbook_Open()
    For I = 1 To 1700
        If Cells(1, I).Value = Date - 1 Then
            ActiveWindow.ScrollColumn = I
        End If
    Next
    For I = 1 To 1700
        If Cells(1, I).Value = Date Then
            Cells(1, I).Interior.ColorIndex = 28
            Cells(2, I).Interior.ColorIndex = 28
        End If
    Next
End Sub
```

答:
Since your VBA mentions 1700, I will assume your shifts start at 1:00, 9:00 and 17:00 respectively.

You can use conditional formatting with the following formulas:

1st shift:

```<code>=AND(NOW()-TODAY()>1/24,NOW()-TODAY()<9/24)
</code>```

2nd shift:

```<code>=AND(NOW()-TODAY()>9/24,NOW()-TODAY()<17/24)
</code>```

3rd shift:

```<code>=OR(NOW()-TODAY()>17/24,NOW()-TODAY()<1/24)
</code>```

Body:
Since your VBA mentions 1700, I will assume your shifts start at 1:00, 9:00 and 17:00 respectively.

You can use conditional formatting with the following formulas:

1st shift:

=AND(NOW()-TODAY()>1/24,NOW()-TODAY()<9/24)

2nd shift:

=AND(NOW()-TODAY()>9/24,NOW()-TODAY()<17/24)

3rd shift:

=OR(NOW()-TODAY()>17/24,NOW()-TODAY()<1/24)


问:
Google Chrome ignores Google Font subset
I'm using a pretty common font-family, Open Sans, trying to load multiple weights & latin as the only subset (which is optional, as it is supported by default), it all goes great with every browser, apart from Google Chrome.

@import url('https://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700,800&subset=latin');

It looks great in Firefox / IE, but in Chrome, the subset is ignored and the browser gets all the subsets & their unicode ranges, and downloads them according to the type of characters found throughout the page. I know that this behaviour is intended.

For example, font-weight: 600 (semibold) and 800 (extrabold) look exactly like 700. If I remove all the subsets from the source and load only the latin subset of each weight, it works great in Chrome too.

Is there any easy way I can force Google to serve that specific subset only, no matter what? I know there are several other ways to load a font.

答:
As you already mentioned in your question, in a browser that supports unicode-range the subset is dynamically served, there's no need (or way) to force it.

Just don't include in the DOM any Unicode characters from the subsets you don't want. This will prevent any aware browser from downloading unnecessary font files.

Also, the latin subset is included by default, so there's also no need to specify it.

Just include other subsets for browsers that doesn't support unicode-range.

ContentLicense: CC BY-SA 3.0


问:
How to do index and match like in Pandas
I am trying to use index and match like function in Pandas. I am new to this.
What I would like to do is

index string or multiple strings and change the corresponding price

index the string without regardless of uppercase and lowercase letters (a lot of the names of the fruits are in all uppercase, one uppercase and rest in lowercase, or all lowercase)

```<code>fruits                  price
apple from us           10
Apple from US           11
Mango from Canada       15
Orange from Mexico      16
Orange from Costa       15
Orange from Brazil      19
Pear from Guatemala     32
Melon from Guatemala    4
orange from Honduras    5
</code>```

I tried
        df.loc[df['fruits'].str.contains('apple'), 'Target Price'] = 275
but I get

```<code>    fruits                  price
    apple from us           275
    Apple from US           275
    Mango from Canada       275
    Orange from Mexico      275
    Orange from Costa       275
    Orange from Brazil      275
    Pear from Guatemala     275
    Melon from Guatemala    275
    Orange from Honduras    275
</code>```

but what I would like is

```<code>    fruits                  price
    apple from us           275
    Apple from US           275
    Mango from Canada       15
    Orange from Mexico      16
    Orange from Costa       15
    Orange from Brazil      19
    Pear from Guatemala     32
    Melon from Guatemala    4
    Orange from Honduras    5
</code>```

Also, the line above does not let me have multiple conditions like containing "Orange" but not from Honduras. Is there a way to only exclude if certain string is also in it so that I can change the price of Orange is set to 222 but Orange from Honduras remains as it was.

```<code>    fruits                  price
    apple from us           275
    Apple from US           275
    Mango from Canada       15
    Orange from Mexico      222
    Orange from Costa       222
    Orange from Brazil      222
    Pear from Guatemala     32
    Melon from Guatemala    4
    Orange from Honduras    5
</code>```

答:
you can convert to lower case</p>

```<code>>>> d_f.loc[d_f['Fruits'].str.lower().str.contains('apple'), 'Price'] = 275
>>> d_f
                 Fruits Price
0         apple from us   275
1         Apple from US   275
2     Mango from Canada    15
3    Orange from Mexico    16
4     Orange from Costa    15
5    Orange from Brazil    19
6   Pear from Guatemala    32
7  Melon from Guatemala     4
8  orange from Honduras     5
</code>```

Body:
I am trying to use index and match like function in Pandas. I am new to this.
What I would like to do is

index string or multiple strings and change the corresponding price

index the string without regardless of uppercase and lowercase letters (a lot of the names of the fruits are in all uppercase, one uppercase and rest in lowercase, or all lowercase)

fruits                  price
apple from us           10
Apple from US           11
Mango from Canada       15
Orange from Mexico      16
Orange from Costa       15
Orange from Brazil      19
Pear from Guatemala     32
Melon from Guatemala    4
orange from Honduras    5

I tried
        df.loc[df['fruits'].str.contains('apple'), 'Target Price'] = 275
but I get

    fruits                  price
    apple from us           275
    Apple from US           275
    Mango from Canada       275
    Orange from Mexico      275
    Orange from Costa       275
    Orange from Brazil      275
    Pear from Guatemala     275
    Melon from Guatemala    275
    Orange from Honduras    275

but what I would like is

    fruits                  price
    apple from us           275
    Apple from US           275
    Mango from Canada       15
    Orange from Mexico      16
    Orange from Costa       15
    Orange from Brazil      19
    Pear from Guatemala     32
    Melon from Guatemala    4
    Orange from Honduras    5

Also, the line above does not let me have multiple conditions like containing "Orange" but not from Honduras. Is there a way to only exclude if certain string is also in it so that I can change the price of Orange is set to 222 but Orange from Honduras remains as it was.

    fruits                  price
    apple from us           275
    Apple from US           275
    Mango from Canada       15
    Orange from Mexico      222
    Orange from Costa       222
    Orange from Brazil      222
    Pear from Guatemala     32
    Melon from Guatemala    4
    Orange from Honduras    5

Body:
you can convert to lower case

>>> d_f.loc[d_f['Fruits'].str.lower().str.contains('apple'), 'Price'] = 275
>>> d_f
                 Fruits Price
0         apple from us   275
1         Apple from US   275
2     Mango from Canada    15
3    Orange from Mexico    16
4     Orange from Costa    15
5    Orange from Brazil    19
6   Pear from Guatemala    32
7  Melon from Guatemala     4
8  orange from Honduras     5


问:
AutoMapper 8 Upgrade ConstructUsing
I have just upgraded to v8 of AutoMapper and the expression below fails but I really cannot see why.

```<code>cfg.CreateMap<string, Nmtoken>()
    .ConstructUsing(i => new Nmtoken(i))
    .ForMember(m => m.Token, o => o.MapFrom(s => s));
</code>```

I believe that the passed expressions are valid. I get no build errors and intellisense is happy. But I get runtime error:

```<code>System.MissingMethodException: 'Method not found:
'AutoMapper.IMappingExpression`2<!0,!1>
AutoMapper.IMappingExpression`2.ConstructUsing(System.Func`2<!0,!1>)'.'
</code>```

I'm happy to admit that I don't understand the error message.

答:
I had the samme issue, but i was using AutoMapper v8.0.0.
Upgrading to version v8.1.0 solved the issue.</p>

Title: AutoMapper 8 Upgrade ConstructUsing

Body:
I have just upgraded to v8 of AutoMapper and the expression below fails but I really cannot see why.

cfg.CreateMap<string, Nmtoken>()
    .ConstructUsing(i => new Nmtoken(i))
    .ForMember(m => m.Token, o => o.MapFrom(s => s));

I believe that the passed expressions are valid. I get no build errors and intellisense is happy. But I get runtime error:

System.MissingMethodException: 'Method not found:
'AutoMapper.IMappingExpression`2<!0,!1>
AutoMapper.IMappingExpression`2.ConstructUsing(System.Func`2<!0,!1>)'.'

I'm happy to admit that I don't understand the error message.


问:
React-Node.js app can't connect to SQL Server database
This is my first time attempting this type of tech stack and I am not sure what I am missing to get my database to connect. When I attempt to go to /api/broker, it just loads for a long time... also, I never get the message that server is working from my / route.

When I stop the loading of the /api/broker route, I get this message:

Proxy Error: See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (ECONNRESET).

How would I get the SQL Server to accept the connection? Any idea what I am missing or doing wrong?

This is my app.js

import React, { Component } from 'react';
import './App.css';
import Header from './components/header';
// import './server';

class App extends Component {
  state = {
      data: null
    };

    componentDidMount() {
        // Call our fetch function below once the component mounts
      this.callBackendAPI()
        .then(res => this.setState({ data: res.express }))
        .catch(err => console.log(err));
    }
      // Fetches our GET route from the Express server. (Note the route we are fetching matches the GET route from server.js
    callBackendAPI = async () => {
      const response = await fetch('/api/broker');
      const body = await response.json();

      if (response.status !== 200) {
        throw Error(body.message)
      }
      return body;
    };

    render() {
    return (

            Edit src/App.js and save to reload.

    );
}
}

export default App;```
</div>
</div>
</p>

<p>And this is my server.js file:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>const express = require("express");
const bodyParser = require ("body-parser");
const sql = require('mssql');
const app = express();

app.use(express.static('public'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.use(function(res, req, next){
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Methods", "GET, HEAD, OPTIONS, POST, PUT");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, contentType, Content-Type, Accept, Authorization");
    next();
});

var dbConfig = {
    user: "user",
    password: "password",
    server: "jdbc:sqlserver://sql3\\misc",
    database: "ReactApp_DB"
};

//Function to connect to database and execute query
var  executeQuery = function(res, query){
    sql.connect(dbConfig, function (err) {
        if (err) {
                    console.log("Error while connecting database :- " + err);
                    res.send(err);
                 }
                 else {
                        // create Request object
                        var request = new sql.Request();
                        // query to the database
                        request.query(query, function (err, res) {
                          if (err) {
                                     console.log("Error while querying database :- " + err);
                                     res.send(err);
                                    }
                                    else {
                                      res.send(res);
                                      console.log("Querying database ");
                                           }
                              });
                      }
     });
}

app.get('/', function(req, res) {
 res.send('Server is working...');
});

//GET API
app.get("/api/broker", function(req , res){
    console.log('brokers queried: ');
    var query = "select * from [broker]";
    executeQuery (res, query);
});

var server = app.listen(3000, function (){
    var port = server.address().port;
    console.log("app now running on port ", port);
});</code>```

答:
Easy fix

in your package.json in your React app, enter:

"proxy": base URI where node app is running.

for example

```<code>  "proxy": "http://localhost:5000"
</code>```

Proxy is what allows your react app to make requests as if it were the node server. Because '/api/broker' is a route on your node server not in your react app. So a proxy allows your react app to make a request as if it were your node server. with the URI path of:

```<code>http://localhost:5000/api/broker
</code>```

even though your react app is running on localhost:3000. Without the proxy I assume your are currently just accessing the route.

```<code>http://localhost:3000/api/broker
</code>```

which doesnt do anything since it is not a valid route.

Body:
This is my first time attempting this type of tech stack and I am not sure what I am missing to get my database to connect. When I attempt to go to /api/broker, it just loads for a long time... also, I never get the message that server is working from my / route.

When I stop the loading of the /api/broker route, I get this message:

Proxy Error: See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (ECONNRESET).

How would I get the SQL Server to accept the connection? Any idea what I am missing or doing wrong?

This is my app.js

import React, { Component } from 'react';
import './App.css';
import Header from './components/header';
// import './server';

class App extends Component {
  state = {
      data: null
    };

    componentDidMount() {
        // Call our fetch function below once the component mounts
      this.callBackendAPI()
        .then(res => this.setState({ data: res.express }))
        .catch(err => console.log(err));
    }
      // Fetches our GET route from the Express server. (Note the route we are fetching matches the GET route from server.js
    callBackendAPI = async () => {
      const response = await fetch('/api/broker');
      const body = await response.json();

      if (response.status !== 200) {
        throw Error(body.message)
      }
      return body;
    };

    render() {
    return (

            Edit src/App.js and save to reload.

    );
}
}

export default App;

And this is my server.js file:

const express = require("express");
const bodyParser = require ("body-parser");
const sql = require('mssql');
const app = express();

app.use(express.static('public'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.use(function(res, req, next){
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Methods", "GET, HEAD, OPTIONS, POST, PUT");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, contentType, Content-Type, Accept, Authorization");
    next();
});

var dbConfig = {
    user: "user",
    password: "password",
    server: "jdbc:sqlserver://sql3\\misc",
    database: "ReactApp_DB"
};

//Function to connect to database and execute query
var  executeQuery = function(res, query){
    sql.connect(dbConfig, function (err) {
        if (err) {
                    console.log("Error while connecting database :- " + err);
                    res.send(err);
                 }
                 else {
                        // create Request object
                        var request = new sql.Request();
                        // query to the database
                        request.query(query, function (err, res) {
                          if (err) {
                                     console.log("Error while querying database :- " + err);
                                     res.send(err);
                                    }
                                    else {
                                      res.send(res);
                                      console.log("Querying database ");
                                           }
                              });
                      }
     });
}

app.get('/', function(req, res) {
 res.send('Server is working...');
});

//GET API
app.get("/api/broker", function(req , res){
    console.log('brokers queried: ');
    var query = "select * from [broker]";
    executeQuery (res, query);
});

var server = app.listen(3000, function (){
    var port = server.address().port;
    console.log("app now running on port ", port);
});

Body:
Easy fix

in your package.json in your React app, enter:

"proxy": base URI where node app is running.

for example

  "proxy": "http://localhost:5000"

Proxy is what allows your react app to make requests as if it were the node server. Because '/api/broker' is a route on your node server not in your react app. So a proxy allows your react app to make a request as if it were your node server. with the URI path of:

http://localhost:5000/api/broker

even though your react app is running on localhost:3000. Without the proxy I assume your are currently just accessing the route.

http://localhost:3000/api/broker

which doesnt do anything since it is not a valid route.


问:
Unable to get Javascript myFunction() to run var requiredFields = document.getElementById before going to next command

function myFunction() {
  var requiredFields = document.getElementById('specialTxtarea');
  window.alert('Thank for your Reservation');
  window.location = 'index.html';
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
  <div class="form-group row">
    <label for="checkin" class="col-2 col-form-label">Check-In</label>
    <div class="col-10">
      <div class="input-group">
        <div class="input-group-prepend">
          <div class="input-group-text">
            <i class="fa fa-calendar"></i>
          </div>
        </div>
        <input id="checkin" name="checkin" type="text" class="form-control" required="required" wfd-id="13">
        <div class="input-group-append">
          <div class="input-group-text">
            <i class="fa "></i>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="form-group row">
    <label for="checkout" class="col-2 col-form-label">Check-Out</label>
    <div class="col-10">
      <div class="input-group">
        <div class="input-group-prepend">
          <div class="input-group-text">
            <i class="fa fa-calendar"></i>
          </div>
        </div>
        <input id="checkout" name="checkout" type="text" class="form-control" required="required" wfd-id="12">
        <div class="input-group-append">
          <div class="input-group-text">
            <i class="fa "></i>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="form-group row">
    <label for="text" class="col-2 col-form-label">Name</label>
    <div class="col-10">
      <div class="input-group">
        <div class="input-group-prepend">
          <div class="input-group-text">
            <i class="fa fa-user"></i>
          </div>
        </div>
        <input id="text" name="text" type="text" required="required" class="form-control" wfd-id="11">
        <div class="input-group-append">
          <div class="input-group-text">
            <i class="fa "></i>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="form-group row">
    <label for="email_id" class="col-2 col-form-label">Email</label>
    <div class="col-10">
      <div class="input-group">
        <div class="input-group-prepend">
          <div class="input-group-text">
            <i class="fa fa-envelope-o"></i>
          </div>
        </div>
        <input id="email" name="email" type="email" required="required" class="form-control" wfd-id="10">
        <div class="input-group-append">
          <div class="input-group-text">
            <i class="fa "></i>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="form-group row">
    <label for="phone" class="col-2 col-form-label">Phone #</label>
    <div class="col-10">
      <div class="input-group">
        <div class="input-group-prepend">
          <div class="input-group-text">
            <i class="fa fa-phone"></i>
          </div>
        </div>
        <input id="phone" name="phone" placeholder="11 numeric" type="tel" required pattern="\d{11}" label="11 digits" class="form-control" wfd-id="9">
        <div class="input-group-append">
          <div class="input-group-text">
            <i class="fa "></i>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="form-group row">
    <label class="col-2">Room Type</label>
    <div class="col-10">
      <div class="custom-control custom-checkbox custom-control-inline">
        <input name="roomtype" id="roomtype_0" type="checkbox" class="custom-control-input" value="" checked wfd-id="8">
        <label for="roomtype_0" class="custom-control-label">Deluxe Room</label>
      </div>
      <div class="custom-control custom-checkbox custom-control-inline">
        <input name="roomtype" id="roomtype_1" type="checkbox" class="custom-control-input" value="" wfd-id="7">
        <label for="roomtype_1" class="custom-control-label">Junior Suite</label>
      </div>
      <div class="custom-control custom-checkbox custom-control-inline">
        <input name="roomtype" id="roomtype_2" type="checkbox" class="custom-control-input" value="" wfd-id="6">
        <label for="roomtype_2" class="custom-control-label">Family Suite</label>
      </div>
      <div class="custom-control custom-checkbox custom-control-inline">
        <input name="roomtype" id="roomtype_3" type="checkbox" class="custom-control-input" value="" wfd-id="5">
        <label for="roomtype_3" class="custom-control-label">Cameron Suite</label>
      </div>
      <div class="custom-control custom-checkbox custom-control-inline">
        <input name="roomtype" id="roomtype_4" type="checkbox" class="custom-control-input" value="" wfd-id="4">
        <label for="roomtype_4" class="custom-control-label">Foster Suite</label>
      </div>
    </div>
  </div>
  <div class="form-group row">
    <label class="col-2">Room Preference</label>
    <div class="col-10">
      <div class="custom-control custom-radio custom-control-inline">
        <input name="preference" id="preference_0" type="radio" class="custom-control-input" value="No Preference" required="required" wfd-id="3">
        <label for="preference_0" class="custom-control-label">No Preference</label>
      </div>
      <div class="custom-control custom-radio custom-control-inline">
        <input name="preference" id="preference_1" type="radio" class="custom-control-input" value="Non Smoking" required="required" wfd-id="2">
        <label for="preference_1" class="custom-control-label">Non Smoking</label>
      </div>
      <div class="custom-control custom-radio custom-control-inline">
        <input name="preference" id="preference_2" type="radio" class="custom-control-input" value="Smoking" required="required" wfd-id="1">
        <label for="preference_2" class="custom-control-label">Smoking</label>
      </div>
    </div>
  </div>
  <div class="form-group row">
    <label for="adults" class="col-2 col-form-label">Adults</label>
    <div class="col-10">
      <select id="adults" name="adults" class="custom-select" required="required" wfd-id="16">
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
      </select>
    </div>
  </div>
  <div class="form-group row">
    <label for="children" class="col-2 col-form-label">Children</label>
    <div class="col-10">
      <select id="children" name="children" class="custom-select" wfd-id="15">
        <option value="None">None</option>
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
      </select>
    </div>
  </div>
  <div class="form-group row">
    <label for="textarea" class="col-2 col-form-label">Special Requirement</label>
    <div class="col-10">
      <textarea id="specialTxtarea" name="specialTxtarea" cols="40" rows="5" class="form-control" wfd-id="17"></textarea>
    </div>
  </div>
  <div class="form-group row">
    <div class="offset-2 col-10">
      <button name="alpsubmit" type="submit" class="btn btn-primary btn-block" wfd-id="18" onclick="myFunction()">Submit</button>

    </div>

  </div>
</form></code>```

This is for my assignment. For this reservation form, I am not required to use PHP to validate. What I am required is to have the form validate the field and upon submit, a response using window alert to pop out.

My lecturer has actually worked through with me and managed to get my codes to work. But somehow.. after I got home. I am unable to get the form to validate prior to submit and go back to home page

I was expecting that the form created will check through all field and be prompt prior to submit button pressed and go through window.alert with a Thank you response and bring back to index.html

答:
I removed the on click on submit and added action="javascript:myFunction();" for the form and it will work here's the code for it.</p>

```<code><!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<form id="myForm" action="javascript:myFunction();">
  <div class="form-group row">
    <label for="checkin" class="col-2 col-form-label">Check-In</label>
    <div class="col-10">
      <div class="input-group">
        <div class="input-group-prepend">
          <div class="input-group-text">
            <i class="fa fa-calendar"></i>
          </div>
        </div>
        <input id="checkin" name="checkin" type="text" class="form-control" required="required" wfd-id="13">
        <div class="input-group-append">
          <div class="input-group-text">
            <i class="fa "></i>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="form-group row">
    <label for="checkout" class="col-2 col-form-label">Check-Out</label>
    <div class="col-10">
      <div class="input-group">
        <div class="input-group-prepend">
          <div class="input-group-text">
            <i class="fa fa-calendar"></i>
          </div>
        </div>
        <input id="checkout" name="checkout" type="text" class="form-control" required="required" wfd-id="12">
        <div class="input-group-append">
          <div class="input-group-text">
            <i class="fa "></i>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="form-group row">
    <label for="text" class="col-2 col-form-label">Name</label>
    <div class="col-10">
      <div class="input-group">
        <div class="input-group-prepend">
          <div class="input-group-text">
            <i class="fa fa-user"></i>
          </div>
        </div>
        <input id="text" name="text" type="text" required="required" class="form-control" wfd-id="11">
        <div class="input-group-append">
          <div class="input-group-text">
            <i class="fa "></i>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="form-group row">
    <label for="email_id" class="col-2 col-form-label">Email</label>
    <div class="col-10">
      <div class="input-group">
        <div class="input-group-prepend">
          <div class="input-group-text">
            <i class="fa fa-envelope-o"></i>
          </div>
        </div>
        <input id="email" name="email" type="email" required="required" class="form-control" wfd-id="10">
        <div class="input-group-append">
          <div class="input-group-text">
            <i class="fa "></i>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="form-group row">
    <label for="phone" class="col-2 col-form-label">Phone #</label>
    <div class="col-10">
      <div class="input-group">
        <div class="input-group-prepend">
          <div class="input-group-text">
            <i class="fa fa-phone"></i>
          </div>
        </div>
        <input id="phone" name="phone" placeholder="11 numeric" type="tel" required pattern="\d{11}" label="11 digits" class="form-control" wfd-id="9">
        <div class="input-group-append">
          <div class="input-group-text">
            <i class="fa "></i>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="form-group row">
    <label class="col-2">Room Type</label>
    <div class="col-10">
      <div class="custom-control custom-checkbox custom-control-inline">
        <input name="roomtype" id="roomtype_0" type="checkbox" class="custom-control-input" value="" checked wfd-id="8">
        <label for="roomtype_0" class="custom-control-label">Deluxe Room</label>
      </div>
      <div class="custom-control custom-checkbox custom-control-inline">
        <input name="roomtype" id="roomtype_1" type="checkbox" class="custom-control-input" value="" wfd-id="7">
        <label for="roomtype_1" class="custom-control-label">Junior Suite</label>
      </div>
      <div class="custom-control custom-checkbox custom-control-inline">
        <input name="roomtype" id="roomtype_2" type="checkbox" class="custom-control-input" value="" wfd-id="6">
        <label for="roomtype_2" class="custom-control-label">Family Suite</label>
      </div>
      <div class="custom-control custom-checkbox custom-control-inline">
        <input name="roomtype" id="roomtype_3" type="checkbox" class="custom-control-input" value="" wfd-id="5">
        <label for="roomtype_3" class="custom-control-label">Cameron Suite</label>
      </div>
      <div class="custom-control custom-checkbox custom-control-inline">
        <input name="roomtype" id="roomtype_4" type="checkbox" class="custom-control-input" value="" wfd-id="4">
        <label for="roomtype_4" class="custom-control-label">Foster Suite</label>
      </div>
    </div>
  </div>
  <div class="form-group row">
    <label class="col-2">Room Preference</label>
    <div class="col-10">
      <div class="custom-control custom-radio custom-control-inline">
        <input name="preference" id="preference_0" type="radio" class="custom-control-input" value="No Preference" required="required" wfd-id="3">
        <label for="preference_0" class="custom-control-label">No Preference</label>
      </div>
      <div class="custom-control custom-radio custom-control-inline">
        <input name="preference" id="preference_1" type="radio" class="custom-control-input" value="Non Smoking" required="required" wfd-id="2">
        <label for="preference_1" class="custom-control-label">Non Smoking</label>
      </div>
      <div class="custom-control custom-radio custom-control-inline">
        <input name="preference" id="preference_2" type="radio" class="custom-control-input" value="Smoking" required="required" wfd-id="1">
        <label for="preference_2" class="custom-control-label">Smoking</label>
      </div>
    </div>
  </div>
  <div class="form-group row">
    <label for="adults" class="col-2 col-form-label">Adults</label>
    <div class="col-10">
      <select id="adults" name="adults" class="custom-select" required="required" wfd-id="16">
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
      </select>
    </div>
  </div>
  <div class="form-group row">
    <label for="children" class="col-2 col-form-label">Children</label>
    <div class="col-10">
      <select id="children" name="children" class="custom-select" wfd-id="15">
        <option value="None">None</option>
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
      </select>
    </div>
  </div>
  <div class="form-group row">
    <label for="textarea" class="col-2 col-form-label">Special Requirement</label>
    <div class="col-10">
      <textarea id="specialTxtarea" name="specialTxtarea" cols="40" rows="5" class="form-control" wfd-id="17"></textarea>
    </div>
  </div>
  <div class="form-group row">
    <div class="offset-2 col-10">
      <button name="alpsubmit" type="submit" class="btn btn-primary btn-block" wfd-id="18">Submit</button>

    </div>

  </div>
</form>
</div>
<script>
function myFunction() {
  var requiredFields = document.getElementById('specialTxtarea');
  window.alert('Thank for your Reservation');
  //window.location = 'index.html';
}
</script>
</body>
</html>
</code>```

Body:
function myFunction() {
  var requiredFields = document.getElementById('specialTxtarea');
  window.alert('Thank for your Reservation');
  window.location = 'index.html';
}

<form>

    Check-In

        <input id="checkin" name="checkin" type="text" class="form-control" required="required" wfd-id="13">

    Check-Out

        <input id="checkout" name="checkout" type="text" class="form-control" required="required" wfd-id="12">

    Name

        <input id="text" name="text" type="text" required="required" class="form-control" wfd-id="11">

    Email

        <input id="email" name="email" type="email" required="required" class="form-control" wfd-id="10">

    Phone #

        <input id="phone" name="phone" placeholder="11 numeric" type="tel" required pattern="\d{11}" label="11 digits" class="form-control" wfd-id="9">

    Room Type

        <input name="roomtype" id="roomtype_0" type="checkbox" class="custom-control-input" value="" checked wfd-id="8">
        Deluxe Room

        <input name="roomtype" id="roomtype_1" type="checkbox" class="custom-control-input" value="" wfd-id="7">
        Junior Suite

        <input name="roomtype" id="roomtype_2" type="checkbox" class="custom-control-input" value="" wfd-id="6">
        Family Suite

        <input name="roomtype" id="roomtype_3" type="checkbox" class="custom-control-input" value="" wfd-id="5">
        Cameron Suite

        <input name="roomtype" id="roomtype_4" type="checkbox" class="custom-control-input" value="" wfd-id="4">
        Foster Suite

    Room Preference

        <input name="preference" id="preference_0" type="radio" class="custom-control-input" value="No Preference" required="required" wfd-id="3">
        No Preference

        <input name="preference" id="preference_1" type="radio" class="custom-control-input" value="Non Smoking" required="required" wfd-id="2">
        Non Smoking

        <input name="preference" id="preference_2" type="radio" class="custom-control-input" value="Smoking" required="required" wfd-id="1">
        Smoking

    Adults

      <select id="adults" name="adults" class="custom-select" required="required" wfd-id="16">
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
      </select>

    Children

      <select id="children" name="children" class="custom-select" wfd-id="15">
        <option value="None">None</option>
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
      </select>

    Special Requirement

      <textarea id="specialTxtarea" name="specialTxtarea" cols="40" rows="5" class="form-control" wfd-id="17"></textarea>

      <button name="alpsubmit" type="submit" class="btn btn-primary btn-block" wfd-id="18" onclick="myFunction()">Submit</button>

</form>

This is for my assignment. For this reservation form, I am not required to use PHP to validate. What I am required is to have the form validate the field and upon submit, a response using window alert to pop out.

My lecturer has actually worked through with me and managed to get my codes to work. But somehow.. after I got home. I am unable to get the form to validate prior to submit and go back to home page

I was expecting that the form created will check through all field and be prompt prior to submit button pressed and go through window.alert with a Thank you response and bring back to index.html

Body:
I removed the on click on submit and added action="javascript:myFunction();" for the form and it will work here's the code for it.

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<form id="myForm" action="javascript:myFunction();">
  <div class="form-group row">
    <label for="checkin" class="col-2 col-form-label">Check-In</label>
    <div class="col-10">
      <div class="input-group">
        <div class="input-group-prepend">
          <div class="input-group-text">
            <i class="fa fa-calendar"></i>
          </div>
        </div>
        <input id="checkin" name="checkin" type="text" class="form-control" required="required" wfd-id="13">
        <div class="input-group-append">
          <div class="input-group-text">
            <i class="fa "></i>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="form-group row">
    <label for="checkout" class="col-2 col-form-label">Check-Out</label>
    <div class="col-10">
      <div class="input-group">
        <div class="input-group-prepend">
          <div class="input-group-text">
            <i class="fa fa-calendar"></i>
          </div>
        </div>
        <input id="checkout" name="checkout" type="text" class="form-control" required="required" wfd-id="12">
        <div class="input-group-append">
          <div class="input-group-text">
            <i class="fa "></i>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="form-group row">
    <label for="text" class="col-2 col-form-label">Name</label>
    <div class="col-10">
      <div class="input-group">
        <div class="input-group-prepend">
          <div class="input-group-text">
            <i class="fa fa-user"></i>
          </div>
        </div>
        <input id="text" name="text" type="text" required="required" class="form-control" wfd-id="11">
        <div class="input-group-append">
          <div class="input-group-text">
            <i class="fa "></i>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="form-group row">
    <label for="email_id" class="col-2 col-form-label">Email</label>
    <div class="col-10">
      <div class="input-group">
        <div class="input-group-prepend">
          <div class="input-group-text">
            <i class="fa fa-envelope-o"></i>
          </div>
        </div>
        <input id="email" name="email" type="email" required="required" class="form-control" wfd-id="10">
        <div class="input-group-append">
          <div class="input-group-text">
            <i class="fa "></i>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="form-group row">
    <label for="phone" class="col-2 col-form-label">Phone #</label>
    <div class="col-10">
      <div class="input-group">
        <div class="input-group-prepend">
          <div class="input-group-text">
            <i class="fa fa-phone"></i>
          </div>
        </div>
        <input id="phone" name="phone" placeholder="11 numeric" type="tel" required pattern="\d{11}" label="11 digits" class="form-control" wfd-id="9">
        <div class="input-group-append">
          <div class="input-group-text">
            <i class="fa "></i>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="form-group row">
    <label class="col-2">Room Type</label>
    <div class="col-10">
      <div class="custom-control custom-checkbox custom-control-inline">
        <input name="roomtype" id="roomtype_0" type="checkbox" class="custom-control-input" value="" checked wfd-id="8">
        <label for="roomtype_0" class="custom-control-label">Deluxe Room</label>
      </div>
      <div class="custom-control custom-checkbox custom-control-inline">
        <input name="roomtype" id="roomtype_1" type="checkbox" class="custom-control-input" value="" wfd-id="7">
        <label for="roomtype_1" class="custom-control-label">Junior Suite</label>
      </div>
      <div class="custom-control custom-checkbox custom-control-inline">
        <input name="roomtype" id="roomtype_2" type="checkbox" class="custom-control-input" value="" wfd-id="6">
        <label for="roomtype_2" class="custom-control-label">Family Suite</label>
      </div>
      <div class="custom-control custom-checkbox custom-control-inline">
        <input name="roomtype" id="roomtype_3" type="checkbox" class="custom-control-input" value="" wfd-id="5">
        <label for="roomtype_3" class="custom-control-label">Cameron Suite</label>
      </div>
      <div class="custom-control custom-checkbox custom-control-inline">
        <input name="roomtype" id="roomtype_4" type="checkbox" class="custom-control-input" value="" wfd-id="4">
        <label for="roomtype_4" class="custom-control-label">Foster Suite</label>
      </div>
    </div>
  </div>
  <div class="form-group row">
    <label class="col-2">Room Preference</label>
    <div class="col-10">
      <div class="custom-control custom-radio custom-control-inline">
        <input name="preference" id="preference_0" type="radio" class="custom-control-input" value="No Preference" required="required" wfd-id="3">
        <label for="preference_0" class="custom-control-label">No Preference</label>
      </div>
      <div class="custom-control custom-radio custom-control-inline">
        <input name="preference" id="preference_1" type="radio" class="custom-control-input" value="Non Smoking" required="required" wfd-id="2">
        <label for="preference_1" class="custom-control-label">Non Smoking</label>
      </div>
      <div class="custom-control custom-radio custom-control-inline">
        <input name="preference" id="preference_2" type="radio" class="custom-control-input" value="Smoking" required="required" wfd-id="1">
        <label for="preference_2" class="custom-control-label">Smoking</label>
      </div>
    </div>
  </div>
  <div class="form-group row">
    <label for="adults" class="col-2 col-form-label">Adults</label>
    <div class="col-10">
      <select id="adults" name="adults" class="custom-select" required="required" wfd-id="16">
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
      </select>
    </div>
  </div>
  <div class="form-group row">
    <label for="children" class="col-2 col-form-label">Children</label>
    <div class="col-10">
      <select id="children" name="children" class="custom-select" wfd-id="15">
        <option value="None">None</option>
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
      </select>
    </div>
  </div>
  <div class="form-group row">
    <label for="textarea" class="col-2 col-form-label">Special Requirement</label>
    <div class="col-10">
      <textarea id="specialTxtarea" name="specialTxtarea" cols="40" rows="5" class="form-control" wfd-id="17"></textarea>
    </div>
  </div>
  <div class="form-group row">
    <div class="offset-2 col-10">
      <button name="alpsubmit" type="submit" class="btn btn-primary btn-block" wfd-id="18">Submit</button>

    </div>

  </div>
</form>
</div>
<script>
function myFunction() {
  var requiredFields = document.getElementById('specialTxtarea');
  window.alert('Thank for your Reservation');
  //window.location = 'index.html';
}
</script>
</body>
</html>


问:
4bit transfer using synchronous d flip-flop( transfer 4bit from register a to register b)
When I run this code two errors appear that say "Actual parameter type in port map does not match the type of the formal port 's'. I need help to understand how to fix these.        </p>

```<code>-- code that try in EDA playground to transfer from one register to another

 -- library
 library ieee;
 use ieee. std_logic_1164.all;

 -- declaration for d flip-flop
 entity D_FF is
 PORT( D : in std_logic_vector(7 downto 0);
       s :in std_logic;
       CLOCK: in std_logic;
       Q: out std_logic_vector(7 downto 0));
  end D_FF;

 architecture behavioral of D_FF is
 -- signals declaration
 signal s1,s2,s3,s4,s5,s6,s7,s8: std_logic;
 begin

 --transfer the 4 bit to another register
s1 <= D(0) and (not s);
Q(0) <= s and D(0);
s2 <= D(1) and (not s);
Q(1) <= (Q(0)and s) or s2;
s3 <= D(2) and (not s);
Q(2) <= (Q(1)and s) or s3;
s4 <= D(3) and not s;
Q(3) <= (Q(2)and s)or s4;
s5 <= D(4) and not s;
Q(4) <= (Q(3)and s)or s5;
s6 <= D(5) and not s;
Q(5) <= (Q(4)and s)or s6;
s7 <= D(6) and not s;
Q(6) <= (Q(5)and s)or s7;
s8 <= D(7) and not s;
Q(7) <= (Q(6)and s)or s8;

end behavioral;

 ------------------------------
-- testbench
 ------------------------------
 -- library
library ieee;
use ieee. std_logic_1164.all;

entity testbench is
-- empty entity
end testbench;
-----------------------------
architecture tb of testbench is -- testbench
-- architecture  -- REDUNDANT transcription error?
 -- component declaration
 component D_FF is
 PORT( D : in std_logic_vector(7 downto 0);
       s :in std_logic;
       CLOCK: in std_logic;
       Q: out std_logic_vector(7 downto 0));
  end component;

  -- signals that need in testbench -- COMMENT DELIMITER transcription error?
  signal D_s: std_logic_vector(7 downto 0);-- signals for entity i/o
  signal Q_s: std_logic_vector(7 downto 0);-- signals for entity i/o
  signal s_s: std_logic;
  signal CLOCK_s: std_logic;
  -- is the signal that must be run 4 time to transfer the bit
  signal loop_count: integer;
   begin

  dut:D_FF port map(D_s,Q_s,s_s,CLOCK_s);
  -- design under test instantiation

 stimProcess: process                                           --
 --stimulus generator
  begin
    --the run 4 time this to transfer the 4 bit
    for loop_counter in 0 to 3 loop
    D_s <= "01100000";
    wait until CLOCK_s = '1' and CLOCK_s'event;
    end loop;

  end process stimProcess;
  -- without sensitivity list
  end tb;
</code>```

答:
You are using a positional association for the port map. When you do this, the order of ports in your port map must match the order of ports in your component declaration. Using positional association, the proper order is:

dut:D_FF port map(D_s,s_s,CLOCK_s,Q_s);
```

<p>Note that in your example, you've connected the signal <code>Q_s</code> to <code>s</code>, <code>s_s</code> to <code>CLOCK</code>, and <code>CLOCK_s</code> to <code>Q</code> (because your order was not the same).</p>

<p>I always prefer named association. On the left, you have your "formal" (the port outlined in your component declaration). On the right, you have the "actual" (the signal you're connecting to that port). The whitespace is just to improve readability.</p>

<pre class="lang-vhdl prettyprint-override"><code>dut: D_FF
  port map (
    D     => D_s,
    s     => s_s,
    CLOCK => CLOCK_s,
    Q     => Q_s
  );
</code>```

Named association port maps are much easier to debug, and the ports can be mapped in any order.

Body:
When I run this code two errors appear that say "Actual parameter type in port map does not match the type of the formal port 's'. I need help to understand how to fix these.

-- code that try in EDA playground to transfer from one register to another

 -- library
 library ieee;
 use ieee. std_logic_1164.all;

 -- declaration for d flip-flop
 entity D_FF is
 PORT( D : in std_logic_vector(7 downto 0);
       s :in std_logic;
       CLOCK: in std_logic;
       Q: out std_logic_vector(7 downto 0));
  end D_FF;

 architecture behavioral of D_FF is
 -- signals declaration
 signal s1,s2,s3,s4,s5,s6,s7,s8: std_logic;
 begin

 --transfer the 4 bit to another register
s1 <= D(0) and (not s);
Q(0) <= s and D(0);
s2 <= D(1) and (not s);
Q(1) <= (Q(0)and s) or s2;
s3 <= D(2) and (not s);
Q(2) <= (Q(1)and s) or s3;
s4 <= D(3) and not s;
Q(3) <= (Q(2)and s)or s4;
s5 <= D(4) and not s;
Q(4) <= (Q(3)and s)or s5;
s6 <= D(5) and not s;
Q(5) <= (Q(4)and s)or s6;
s7 <= D(6) and not s;
Q(6) <= (Q(5)and s)or s7;
s8 <= D(7) and not s;
Q(7) <= (Q(6)and s)or s8;

end behavioral;

 ------------------------------
-- testbench
 ------------------------------
 -- library
library ieee;
use ieee. std_logic_1164.all;

entity testbench is
-- empty entity
end testbench;
-----------------------------
architecture tb of testbench is -- testbench
-- architecture  -- REDUNDANT transcription error?
 -- component declaration
 component D_FF is
 PORT( D : in std_logic_vector(7 downto 0);
       s :in std_logic;
       CLOCK: in std_logic;
       Q: out std_logic_vector(7 downto 0));
  end component;

  -- signals that need in testbench -- COMMENT DELIMITER transcription error?
  signal D_s: std_logic_vector(7 downto 0);-- signals for entity i/o
  signal Q_s: std_logic_vector(7 downto 0);-- signals for entity i/o
  signal s_s: std_logic;
  signal CLOCK_s: std_logic;
  -- is the signal that must be run 4 time to transfer the bit
  signal loop_count: integer;
   begin

  dut:D_FF port map(D_s,Q_s,s_s,CLOCK_s);
  -- design under test instantiation

 stimProcess: process                                           --
 --stimulus generator
  begin
    --the run 4 time this to transfer the 4 bit
    for loop_counter in 0 to 3 loop
    D_s <= "01100000";
    wait until CLOCK_s = '1' and CLOCK_s'event;
    end loop;

  end process stimProcess;
  -- without sensitivity list
  end tb;

Body:
You are using a positional association for the port map. When you do this, the order of ports in your port map must match the order of ports in your component declaration. Using positional association, the proper order is:

dut:D_FF port map(D_s,s_s,CLOCK_s,Q_s);

Note that in your example, you've connected the signal Q_s to s, s_s to CLOCK, and CLOCK_s to Q (because your order was not the same).

I always prefer named association. On the left, you have your "formal" (the port outlined in your component declaration). On the right, you have the "actual" (the signal you're connecting to that port). The whitespace is just to improve readability.

dut: D_FF
  port map (
    D     => D_s,
    s     => s_s,
    CLOCK => CLOCK_s,
    Q     => Q_s
  );

Named association port maps are much easier to debug, and the ports can be mapped in any order.