问:
Implementing pattern matching in C#
In Scala, you can use pattern matching to produce a result depending on the type of the input. For instance:

```<code>val title = content match {
    case blogPost: BlogPost => blogPost.blog.title + ": " + blogPost.title
    case blog: Blog => blog.title
}
</code>```

In C#, I'd ideally like to be able to write:

```<code>var title = Visit(content,
    (BlogPost blogPost) => blogPost.Blog.Title + ": " + blogPost.Title,
    (Blog blog) => blog.Title
);
</code>```

Is this possible? When I've tried writing it as a single method, I don't know how to specify the generics. The following implementation seems right, apart from getting the type checker to allow functions that accept subtypes of T:

```<code>    public TResult Visit<T, TResult>(T value, params Func<T, TResult>[] visitors)
    {
        foreach (var visitor in visitors)
        {
            if (visitor.Method.GetGenericArguments()[0].IsAssignableFrom(value.GetType()))
            {
                return visitor(value);
            }
        }
        throw new ApplicationException("No match");
    }
</code>```

The closest I've gotten is to add the functions to an object individually, and then call visit on a value:

```<code>    public class Visitor<T, TResult>
    {
        private class Result
        {
            public bool HasResult;
            public TResult ResultValue;
        }

        private readonly IList<Func<T, Result>> m_Visitors = new List<Func<T, Result>>();

        public TResult Visit(T value)
        {
            foreach (var visitor in m_Visitors)
            {
                var result = visitor(value);
                if (result.HasResult)
                {
                    return result.ResultValue;
                }
            }
            throw new ApplicationException("No match");
        }

        public Visitor<T, TResult> Add<TIn>(Func<TIn, TResult> visitor) where TIn : T
        {
            m_Visitors.Add(value =>
            {
                if (value is TIn)
                {
                    return new Result { HasResult = true, ResultValue = visitor((TIn)value) };
                }
                return new Result { HasResult = false };
            });
            return this;
        }
    }
</code>```

This can be used like so:

```<code>var title = new Visitor<IContent, string>()
    .Add((BlogPost blogPost) => blogPost.Blog.Title + ": " + blogPost.Title)
    .Add((Blog blog) => blog.Title)
    .Visit(content);
</code>```

Any idea how to do this with a single method call?

答:
Pattern matching is one of those lovely features mostly found in functional programming languages like F#. There is a great project going on in codeplex named Functional C#.
Consider the following F# code:

```<code>let operator x = match x with
                 | ExpressionType.Add -> "+"

let rec toString exp = match exp with
                       | LambdaExpression(args, body) -> toString(body)
                       | ParameterExpression(name) -> name
                       | BinaryExpression(op,l,r) -> sprintf "%s %s %s" (toString l) (operator op) (toString r)
</code>```

Using the Functional C# library, the C# equivalent would be:

```<code>var Op = new Dictionary<ExpressionType, string> { { ExpressionType.Add, "+" } };

Expression<Func<int,int,int>> add = (x,y) => x + y;

Func<Expression, string> toString = null;
 toString = exp =>
 exp.Match()
    .With<LambdaExpression>(l => toString(l.Body))
    .With<ParameterExpression>(p => p.Name)
    .With<BinaryExpression>(b => String.Format("{0} {1} {2}", toString(b.Left), Op[b.NodeType], toString(b.Right)))
    .Return<string>();
</code>```

Title: Implementing pattern matching in C#

Body:
In Scala, you can use pattern matching to produce a result depending on the type of the input. For instance:

val title = content match {
    case blogPost: BlogPost => blogPost.blog.title + ": " + blogPost.title
    case blog: Blog => blog.title
}

In C#, I'd ideally like to be able to write:

var title = Visit(content,
    (BlogPost blogPost) => blogPost.Blog.Title + ": " + blogPost.Title,
    (Blog blog) => blog.Title
);

Is this possible? When I've tried writing it as a single method, I don't know how to specify the generics. The following implementation seems right, apart from getting the type checker to allow functions that accept subtypes of T:

    public TResult Visit<T, TResult>(T value, params Func<T, TResult>[] visitors)
    {
        foreach (var visitor in visitors)
        {
            if (visitor.Method.GetGenericArguments()[0].IsAssignableFrom(value.GetType()))
            {
                return visitor(value);
            }
        }
        throw new ApplicationException("No match");
    }

The closest I've gotten is to add the functions to an object individually, and then call visit on a value:

    public class Visitor<T, TResult>
    {
        private class Result
        {
            public bool HasResult;
            public TResult ResultValue;
        }

        private readonly IList<Func<T, Result>> m_Visitors = new List<Func<T, Result>>();

        public TResult Visit(T value)
        {
            foreach (var visitor in m_Visitors)
            {
                var result = visitor(value);
                if (result.HasResult)
                {
                    return result.ResultValue;
                }
            }
            throw new ApplicationException("No match");
        }

        public Visitor<T, TResult> Add<TIn>(Func<TIn, TResult> visitor) where TIn : T
        {
            m_Visitors.Add(value =>
            {
                if (value is TIn)
                {
                    return new Result { HasResult = true, ResultValue = visitor((TIn)value) };
                }
                return new Result { HasResult = false };
            });
            return this;
        }
    }

This can be used like so:

var title = new Visitor<IContent, string>()
    .Add((BlogPost blogPost) => blogPost.Blog.Title + ": " + blogPost.Title)
    .Add((Blog blog) => blog.Title)
    .Visit(content);

Any idea how to do this with a single method call?

Body:
Pattern matching is one of those lovely features mostly found in functional programming languages like F#. There is a great project going on in codeplex named Functional C#.
Consider the following F# code:

let operator x = match x with
                 | ExpressionType.Add -> "+"

let rec toString exp = match exp with
                       | LambdaExpression(args, body) -> toString(body)
                       | ParameterExpression(name) -> name
                       | BinaryExpression(op,l,r) -> sprintf "%s %s %s" (toString l) (operator op) (toString r)

Using the Functional C# library, the C# equivalent would be:

var Op = new Dictionary<ExpressionType, string> { { ExpressionType.Add, "+" } };

Expression<Func<int,int,int>> add = (x,y) => x + y;

Func<Expression, string> toString = null;
 toString = exp =>
 exp.Match()
    .With<LambdaExpression>(l => toString(l.Body))
    .With<ParameterExpression>(p => p.Name)
    .With<BinaryExpression>(b => String.Format("{0} {1} {2}", toString(b.Left), Op[b.NodeType], toString(b.Right)))
    .Return<string>();


来源: stackexchange

问:
MySQL connection refused from Node on first run only (docker-compose)
I'm trying to build out a NodeJS/MySQL stack, but am experiencing an intermittent issue.

Here is my docker compose file:

```<code>version: '3'
services:
    db:
        image: mysql:5.7
        command: --default-authentication-plugin=mysql_native_password
        ports:
            - "3306:3306"
        environment:
            MYSQL_ROOT_PASSWORD: root
        container_name: 'db'
        networks:
            - db-network
        volumes:
            - db-data:/var/lib/mysql
            - ./db:/docker-entrypoint-initdb.d
    forum:
        image: "node:12"
        user: "node"
        working_dir: /home/node/app
        depends_on:
            - db
        ports:
            - 7000:3000
        environment:
          - NODE_ENV=development
          - PORT=3000
        volumes:
          - ./server:/home/node/app
        command: "npm start"
        networks:
            - db-network
    adminer:
        image: adminer
        restart: always
        networks:
            - db-network
        depends_on:
            - db
        ports:
          - 7777:8080
        environment:
          ADMINER_DEFAULT_DB_DRIVER: mysql
          ADMINER_DEFAULT_DB_HOST: db
volumes:
    db-data:
networks:
    db-network:
</code>```

You can see that I've got an SQL script mapped into the initdb entrypoint. This is really simple SQL, it simply creates the db: CREATE DATABASE IF NOT EXISTS forum;

Inside the Node container I'm using knex to talk to the database. When I instantiate knex, I also run any outstanding migrations:

```<code>const environment = process.env.ENVIRONMENT || 'development'
const Knex = require('knex');
const knexConfig = require('../knexfile');
const knex = Knex(knexConfig[environment]);

async function init() {
  try {
    return await knex.migrate.latest();
  } catch (error) {
    console.log(error);
  } finally {
    return;
  }
}

init();

module.exports = knex;
</code>```

The problem i'm getting only appears on 'first up' o docker-compose (or more specifically when it needs to create the db-data volume). If I drop the volume docker-compose down -V I get the error when 'up-ing' again. The problem is your classic ECONNREFUSED:

```<code>Creating network "forum_db-network" with the default driver
Creating volume "forum_db-data" with default driver
Creating db ... done
Creating forum_adminer_1 ... done
Creating forum_forum_1   ... done
Attaching to db, forum_adminer_1, forum_forum_1
db         | Initializing database
db         | 2020-02-20T09:50:46.701629Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
db         | 2020-02-20T09:50:47.004757Z 0 [Warning] InnoDB: New log files created, LSN=45790
db         | 2020-02-20T09:50:47.062521Z 0 [Warning] InnoDB: Creating foreign key constraint system tables.
db         | 2020-02-20T09:50:47.122917Z 0 [Warning] No existing UUID has been found, so we assume that this is the first time that this server has been started. Generating a new UUID: 7810f3c2-53c6-11ea-ba00-0242c0a81002.
db         | 2020-02-20T09:50:47.126689Z 0 [Warning] Gtid table is not ready to be used. Table 'mysql.gtid_executed' cannot be opened.
adminer_1  | [Thu Feb 20 09:50:47 2020] PHP 7.4.2 Development Server (http://[::]:8080) started
db         | 2020-02-20T09:50:47.127637Z 1 [Warning] root@localhost is created with an empty password ! Please consider switching off the --initialize-insecure option.
db         | 2020-02-20T09:50:47.955961Z 1 [Warning] 'user' entry 'root@localhost' ignored in --skip-name-resolve mode.
db         | 2020-02-20T09:50:47.956454Z 1 [Warning] 'user' entry 'mysql.session@localhost' ignored in --skip-name-resolve mode.
db         | 2020-02-20T09:50:47.957026Z 1 [Warning] 'user' entry 'mysql.sys@localhost' ignored in --skip-name-resolve mode.
db         | 2020-02-20T09:50:47.957747Z 1 [Warning] 'db' entry 'performance_schema mysql.session@localhost' ignored in --skip-name-resolve mode.
db         | 2020-02-20T09:50:47.958212Z 1 [Warning] 'db' entry 'sys mysql.sys@localhost' ignored in --skip-name-resolve mode.
db         | 2020-02-20T09:50:47.958797Z 1 [Warning] 'proxies_priv' entry '@ root@localhost' ignored in --skip-name-resolve mode.
db         | 2020-02-20T09:50:47.959520Z 1 [Warning] 'tables_priv' entry 'user mysql.session@localhost' ignored in --skip-name-resolve mode.
db         | 2020-02-20T09:50:47.960113Z 1 [Warning] 'tables_priv' entry 'sys_config mysql.sys@localhost' ignored in --skip-name-resolve mode.
forum_1    |
forum_1    | > express-oauth-vuex-starter@1.0.0 start /home/node/app
forum_1    | > nodemon index.js
forum_1    |
forum_1    | [nodemon] 2.0.2
forum_1    | [nodemon] to restart at any time, enter `rs`
forum_1    | [nodemon] watching dir(s): *.*
forum_1    | [nodemon] watching extensions: js,mjs,json
forum_1    | [nodemon] starting `node index.js`
db         | Database initialized
db         | Initializing certificates
db         | Generating a RSA private key
db         | ........................................................................................................................+++++
db         | ..........+++++
db         | unable to write 'random state'
db         | writing new private key to 'ca-key.pem'
db         | -----
db         | Generating a RSA private key
db         | .........................................................................................+++++
db         | .............+++++
db         | unable to write 'random state'
db         | writing new private key to 'server-key.pem'
db         | -----
db         | Generating a RSA private key
db         | .....................................................+++++
db         | .+++++
db         | unable to write 'random state'
db         | writing new private key to 'client-key.pem'
db         | -----
db         | Certificates initialized
db         | MySQL init process in progress...
db         | 2020-02-20T09:50:51.037907Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
db         | 2020-02-20T09:50:51.039423Z 0 [Note] mysqld (mysqld 5.7.24) starting as process 89 ...
db         | 2020-02-20T09:50:51.044545Z 0 [Note] InnoDB: PUNCH HOLE support available
db         | 2020-02-20T09:50:51.044653Z 0 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins
db         | 2020-02-20T09:50:51.044701Z 0 [Note] InnoDB: Uses event mutexes
db         | 2020-02-20T09:50:51.044745Z 0 [Note] InnoDB: GCC builtin __atomic_thread_fence() is used for memory barrier
db         | 2020-02-20T09:50:51.044786Z 0 [Note] InnoDB: Compressed tables use zlib 1.2.11
db         | 2020-02-20T09:50:51.044825Z 0 [Note] InnoDB: Using Linux native AIO
db         | 2020-02-20T09:50:51.045705Z 0 [Note] InnoDB: Number of pools: 1
db         | 2020-02-20T09:50:51.046113Z 0 [Note] InnoDB: Using CPU crc32 instructions
db         | 2020-02-20T09:50:51.048701Z 0 [Note] InnoDB: Initializing buffer pool, total size = 128M, instances = 1, chunk size = 128M
db         | 2020-02-20T09:50:51.060691Z 0 [Note] InnoDB: Completed initialization of buffer pool
db         | 2020-02-20T09:50:51.064263Z 0 [Note] InnoDB: If the mysqld execution user is authorized, page cleaner thread priority can be changed. See the man page of setpriority().
db         | 2020-02-20T09:50:51.076676Z 0 [Note] InnoDB: Highest supported file format is Barracuda.
db         | 2020-02-20T09:50:51.097380Z 0 [Note] InnoDB: Creating shared tablespace for temporary tables
db         | 2020-02-20T09:50:51.097533Z 0 [Note] InnoDB: Setting file './ibtmp1' size to 12 MB. Physically writing the file full; Please wait ...
db         | 2020-02-20T09:50:51.131620Z 0 [Note] InnoDB: File './ibtmp1' size is now 12 MB.
db         | 2020-02-20T09:50:51.134052Z 0 [Note] InnoDB: 96 redo rollback segment(s) found. 96 redo rollback segment(s) are active.
db         | 2020-02-20T09:50:51.134142Z 0 [Note] InnoDB: 32 non-redo rollback segment(s) are active.
db         | 2020-02-20T09:50:51.135177Z 0 [Note] InnoDB: Waiting for purge to start
db         | 2020-02-20T09:50:51.185530Z 0 [Note] InnoDB: 5.7.24 started; log sequence number 2591440
db         | 2020-02-20T09:50:51.186329Z 0 [Note] Plugin 'FEDERATED' is disabled.
db         | 2020-02-20T09:50:51.192075Z 0 [Note] Found ca.pem, server-cert.pem and server-key.pem in data directory. Trying to enable SSL support using them.
db         | 2020-02-20T09:50:51.192591Z 0 [Warning] CA certificate ca.pem is self signed.
db         | 2020-02-20T09:50:51.194602Z 0 [Note] InnoDB: Loading buffer pool(s) from /var/lib/mysql/ib_buffer_pool
db         | 2020-02-20T09:50:51.197793Z 0 [Note] InnoDB: Buffer pool(s) load completed at 200220  9:50:51
db         | 2020-02-20T09:50:51.198483Z 0 [Warning] Insecure configuration for --pid-file: Location '/var/run/mysqld' in the path is accessible to all OS users. Consider choosing a different directory.
db         | 2020-02-20T09:50:51.200316Z 0 [Warning] 'user' entry 'root@localhost' ignored in --skip-name-resolve mode.
db         | 2020-02-20T09:50:51.200460Z 0 [Warning] 'user' entry 'mysql.session@localhost' ignored in --skip-name-resolve mode.
db         | 2020-02-20T09:50:51.200532Z 0 [Warning] 'user' entry 'mysql.sys@localhost' ignored in --skip-name-resolve mode.
db         | 2020-02-20T09:50:51.200606Z 0 [Warning] 'db' entry 'performance_schema mysql.session@localhost' ignored in --skip-name-resolve mode.
db         | 2020-02-20T09:50:51.200656Z 0 [Warning] 'db' entry 'sys mysql.sys@localhost' ignored in --skip-name-resolve mode.
db         | 2020-02-20T09:50:51.200717Z 0 [Warning] 'proxies_priv' entry '@ root@localhost' ignored in --skip-name-resolve mode.
db         | 2020-02-20T09:50:51.202731Z 0 [Warning] 'tables_priv' entry 'user mysql.session@localhost' ignored in --skip-name-resolve mode.
db         | 2020-02-20T09:50:51.202816Z 0 [Warning] 'tables_priv' entry 'sys_config mysql.sys@localhost' ignored in --skip-name-resolve mode.
db         | 2020-02-20T09:50:51.219832Z 0 [Note] Event Scheduler: Loaded 0 events
db         | 2020-02-20T09:50:51.221248Z 0 [Note] mysqld: ready for connections.
db         | Version: '5.7.24'  socket: '/var/run/mysqld/mysqld.sock'  port: 0  MySQL Community Server (GPL)
forum_1    | Listening...
forum_1    | Error: connect ECONNREFUSED 192.168.16.2:3306
forum_1    |     at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1137:16)
forum_1    |     at Protocol._enqueue (/home/node/app/node_modules/mysql/lib/protocol/Protocol.js:144:48)
forum_1    |     at Protocol.handshake (/home/node/app/node_modules/mysql/lib/protocol/Protocol.js:51:23)
forum_1    |     at Connection.connect (/home/node/app/node_modules/mysql/lib/Connection.js:116:18)
forum_1    |     at /home/node/app/node_modules/knex/lib/dialects/mysql/index.js:69:18
forum_1    | From previous event:
forum_1    |     at Client_MySQL.acquireRawConnection (/home/node/app/node_modules/knex/lib/dialects/mysql/index.js:64:12)
forum_1    |     at create (/home/node/app/node_modules/knex/lib/client.js:291:39)
forum_1    |     at processTicksAndRejections (internal/process/task_queues.js:97:5) {
forum_1    |   errno: 'ECONNREFUSED',
forum_1    |   code: 'ECONNREFUSED',
forum_1    |   syscall: 'connect',
forum_1    |   address: '192.168.16.2',
forum_1    |   port: 3306,
forum_1    |   fatal: true
forum_1    | }
db         | Warning: Unable to load '/usr/share/zoneinfo/iso3166.tab' as time zone. Skipping it.
db         | Warning: Unable to load '/usr/share/zoneinfo/leap-seconds.list' as time zone. Skipping it.
db         | Warning: Unable to load '/usr/share/zoneinfo/zone.tab' as time zone. Skipping it.
db         | Warning: Unable to load '/usr/share/zoneinfo/zone1970.tab' as time zone. Skipping it.
db         | 2020-02-20T09:50:54.889060Z 4 [Warning] 'user' entry 'root@localhost' ignored in --skip-name-resolve mode.
db         | 2020-02-20T09:50:54.889116Z 4 [Warning] 'user' entry 'mysql.session@localhost' ignored in --skip-name-resolve mode.
db         | 2020-02-20T09:50:54.889137Z 4 [Warning] 'user' entry 'mysql.sys@localhost' ignored in --skip-name-resolve mode.
db         | 2020-02-20T09:50:54.889164Z 4 [Warning] 'db' entry 'performance_schema mysql.session@localhost' ignored in --skip-name-resolve mode.
db         | 2020-02-20T09:50:54.889172Z 4 [Warning] 'db' entry 'sys mysql.sys@localhost' ignored in --skip-name-resolve mode.
db         | 2020-02-20T09:50:54.889188Z 4 [Warning] 'proxies_priv' entry '@ root@localhost' ignored in --skip-name-resolve mode.
db         | 2020-02-20T09:50:54.890011Z 4 [Warning] 'tables_priv' entry 'user mysql.session@localhost' ignored in --skip-name-resolve mode.
db         | 2020-02-20T09:50:54.890057Z 4 [Warning] 'tables_priv' entry 'sys_config mysql.sys@localhost' ignored in --skip-name-resolve mode.
db         |
db         | /usr/local/bin/docker-entrypoint.sh: running /docker-entrypoint-initdb.d/init.sql
db         | mysql: [Warning] Using a password on the command line interface can be insecure.
db         |
db         |
db         | 2020-02-20T09:50:54.915362Z 0 [Note] Giving 0 client threads a chance to die gracefully
db         | 2020-02-20T09:50:54.915705Z 0 [Note] Shutting down slave threads
db         | 2020-02-20T09:50:54.916456Z 0 [Note] Forcefully disconnecting 0 remaining clients
db         | 2020-02-20T09:50:54.917013Z 0 [Note] Event Scheduler: Purging the queue. 0 events
db         | 2020-02-20T09:50:54.917696Z 0 [Note] Binlog end
db         | 2020-02-20T09:50:54.918665Z 0 [Note] Shutting down plugin 'ngram'
db         | 2020-02-20T09:50:54.919138Z 0 [Note] Shutting down plugin 'partition'
db         | 2020-02-20T09:50:54.919357Z 0 [Note] Shutting down plugin 'BLACKHOLE'
db         | 2020-02-20T09:50:54.920107Z 0 [Note] Shutting down plugin 'ARCHIVE'
db         | 2020-02-20T09:50:54.920322Z 0 [Note] Shutting down plugin 'PERFORMANCE_SCHEMA'
db         | 2020-02-20T09:50:54.921325Z 0 [Note] Shutting down plugin 'MRG_MYISAM'
db         | 2020-02-20T09:50:54.921840Z 0 [Note] Shutting down plugin 'MyISAM'
db         | 2020-02-20T09:50:54.922751Z 0 [Note] Shutting down plugin 'INNODB_SYS_VIRTUAL'
db         | 2020-02-20T09:50:54.923300Z 0 [Note] Shutting down plugin 'INNODB_SYS_DATAFILES'
db         | 2020-02-20T09:50:54.923360Z 0 [Note] Shutting down plugin 'INNODB_SYS_TABLESPACES'
db         | 2020-02-20T09:50:54.923589Z 0 [Note] Shutting down plugin 'INNODB_SYS_FOREIGN_COLS'
db         | 2020-02-20T09:50:54.923959Z 0 [Note] Shutting down plugin 'INNODB_SYS_FOREIGN'
db         | 2020-02-20T09:50:54.924112Z 0 [Note] Shutting down plugin 'INNODB_SYS_FIELDS'
db         | 2020-02-20T09:50:54.924269Z 0 [Note] Shutting down plugin 'INNODB_SYS_COLUMNS'
db         | 2020-02-20T09:50:54.924754Z 0 [Note] Shutting down plugin 'INNODB_SYS_INDEXES'
db         | 2020-02-20T09:50:54.925454Z 0 [Note] Shutting down plugin 'INNODB_SYS_TABLESTATS'
db         | 2020-02-20T09:50:54.925535Z 0 [Note] Shutting down plugin 'INNODB_SYS_TABLES'
db         | 2020-02-20T09:50:54.925688Z 0 [Note] Shutting down plugin 'INNODB_FT_INDEX_TABLE'
db         | 2020-02-20T09:50:54.925728Z 0 [Note] Shutting down plugin 'INNODB_FT_INDEX_CACHE'
db         | 2020-02-20T09:50:54.926261Z 0 [Note] Shutting down plugin 'INNODB_FT_CONFIG'
db         | 2020-02-20T09:50:54.926443Z 0 [Note] Shutting down plugin 'INNODB_FT_BEING_DELETED'
db         | 2020-02-20T09:50:54.926836Z 0 [Note] Shutting down plugin 'INNODB_FT_DELETED'
db         | 2020-02-20T09:50:54.927513Z 0 [Note] Shutting down plugin 'INNODB_FT_DEFAULT_STOPWORD'
db         | 2020-02-20T09:50:54.927560Z 0 [Note] Shutting down plugin 'INNODB_METRICS'
db         | 2020-02-20T09:50:54.927718Z 0 [Note] Shutting down plugin 'INNODB_TEMP_TABLE_INFO'
db         | 2020-02-20T09:50:54.927806Z 0 [Note] Shutting down plugin 'INNODB_BUFFER_POOL_STATS'
db         | 2020-02-20T09:50:54.927847Z 0 [Note] Shutting down plugin 'INNODB_BUFFER_PAGE_LRU'
db         | 2020-02-20T09:50:54.928201Z 0 [Note] Shutting down plugin 'INNODB_BUFFER_PAGE'
db         | 2020-02-20T09:50:54.928360Z 0 [Note] Shutting down plugin 'INNODB_CMP_PER_INDEX_RESET'
db         | 2020-02-20T09:50:54.928817Z 0 [Note] Shutting down plugin 'INNODB_CMP_PER_INDEX'
db         | 2020-02-20T09:50:54.929031Z 0 [Note] Shutting down plugin 'INNODB_CMPMEM_RESET'
db         | 2020-02-20T09:50:54.929717Z 0 [Note] Shutting down plugin 'INNODB_CMPMEM'
db         | 2020-02-20T09:50:54.929740Z 0 [Note] Shutting down plugin 'INNODB_CMP_RESET'
db         | 2020-02-20T09:50:54.929898Z 0 [Note] Shutting down plugin 'INNODB_CMP'
db         | 2020-02-20T09:50:54.929912Z 0 [Note] Shutting down plugin 'INNODB_LOCK_WAITS'
db         | 2020-02-20T09:50:54.930509Z 0 [Note] Shutting down plugin 'INNODB_LOCKS'
db         | 2020-02-20T09:50:54.930535Z 0 [Note] Shutting down plugin 'INNODB_TRX'
db         | 2020-02-20T09:50:54.930549Z 0 [Note] Shutting down plugin 'InnoDB'
db         | 2020-02-20T09:50:54.931131Z 0 [Note] InnoDB: FTS optimize thread exiting.
db         | 2020-02-20T09:50:54.931746Z 0 [Note] InnoDB: Starting shutdown...
db         | 2020-02-20T09:50:55.032188Z 0 [Note] InnoDB: Dumping buffer pool(s) to /var/lib/mysql/ib_buffer_pool
db         | 2020-02-20T09:50:55.032448Z 0 [Note] InnoDB: Buffer pool(s) dump completed at 200220  9:50:55
</code>```

If the volume already exists, I get no errors, knex connects and the migrations are run.

In the error log you can see that the Node container starts up directly after mysqld: ready for connections. However, you can see that after the Node error, the db container then runs init.sql. Presumably this means that knex is trying to connect to a specific database before it exists, which I guess could be the cause of the refused connection.

So I guess I'm looking for a way to defer the instantiation of the node container until after the MySQL container has run init.sql. I'm already using the depends_on docker compose property - are there any other docker options available to me?

答:
There's no native solution that I'm aware of, I'm afraid.

For waiting for a service to become available in general, I've used wait-for-it, but in your case you'd need something to verify MySQL also contains the database your app requires.

Maybe a simple Node script that loops a connection and attempts to select the database before running your app proper.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to build out a NodeJS/MySQL stack, but am experiencing an intermittent issue.

Here is my docker compose file:

version: '3'
services:
    db:
        image: mysql:5.7
        command: --default-authentication-plugin=mysql_native_password
        ports:
            - "3306:3306"
        environment:
            MYSQL_ROOT_PASSWORD: root
        container_name: 'db'
        networks:
            - db-network
        volumes:
            - db-data:/var/lib/mysql
            - ./db:/docker-entrypoint-initdb.d
    forum:
        image: "node:12"
        user: "node"
        working_dir: /home/node/app
        depends_on:
            - db
        ports:
            - 7000:3000
        environment:
          - NODE_ENV=development
          - PORT=3000
        volumes:
          - ./server:/home/node/app
        command: "npm start"
        networks:
            - db-network
    adminer:
        image: adminer
        restart: always
        networks:
            - db-network
        depends_on:
            - db
        ports:
          - 7777:8080
        environment:
          ADMINER_DEFAULT_DB_DRIVER: mysql
          ADMINER_DEFAULT_DB_HOST: db
volumes:
    db-data:
networks:
    db-network:

You can see that I've got an SQL script mapped into the initdb entrypoint. This is really simple SQL, it simply creates the db: CREATE DATABASE IF NOT EXISTS forum;

Inside the Node container I'm using knex to talk to the database. When I instantiate knex, I also run any outstanding migrations:

const environment = process.env.ENVIRONMENT || 'development'
const Knex = require('knex');
const knexConfig = require('../knexfile');
const knex = Knex(knexConfig[environment]);

async function init() {
  try {
    return await knex.migrate.latest();
  } catch (error) {
    console.log(error);
  } finally {
    return;
  }
}

init();

module.exports = knex;

The problem i'm getting only appears on 'first up' o docker-compose (or more specifically when it needs to create the db-data volume). If I drop the volume docker-compose down -V I get the error when 'up-ing' again. The problem is your classic ECONNREFUSED:

Creating network "forum_db-network" with the default driver
Creating volume "forum_db-data" with default driver
Creating db ... done
Creating forum_adminer_1 ... done
Creating forum_forum_1   ... done
Attaching to db, forum_adminer_1, forum_forum_1
db         | Initializing database
db         | 2020-02-20T09:50:46.701629Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
db         | 2020-02-20T09:50:47.004757Z 0 [Warning] InnoDB: New log files created, LSN=45790
db         | 2020-02-20T09:50:47.062521Z 0 [Warning] InnoDB: Creating foreign key constraint system tables.
db         | 2020-02-20T09:50:47.122917Z 0 [Warning] No existing UUID has been found, so we assume that this is the first time that this server has been started. Generating a new UUID: 7810f3c2-53c6-11ea-ba00-0242c0a81002.
db         | 2020-02-20T09:50:47.126689Z 0 [Warning] Gtid table is not ready to be used. Table 'mysql.gtid_executed' cannot be opened.
adminer_1  | [Thu Feb 20 09:50:47 2020] PHP 7.4.2 Development Server (http://[::]:8080) started
db         | 2020-02-20T09:50:47.127637Z 1 [Warning] root@localhost is created with an empty password ! Please consider switching off the --initialize-insecure option.
db         | 2020-02-20T09:50:47.955961Z 1 [Warning] 'user' entry 'root@localhost' ignored in --skip-name-resolve mode.
db         | 2020-02-20T09:50:47.956454Z 1 [Warning] 'user' entry 'mysql.session@localhost' ignored in --skip-name-resolve mode.
db         | 2020-02-20T09:50:47.957026Z 1 [Warning] 'user' entry 'mysql.sys@localhost' ignored in --skip-name-resolve mode.
db         | 2020-02-20T09:50:47.957747Z 1 [Warning] 'db' entry 'performance_schema mysql.session@localhost' ignored in --skip-name-resolve mode.
db         | 2020-02-20T09:50:47.958212Z 1 [Warning] 'db' entry 'sys mysql.sys@localhost' ignored in --skip-name-resolve mode.
db         | 2020-02-20T09:50:47.958797Z 1 [Warning] 'proxies_priv' entry '@ root@localhost' ignored in --skip-name-resolve mode.
db         | 2020-02-20T09:50:47.959520Z 1 [Warning] 'tables_priv' entry 'user mysql.session@localhost' ignored in --skip-name-resolve mode.
db         | 2020-02-20T09:50:47.960113Z 1 [Warning] 'tables_priv' entry 'sys_config mysql.sys@localhost' ignored in --skip-name-resolve mode.
forum_1    |
forum_1    | > express-oauth-vuex-starter@1.0.0 start /home/node/app
forum_1    | > nodemon index.js
forum_1    |
forum_1    | [nodemon] 2.0.2
forum_1    | [nodemon] to restart at any time, enter `rs`
forum_1    | [nodemon] watching dir(s): *.*
forum_1    | [nodemon] watching extensions: js,mjs,json
forum_1    | [nodemon] starting `node index.js`
db         | Database initialized
db         | Initializing certificates
db         | Generating a RSA private key
db         | ........................................................................................................................+++++
db         | ..........+++++
db         | unable to write 'random state'
db         | writing new private key to 'ca-key.pem'
db         | -----
db         | Generating a RSA private key
db         | .........................................................................................+++++
db         | .............+++++
db         | unable to write 'random state'
db         | writing new private key to 'server-key.pem'
db         | -----
db         | Generating a RSA private key
db         | .....................................................+++++
db         | .+++++
db         | unable to write 'random state'
db         | writing new private key to 'client-key.pem'
db         | -----
db         | Certificates initialized
db         | MySQL init process in progress...
db         | 2020-02-20T09:50:51.037907Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
db         | 2020-02-20T09:50:51.039423Z 0 [Note] mysqld (mysqld 5.7.24) starting as process 89 ...
db         | 2020-02-20T09:50:51.044545Z 0 [Note] InnoDB: PUNCH HOLE support available
db         | 2020-02-20T09:50:51.044653Z 0 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins
db         | 2020-02-20T09:50:51.044701Z 0 [Note] InnoDB: Uses event mutexes
db         | 2020-02-20T09:50:51.044745Z 0 [Note] InnoDB: GCC builtin __atomic_thread_fence() is used for memory barrier
db         | 2020-02-20T09:50:51.044786Z 0 [Note] InnoDB: Compressed tables use zlib 1.2.11
db         | 2020-02-20T09:50:51.044825Z 0 [Note] InnoDB: Using Linux native AIO
db         | 2020-02-20T09:50:51.045705Z 0 [Note] InnoDB: Number of pools: 1
db         | 2020-02-20T09:50:51.046113Z 0 [Note] InnoDB: Using CPU crc32 instructions
db         | 2020-02-20T09:50:51.048701Z 0 [Note] InnoDB: Initializing buffer pool, total size = 128M, instances = 1, chunk size = 128M
db         | 2020-02-20T09:50:51.060691Z 0 [Note] InnoDB: Completed initialization of buffer pool
db         | 2020-02-20T09:50:51.064263Z 0 [Note] InnoDB: If the mysqld execution user is authorized, page cleaner thread priority can be changed. See the man page of setpriority().
db         | 2020-02-20T09:50:51.076676Z 0 [Note] InnoDB: Highest supported file format is Barracuda.
db         | 2020-02-20T09:50:51.097380Z 0 [Note] InnoDB: Creating shared tablespace for temporary tables
db         | 2020-02-20T09:50:51.097533Z 0 [Note] InnoDB: Setting file './ibtmp1' size to 12 MB. Physically writing the file full; Please wait ...
db         | 2020-02-20T09:50:51.131620Z 0 [Note] InnoDB: File './ibtmp1' size is now 12 MB.
db         | 2020-02-20T09:50:51.134052Z 0 [Note] InnoDB: 96 redo rollback segment(s) found. 96 redo rollback segment(s) are active.
db         | 2020-02-20T09:50:51.134142Z 0 [Note] InnoDB: 32 non-redo rollback segment(s) are active.
db         | 2020-02-20T09:50:51.135177Z 0 [Note] InnoDB: Waiting for purge to start
db         | 2020-02-20T09:50:51.185530Z 0 [Note] InnoDB: 5.7.24 started; log sequence number 2591440
db         | 2020-02-20T09:50:51.186329Z 0 [Note] Plugin 'FEDERATED' is disabled.
db         | 2020-02-20T09:50:51.192075Z 0 [Note] Found ca.pem, server-cert.pem and server-key.pem in data directory. Trying to enable SSL support using them.
db         | 2020-02-20T09:50:51.192591Z 0 [Warning] CA certificate ca.pem is self signed.
db         | 2020-02-20T09:50:51.194602Z 0 [Note] InnoDB: Loading buffer pool(s) from /var/lib/mysql/ib_buffer_pool
db         | 2020-02-20T09:50:51.197793Z 0 [Note] InnoDB: Buffer pool(s) load completed at 200220  9:50:51
db         | 2020-02-20T09:50:51.198483Z 0 [Warning] Insecure configuration for --pid-file: Location '/var/run/mysqld' in the path is accessible to all OS users. Consider choosing a different directory.
db         | 2020-02-20T09:50:51.200316Z 0 [Warning] 'user' entry 'root@localhost' ignored in --skip-name-resolve mode.
db         | 2020-02-20T09:50:51.200460Z 0 [Warning] 'user' entry 'mysql.session@localhost' ignored in --skip-name-resolve mode.
db         | 2020-02-20T09:50:51.200532Z 0 [Warning] 'user' entry 'mysql.sys@localhost' ignored in --skip-name-resolve mode.
db         | 2020-02-20T09:50:51.200606Z 0 [Warning] 'db' entry 'performance_schema mysql.session@localhost' ignored in --skip-name-resolve mode.
db         | 2020-02-20T09:50:51.200656Z 0 [Warning] 'db' entry 'sys mysql.sys@localhost' ignored in --skip-name-resolve mode.
db         | 2020-02-20T09:50:51.200717Z 0 [Warning] 'proxies_priv' entry '@ root@localhost' ignored in --skip-name-resolve mode.
db         | 2020-02-20T09:50:51.202731Z 0 [Warning] 'tables_priv' entry 'user mysql.session@localhost' ignored in --skip-name-resolve mode.
db         | 2020-02-20T09:50:51.202816Z 0 [Warning] 'tables_priv' entry 'sys_config mysql.sys@localhost' ignored in --skip-name-resolve mode.
db         | 2020-02-20T09:50:51.219832Z 0 [Note] Event Scheduler: Loaded 0 events
db         | 2020-02-20T09:50:51.221248Z 0 [Note] mysqld: ready for connections.
db         | Version: '5.7.24'  socket: '/var/run/mysqld/mysqld.sock'  port: 0  MySQL Community Server (GPL)
forum_1    | Listening...
forum_1    | Error: connect ECONNREFUSED 192.168.16.2:3306
forum_1    |     at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1137:16)
forum_1    |     at Protocol._enqueue (/home/node/app/node_modules/mysql/lib/protocol/Protocol.js:144:48)
forum_1    |     at Protocol.handshake (/home/node/app/node_modules/mysql/lib/protocol/Protocol.js:51:23)
forum_1    |     at Connection.connect (/home/node/app/node_modules/mysql/lib/Connection.js:116:18)
forum_1    |     at /home/node/app/node_modules/knex/lib/dialects/mysql/index.js:69:18
forum_1    | From previous event:
forum_1    |     at Client_MySQL.acquireRawConnection (/home/node/app/node_modules/knex/lib/dialects/mysql/index.js:64:12)
forum_1    |     at create (/home/node/app/node_modules/knex/lib/client.js:291:39)
forum_1    |     at processTicksAndRejections (internal/process/task_queues.js:97:5) {
forum_1    |   errno: 'ECONNREFUSED',
forum_1    |   code: 'ECONNREFUSED',
forum_1    |   syscall: 'connect',
forum_1    |   address: '192.168.16.2',
forum_1    |   port: 3306,
forum_1    |   fatal: true
forum_1    | }
db         | Warning: Unable to load '/usr/share/zoneinfo/iso3166.tab' as time zone. Skipping it.
db         | Warning: Unable to load '/usr/share/zoneinfo/leap-seconds.list' as time zone. Skipping it.
db         | Warning: Unable to load '/usr/share/zoneinfo/zone.tab' as time zone. Skipping it.
db         | Warning: Unable to load '/usr/share/zoneinfo/zone1970.tab' as time zone. Skipping it.
db         | 2020-02-20T09:50:54.889060Z 4 [Warning] 'user' entry 'root@localhost' ignored in --skip-name-resolve mode.
db         | 2020-02-20T09:50:54.889116Z 4 [Warning] 'user' entry 'mysql.session@localhost' ignored in --skip-name-resolve mode.
db         | 2020-02-20T09:50:54.889137Z 4 [Warning] 'user' entry 'mysql.sys@localhost' ignored in --skip-name-resolve mode.
db         | 2020-02-20T09:50:54.889164Z 4 [Warning] 'db' entry 'performance_schema mysql.session@localhost' ignored in --skip-name-resolve mode.
db         | 2020-02-20T09:50:54.889172Z 4 [Warning] 'db' entry 'sys mysql.sys@localhost' ignored in --skip-name-resolve mode.
db         | 2020-02-20T09:50:54.889188Z 4 [Warning] 'proxies_priv' entry '@ root@localhost' ignored in --skip-name-resolve mode.
db         | 2020-02-20T09:50:54.890011Z 4 [Warning] 'tables_priv' entry 'user mysql.session@localhost' ignored in --skip-name-resolve mode.
db         | 2020-02-20T09:50:54.890057Z 4 [Warning] 'tables_priv' entry 'sys_config mysql.sys@localhost' ignored in --skip-name-resolve mode.
db         |
db         | /usr/local/bin/docker-entrypoint.sh: running /docker-entrypoint-initdb.d/init.sql
db         | mysql: [Warning] Using a password on the command line interface can be insecure.
db         |
db         |
db         | 2020-02-20T09:50:54.915362Z 0 [Note] Giving 0 client threads a chance to die gracefully
db         | 2020-02-20T09:50:54.915705Z 0 [Note] Shutting down slave threads
db         | 2020-02-20T09:50:54.916456Z 0 [Note] Forcefully disconnecting 0 remaining clients
db         | 2020-02-20T09:50:54.917013Z 0 [Note] Event Scheduler: Purging the queue. 0 events
db         | 2020-02-20T09:50:54.917696Z 0 [Note] Binlog end
db         | 2020-02-20T09:50:54.918665Z 0 [Note] Shutting down plugin 'ngram'
db         | 2020-02-20T09:50:54.919138Z 0 [Note] Shutting down plugin 'partition'
db         | 2020-02-20T09:50:54.919357Z 0 [Note] Shutting down plugin 'BLACKHOLE'
db         | 2020-02-20T09:50:54.920107Z 0 [Note] Shutting down plugin 'ARCHIVE'
db         | 2020-02-20T09:50:54.920322Z 0 [Note] Shutting down plugin 'PERFORMANCE_SCHEMA'
db         | 2020-02-20T09:50:54.921325Z 0 [Note] Shutting down plugin 'MRG_MYISAM'
db         | 2020-02-20T09:50:54.921840Z 0 [Note] Shutting down plugin 'MyISAM'
db         | 2020-02-20T09:50:54.922751Z 0 [Note] Shutting down plugin 'INNODB_SYS_VIRTUAL'
db         | 2020-02-20T09:50:54.923300Z 0 [Note] Shutting down plugin 'INNODB_SYS_DATAFILES'
db         | 2020-02-20T09:50:54.923360Z 0 [Note] Shutting down plugin 'INNODB_SYS_TABLESPACES'
db         | 2020-02-20T09:50:54.923589Z 0 [Note] Shutting down plugin 'INNODB_SYS_FOREIGN_COLS'
db         | 2020-02-20T09:50:54.923959Z 0 [Note] Shutting down plugin 'INNODB_SYS_FOREIGN'
db         | 2020-02-20T09:50:54.924112Z 0 [Note] Shutting down plugin 'INNODB_SYS_FIELDS'
db         | 2020-02-20T09:50:54.924269Z 0 [Note] Shutting down plugin 'INNODB_SYS_COLUMNS'
db         | 2020-02-20T09:50:54.924754Z 0 [Note] Shutting down plugin 'INNODB_SYS_INDEXES'
db         | 2020-02-20T09:50:54.925454Z 0 [Note] Shutting down plugin 'INNODB_SYS_TABLESTATS'
db         | 2020-02-20T09:50:54.925535Z 0 [Note] Shutting down plugin 'INNODB_SYS_TABLES'
db         | 2020-02-20T09:50:54.925688Z 0 [Note] Shutting down plugin 'INNODB_FT_INDEX_TABLE'
db         | 2020-02-20T09:50:54.925728Z 0 [Note] Shutting down plugin 'INNODB_FT_INDEX_CACHE'
db         | 2020-02-20T09:50:54.926261Z 0 [Note] Shutting down plugin 'INNODB_FT_CONFIG'
db         | 2020-02-20T09:50:54.926443Z 0 [Note] Shutting down plugin 'INNODB_FT_BEING_DELETED'
db         | 2020-02-20T09:50:54.926836Z 0 [Note] Shutting down plugin 'INNODB_FT_DELETED'
db         | 2020-02-20T09:50:54.927513Z 0 [Note] Shutting down plugin 'INNODB_FT_DEFAULT_STOPWORD'
db         | 2020-02-20T09:50:54.927560Z 0 [Note] Shutting down plugin 'INNODB_METRICS'
db         | 2020-02-20T09:50:54.927718Z 0 [Note] Shutting down plugin 'INNODB_TEMP_TABLE_INFO'
db         | 2020-02-20T09:50:54.927806Z 0 [Note] Shutting down plugin 'INNODB_BUFFER_POOL_STATS'
db         | 2020-02-20T09:50:54.927847Z 0 [Note] Shutting down plugin 'INNODB_BUFFER_PAGE_LRU'
db         | 2020-02-20T09:50:54.928201Z 0 [Note] Shutting down plugin 'INNODB_BUFFER_PAGE'
db         | 2020-02-20T09:50:54.928360Z 0 [Note] Shutting down plugin 'INNODB_CMP_PER_INDEX_RESET'
db         | 2020-02-20T09:50:54.928817Z 0 [Note] Shutting down plugin 'INNODB_CMP_PER_INDEX'
db         | 2020-02-20T09:50:54.929031Z 0 [Note] Shutting down plugin 'INNODB_CMPMEM_RESET'
db         | 2020-02-20T09:50:54.929717Z 0 [Note] Shutting down plugin 'INNODB_CMPMEM'
db         | 2020-02-20T09:50:54.929740Z 0 [Note] Shutting down plugin 'INNODB_CMP_RESET'
db         | 2020-02-20T09:50:54.929898Z 0 [Note] Shutting down plugin 'INNODB_CMP'
db         | 2020-02-20T09:50:54.929912Z 0 [Note] Shutting down plugin 'INNODB_LOCK_WAITS'
db         | 2020-02-20T09:50:54.930509Z 0 [Note] Shutting down plugin 'INNODB_LOCKS'
db         | 2020-02-20T09:50:54.930535Z 0 [Note] Shutting down plugin 'INNODB_TRX'
db         | 2020-02-20T09:50:54.930549Z 0 [Note] Shutting down plugin 'InnoDB'
db         | 2020-02-20T09:50:54.931131Z 0 [Note] InnoDB: FTS optimize thread exiting.
db         | 2020-02-20T09:50:54.931746Z 0 [Note] InnoDB: Starting shutdown...
db         | 2020-02-20T09:50:55.032188Z 0 [Note] InnoDB: Dumping buffer pool(s) to /var/lib/mysql/ib_buffer_pool
db         | 2020-02-20T09:50:55.032448Z 0 [Note] InnoDB: Buffer pool(s) dump completed at 200220  9:50:55

If the volume already exists, I get no errors, knex connects and the migrations are run.

In the error log you can see that the Node container starts up directly after mysqld: ready for connections. However, you can see that after the Node error, the db container then runs init.sql. Presumably this means that knex is trying to connect to a specific database before it exists, which I guess could be the cause of the refused connection.

So I guess I'm looking for a way to defer the instantiation of the node container until after the MySQL container has run init.sql. I'm already using the depends_on docker compose property - are there any other docker options available to me?


问:
Using the Parse Template transformer with an array in the data
I'm a newbie to Mulesoft, and I'm looking to transform a Json object into an XML object via the Parse Template transformer. Straight forward enough, however, what is the appropriate approach when the Json object has an array with an undetermined number of elements?

For example, if I have a JSON object that looks like

{ "name" : "Methusela",
   "hobbies: [
     "name": "guitar",
     "name": "cooking",
     "name": "someting",
  ...
  ]}

where the number of hobbies is unknown at runtime

and my xml template looks like:

```<code><Person>
<Name>#[payload.name]</Name>
<Hobbies>
    <!- What should this bit look like -->
</Hobbies>
</code>```

So - my question is how should I approach the conversion of the open ended JSON array to XML?

Note that we are currently exploring the community edition and therefore don't have access to the data mapping functionality available through the enterprise edition.

Thanks

答:
In parse template you can use simple javascript loop:</p>

```<code>for(i=0;i<#[payload.Hobbies].length;i++){
document.getElementById('Id').innerHtml += #[payload.Hobbies][i]
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm a newbie to Mulesoft, and I'm looking to transform a Json object into an XML object via the Parse Template transformer. Straight forward enough, however, what is the appropriate approach when the Json object has an array with an undetermined number of elements?

For example, if I have a JSON object that looks like

{ "name" : "Methusela",
   "hobbies: [
     "name": "guitar",
     "name": "cooking",
     "name": "someting",
  ...
  ]}

where the number of hobbies is unknown at runtime

and my xml template looks like:

<Person>
<Name>#[payload.name]</Name>
<Hobbies>
    <!- What should this bit look like -->
</Hobbies>

So - my question is how should I approach the conversion of the open ended JSON array to XML?

Note that we are currently exploring the community edition and therefore don't have access to the data mapping functionality available through the enterprise edition.

Thanks

Body:
In parse template you can use simple javascript loop:

for(i=0;i<#[payload.Hobbies].length;i++){
document.getElementById('Id').innerHtml += #[payload.Hobbies][i]
}


问:
Cannot deserialize the json file with list of events?
I have below C# class structure,

```<code>public class Event
{
    public string Id { get; set; }
    public Body Body { get; set; }
    public BodyProperty[] BodyProperties { get; set; }
    public string EventType { get; set; }
    public string CreatedTime { get; set; }
}

public class BodyProperty
{
    public string Key { get; set; }
    public string Value { get; set; }
}

public class Body
{
    public Body(string value, string type = "TextualBody", string format = "application/json")
    {
        Type = type;
        Value = value;
        Format = format;
    }

    public string Type { get; set; }
    public string Value { get; set; }
    public string Format { get; set; }
}
</code>```

and trying to read below JSON file,

```<code>{
    "Events": [
        {
            "Id": "d22fc23c-968f-4406-bebb-fca231694986",
            "Body": {
                "Type": "TextualBody",
                "Value": "test",
                "Format": "application/json"
            },
            "BodyProperties": null,
            "EventType": "Entity",
            "CreatedTime": "2020-02-20T13:57:14.1234165+05:30"
        },
        {
            "Id": "fgdgdg-968f-4406-bebb-646464",
            "Body": {
                "Type": "TextualBody",
                "Value": "test",
                "Format": "application/json"
            },
            "BodyProperties": null,
            "EventType": "Entity",
            "CreatedTime": "2020-02-21T13:57:14.1234165+05:30"
        }
    ]
}
</code>```

But this give below error while trying to read like this, I can't change JSON format, what can I change while reading?

```<code>using (StreamReader file = File.OpenText(@"C:\TEMP\json1.json"))
        using (JsonTextReader jsonreader = new JsonTextReader(file))
        {
            var serializer = new JsonSerializer();
            return serializer.Deserialize<List<Event>>(jsonreader);
        }
</code>```

Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[uploadJSON.Event]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
  To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object.

答:
You are missing RootObject

```<code>public class RootObject
{
    public List<Event> Events { get; set; }
}
</code>```

Body:
I have below C# class structure,

public class Event
{
    public string Id { get; set; }
    public Body Body { get; set; }
    public BodyProperty[] BodyProperties { get; set; }
    public string EventType { get; set; }
    public string CreatedTime { get; set; }
}

public class BodyProperty
{
    public string Key { get; set; }
    public string Value { get; set; }
}

public class Body
{
    public Body(string value, string type = "TextualBody", string format = "application/json")
    {
        Type = type;
        Value = value;
        Format = format;
    }

    public string Type { get; set; }
    public string Value { get; set; }
    public string Format { get; set; }
}

and trying to read below JSON file,

{
    "Events": [
        {
            "Id": "d22fc23c-968f-4406-bebb-fca231694986",
            "Body": {
                "Type": "TextualBody",
                "Value": "test",
                "Format": "application/json"
            },
            "BodyProperties": null,
            "EventType": "Entity",
            "CreatedTime": "2020-02-20T13:57:14.1234165+05:30"
        },
        {
            "Id": "fgdgdg-968f-4406-bebb-646464",
            "Body": {
                "Type": "TextualBody",
                "Value": "test",
                "Format": "application/json"
            },
            "BodyProperties": null,
            "EventType": "Entity",
            "CreatedTime": "2020-02-21T13:57:14.1234165+05:30"
        }
    ]
}

But this give below error while trying to read like this, I can't change JSON format, what can I change while reading?

using (StreamReader file = File.OpenText(@"C:\TEMP\json1.json"))
        using (JsonTextReader jsonreader = new JsonTextReader(file))
        {
            var serializer = new JsonSerializer();
            return serializer.Deserialize<List<Event>>(jsonreader);
        }

Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[uploadJSON.Event]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
  To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object.

Body:
You are missing RootObject

public class RootObject
{
    public List<Event> Events { get; set; }
}


问:
403 Error while creating storage account in Azure
I was trying to access the CLI in azure. I wanted to execute the script in Power shell CLI. But I'm not able to create a storage account for PowerShell in azure.

答:
You get the error that you are not authorized to perform action 'Microsoft.Resources/subscriptions/resourcegroups/read' over scope of <s>storage account</s> because you don't have the relevant permissions on the <s>Storage Account.</s>

You either need to have <s>"Contributor"</s>  permissions to create & manage storage account or related resources. More details of the azure RBAC roles in the link

edit:

as  4c74356b41  mentioned in the comment, you need read role and scope should be resource group.


问:
SAXParseException creating an Enum in XSD
I'm having trouble constructing my first XSD file. I'm trying to generate Java POJO's bases on my XSD with jaxb2-maven-plugin.

To start, I've followed the example that I've seen this tutorial

This is my xsd file:

```<code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xs:schema version="1.0"
           xmlns:xs="http://www.w3.org/2001/XMLSchema">

   <xs:element name = "Tshirt">
        <xs:complexType>
            <xs:sequence>
                <xs:element name = "Color" type = "clothesColorType" />
                <xs:element name = "Size" type = "clothesSizeType" />
            </xs:sequence>
        </xs:complexType>
    </xs:element>

    <xs:simpleType name="clothesSizeType">
        <xs:restriction base="xs:string">
            <xs:enumeration value="S" />
            <xs:enumeration value="M" />
            <xs:enumeration value="L" />
            <xs:enumeration value="XL" />
        </xs:restriction>
    </xs:simpleType>

    <xs:simpleType name="clothesColorType">
        <xs:restriction base="xs:string">
            <xs:enumeration value="Black" />
            <xs:enumeration value="White" />
            <xs:enumeration value="Green" />
            <xs:enumeration value="Blue" />
        </xs:restriction>
    </xs:simpleType>
</xs:schema>
</code>```

When my plugin try to parse the file, I get the error

```<code>org.xml.sax.SAXParseException; systemId: file:/ruta/src/main/resources/wsdl-definition/Assurance.xsd; lineNumber: 47; columnNumber: 72; src-resolve: No se puede resolver el nombre 'clothesColorType' para un componente 'type definition'.
</code>```

I have been googling for hours but I have not found the response. Any Ideas?

Thank you in advance.

答:
The schema is valid (Saxon accepts it, so it must be...)

The problem is therefore either with your schema processor, or with the way you are invoking it.

I note that your schema does not have 47 lines, therefore I suspect the file you are actually using differs from the one shown.

Body:
I'm having trouble constructing my first XSD file. I'm trying to generate Java POJO's bases on my XSD with jaxb2-maven-plugin.

To start, I've followed the example that I've seen this tutorial

This is my xsd file:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xs:schema version="1.0"
           xmlns:xs="http://www.w3.org/2001/XMLSchema">

   <xs:element name = "Tshirt">
        <xs:complexType>
            <xs:sequence>
                <xs:element name = "Color" type = "clothesColorType" />
                <xs:element name = "Size" type = "clothesSizeType" />
            </xs:sequence>
        </xs:complexType>
    </xs:element>

    <xs:simpleType name="clothesSizeType">
        <xs:restriction base="xs:string">
            <xs:enumeration value="S" />
            <xs:enumeration value="M" />
            <xs:enumeration value="L" />
            <xs:enumeration value="XL" />
        </xs:restriction>
    </xs:simpleType>

    <xs:simpleType name="clothesColorType">
        <xs:restriction base="xs:string">
            <xs:enumeration value="Black" />
            <xs:enumeration value="White" />
            <xs:enumeration value="Green" />
            <xs:enumeration value="Blue" />
        </xs:restriction>
    </xs:simpleType>
</xs:schema>

When my plugin try to parse the file, I get the error

org.xml.sax.SAXParseException; systemId: file:/ruta/src/main/resources/wsdl-definition/Assurance.xsd; lineNumber: 47; columnNumber: 72; src-resolve: No se puede resolver el nombre 'clothesColorType' para un componente 'type definition'.

I have been googling for hours but I have not found the response. Any Ideas?

Thank you in advance.


问:
etcd replication in a kubernetes architecture
I'm new to kubernetes and etcd , i'm trying to figure out how etcd is distributed in kubernetes.
the answer to these question will help me very much

Question 1:
if we have a kubernetes architecture with 1 master and 2 nodes ,
are we going to have :
    - 1 etcd store that is located on the master
    - or an etcd distributed between the master and the nodes ( all will have a replication of the store )

if we have a kubernetes architecture with 2 masters and 3 nodes ,
are we going to have :
    - 2 etcd stores replicated on both the 2 masters
    - or an etcd distributed between the master and the nodes ( all will have a replication of the store )

Question 2:
i found this recommandation "Always use an odd number of cluster members as quorum is needed to agree on updates to the cluster state"
source : https://rancher.com/blog/2019/2019-01-29-what-is-etcd/
is it about the number of nodes in kubernetes cluster or is it about the number of members in the etcd cluster
can you give me an example

Question 3:
what does is mean: external clustered etcd , etcd runs as static pods on the master nodes

答:
You are not supposed to have etcd on worker node. etcd should be either stacked within master nodes or should be external. Refer official docs.

Number of the etcd members should be odd to achieve quorum. In the blog that's what is being meant.

You can have etcd deployed on the master nodes as containers using static pods mechanism of kubernetes. Kubernetes will manage etcd as pods.

Alternatively you can run etcd as systemd unit on external hosts outside of your kubernetes cluster.


问:
Password policy requirement regex
I need a regex to meet this password policy requirement
Minimum eight (8) characters
At least one number (0-9)
Any three of the following:
Lowercase
Uppercase
Number
Special character (   ! " # $ % & ' ( )
* + , - . / : ; < = > ? @ [ \ ] ^ _ ` { | } ~ )

for now i am using this regex Minimum eight (8) characters

```<code>/^(?=.*\d)[ !#$%&()*+,.\/:;<=>?@[\]^`{|}~\w-]{8,}$/
</code>```

This regex is not working as expected it is taking input of
testtest1 as a right match.It should take this test@test1,Testtest12 as a right input

答:
The pattern will match testtest1 as you are only asserting a required digit and following character class [ !#$%&()*+,.\/:;<=>?@[\]^{|}~\w-]{8,}` will repeat matching at least 8 times any of the listed.

If you want to assert either an uppercase char A-Z or a special character as well, you could use another positive lookahead with an alternation

```<code>^(?=.*\d)(?=.*(?:[A-Z]|[!#$%&()*+,.\/:;<=>?@[\]^`{|}~-]))[!#$%&()*+,.\/:;<=>?@[\]^`{|}~\w-]{8,}$
</code>```

Regex demo

Note that I omitted matching the spaces, you could a space to the character class if you want to match it (Not sure if you would allow spaces in the password)

Title: Password policy requirement regex

Body:
I need a regex to meet this password policy requirement
Minimum eight (8) characters
At least one number (0-9)
Any three of the following:
Lowercase
Uppercase
Number
Special character (   ! " # $ % & ' ( )
* + , - . / : ; < = > ? @ [ \ ] ^ _ ` { | } ~ )

for now i am using this regex Minimum eight (8) characters

/^(?=.*\d)[ !#$%&()*+,.\/:;<=>?@[\]^`{|}~\w-]{8,}$/

This regex is not working as expected it is taking input of
testtest1 as a right match.It should take this test@test1,Testtest12 as a right input

Body:
The pattern will match testtest1 as you are only asserting a required digit and following character class [ !#$%&()*+,.\/:;<=>?@[\]^{|}~\w-]{8,}` will repeat matching at least 8 times any of the listed.

If you want to assert either an uppercase char A-Z or a special character as well, you could use another positive lookahead with an alternation

^(?=.*\d)(?=.*(?:[A-Z]|[!#$%&()*+,.\/:;<=>?@[\]^`{|}~-]))[!#$%&()*+,.\/:;<=>?@[\]^`{|}~\w-]{8,}$

Regex demo

Note that I omitted matching the spaces, you could a space to the character class if you want to match it (Not sure if you would allow spaces in the password)


问:
BrightIdeasSoftware.FastObjectListView.CellEditFinished e.Cancel not working
I have a listview where a user can double click a cell to edit. I am validating the users input and if its incorrect I don't want the change to be implemented.

Issue is the e.Cancel is not cancelling the event? Is there anything in the properites that needs setting aswell?

```<code>private void HoursListView_CellEditFinished(object sender, CellEditEventArgs e)
    {
        string originalValue = e.Value.ToString();
        string newValue = e.NewValue.ToString();

        string[] timeSplit = e.NewValue.ToString().Split(':');

        if (!Regex.IsMatch(newValue, @"^\d{2}:\d{2}:\d{2}"))
        {
            e.Cancel = true;
            MessageBox.Show("Incorrect hours format!", "Edit Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        else if (Convert.ToDouble(timeSplit[0]) > 24)
        {
            e.Cancel = true;
            MessageBox.Show("Hours cannot be over 24!", "Edit Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        else if (Convert.ToDouble(timeSplit[1]) > 59)
        {
            e.Cancel = true;
            MessageBox.Show("Minutes value cannot be over 59!", "Edit Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        else if (Convert.ToDouble(timeSplit[2]) > 59)
        {
            e.Cancel = true;
            MessageBox.Show("Seconds value cannot be over 59!", "Edit Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        else
        {
            UpdateTotalHoursForTheWeek();
        }
    }
</code>```

答: Sorted it... Turns out you need to use the event CellEditFinishing not CellEditFinished!</p>

Body:
I have a listview where a user can double click a cell to edit. I am validating the users input and if its incorrect I don't want the change to be implemented.

Issue is the e.Cancel is not cancelling the event? Is there anything in the properites that needs setting aswell?

private void HoursListView_CellEditFinished(object sender, CellEditEventArgs e)
    {
        string originalValue = e.Value.ToString();
        string newValue = e.NewValue.ToString();

        string[] timeSplit = e.NewValue.ToString().Split(':');

        if (!Regex.IsMatch(newValue, @"^\d{2}:\d{2}:\d{2}"))
        {
            e.Cancel = true;
            MessageBox.Show("Incorrect hours format!", "Edit Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        else if (Convert.ToDouble(timeSplit[0]) > 24)
        {
            e.Cancel = true;
            MessageBox.Show("Hours cannot be over 24!", "Edit Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        else if (Convert.ToDouble(timeSplit[1]) > 59)
        {
            e.Cancel = true;
            MessageBox.Show("Minutes value cannot be over 59!", "Edit Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        else if (Convert.ToDouble(timeSplit[2]) > 59)
        {
            e.Cancel = true;
            MessageBox.Show("Seconds value cannot be over 59!", "Edit Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        else
        {
            UpdateTotalHoursForTheWeek();
        }
    }


问:
How to access data.frame columns by $ followed by a function?
Say I have a df.

```<code>df<-data.frame(matrix(,ncol=3,nrow=2));
colnames(df)<-(c("day1","day2","day3"))
</code>```

Of course now I can access the first column by df$day1.
However, instead of directly put day1 in there, I sometimes like to access within a loop, e.g.,

in  a loop where I have val=3

Can I access df$day3 by something like df$paste("day",val,sep="")?

Of course the one I wrote won't work.

答:
Here's a little round trip through the accessing possibilities that R affords.
Let's say we have this data:

```<code>set.seed(111)
df<-data.frame(
   day1 = paste0(sample(LETTERS[1:5], 2), rep(letters[1:2], 5)),
   day2 = runif(10),
   day3 = c(sample(9), NA),
   day4 = round(rnorm(10), 2)
)
df
   day1       day2 day3  day4
1    Ca 0.51492383    4  0.39
2    Db 0.37766322    7  0.80
3    Ca 0.41833733    6 -1.57
4    Db 0.01065785    2 -0.09
5    Ca 0.53229524    1 -0.36
6    Db 0.43216062    9 -1.19
7    Ca 0.09368152    3  0.36
8    Db 0.55577991    8  0.36
9    Ca 0.59022849    5  0.35
10   Db 0.06714114   NA  0.19
</code>```

Here's a (a few) ways you can access data in the dataframe:

```<code># Access specific fields by indices:
df[5, 2]
[1] 0.5322952

# Access specific row:
df[2,]
  day1      day2 day3 day4
2   Db 0.3776632    7  0.8

# Access specific column:
df[,3]
 [1]  4  7  6  2  1  9  3  8  5 NA

# Access more than one specific row/column:
df[c(1, 3) ,]
  day1      day2 day3  day4
1   Ca 0.5149238    4  0.39
3   Ca 0.4183373    6 -1.57

df[ ,c(1, 3:4)]
   day1 day3  day4
1    Ca    4  0.39
2    Db    7  0.80
3    Ca    6 -1.57
4    Db    2 -0.09
5    Ca    1 -0.36
6    Db    9 -1.19
7    Ca    3  0.36
8    Db    8  0.36
9    Ca    5  0.35
10   Db   NA  0.19

# Access by subsetting on rows with specific values:
df[df$day1=="Ca" ,]
  day1       day2 day3  day4
1   Ca 0.51492383    4  0.39
3   Ca 0.41833733    6 -1.57
5   Ca 0.53229524    1 -0.36
7   Ca 0.09368152    3  0.36
9   Ca 0.59022849    5  0.35

# Access with regular expression:
df[grep("a", df$day1),]
  day1       day2 day3  day4
1   Ca 0.51492383    4  0.39
3   Ca 0.41833733    6 -1.57
5   Ca 0.53229524    1 -0.36
7   Ca 0.09368152    3  0.36
9   Ca 0.59022849    5  0.35

# Access via NA:
df[is.na(df$day3), ]
   day1       day2 day3 day4
10   Db 0.06714114   NA 0.19

# Access with mixture of index and column name:
df[3, "day2"]
[1] 0.4183373

# Access with mixture of index and several column names at once
df[2, paste0("day", 1:3)]
  day1      day2 day3
2   Db 0.3776632    7
</code>```

And I'm pretty sure there's more ways!

Body:
Say I have a df.

df<-data.frame(matrix(,ncol=3,nrow=2));
colnames(df)<-(c("day1","day2","day3"))

Of course now I can access the first column by df$day1.
However, instead of directly put day1 in there, I sometimes like to access within a loop, e.g.,

in  a loop where I have val=3

Can I access df$day3 by something like df$paste("day",val,sep="")?

Of course the one I wrote won't work.

Body:
Here's a little round trip through the accessing possibilities that R affords.
Let's say we have this data:

set.seed(111)
df<-data.frame(
   day1 = paste0(sample(LETTERS[1:5], 2), rep(letters[1:2], 5)),
   day2 = runif(10),
   day3 = c(sample(9), NA),
   day4 = round(rnorm(10), 2)
)
df
   day1       day2 day3  day4
1    Ca 0.51492383    4  0.39
2    Db 0.37766322    7  0.80
3    Ca 0.41833733    6 -1.57
4    Db 0.01065785    2 -0.09
5    Ca 0.53229524    1 -0.36
6    Db 0.43216062    9 -1.19
7    Ca 0.09368152    3  0.36
8    Db 0.55577991    8  0.36
9    Ca 0.59022849    5  0.35
10   Db 0.06714114   NA  0.19

Here's a (a few) ways you can access data in the dataframe:

# Access specific fields by indices:
df[5, 2]
[1] 0.5322952

# Access specific row:
df[2,]
  day1      day2 day3 day4
2   Db 0.3776632    7  0.8

# Access specific column:
df[,3]
 [1]  4  7  6  2  1  9  3  8  5 NA

# Access more than one specific row/column:
df[c(1, 3) ,]
  day1      day2 day3  day4
1   Ca 0.5149238    4  0.39
3   Ca 0.4183373    6 -1.57

df[ ,c(1, 3:4)]
   day1 day3  day4
1    Ca    4  0.39
2    Db    7  0.80
3    Ca    6 -1.57
4    Db    2 -0.09
5    Ca    1 -0.36
6    Db    9 -1.19
7    Ca    3  0.36
8    Db    8  0.36
9    Ca    5  0.35
10   Db   NA  0.19

# Access by subsetting on rows with specific values:
df[df$day1=="Ca" ,]
  day1       day2 day3  day4
1   Ca 0.51492383    4  0.39
3   Ca 0.41833733    6 -1.57
5   Ca 0.53229524    1 -0.36
7   Ca 0.09368152    3  0.36
9   Ca 0.59022849    5  0.35

# Access with regular expression:
df[grep("a", df$day1),]
  day1       day2 day3  day4
1   Ca 0.51492383    4  0.39
3   Ca 0.41833733    6 -1.57
5   Ca 0.53229524    1 -0.36
7   Ca 0.09368152    3  0.36
9   Ca 0.59022849    5  0.35

# Access via NA:
df[is.na(df$day3), ]
   day1       day2 day3 day4
10   Db 0.06714114   NA 0.19

# Access with mixture of index and column name:
df[3, "day2"]
[1] 0.4183373

# Access with mixture of index and several column names at once
df[2, paste0("day", 1:3)]
  day1      day2 day3
2   Db 0.3776632    7

And I'm pretty sure there's more ways!


问:
MSBuild error - Program does not contain a static 'Main' method suitable for an entry point
I have a visual studio solution containing some class library projects and a windows service project.

I am trying to build it using the following msbuild command:

```<code>MSBuild SolutionName.sln /t:rebuild /p:Configuration=Release;OutputType=Winexe /clp:ErrorsOnly
</code>```

However, I am getting the following error:

CSC : error CS5001: Program does not contain a static 'Main' method
  suitable for an entry point [C:..\BusinessObjects.csproj]

Somehow it tries to find an entry point inside a class library project instead of using the windows service project.

I believe if I try to build WindowsService.csproj instead of .sln file then it may fix the issue. However, WindowsService.CsProj does not contain all other dll references so I have to build .sln file.

Is there any other way I can fix this error?

答:
I believe if I try to build WindowsService.csproj instead of .sln file
  then it may fix the issue. However, WindowsService.CsProj does not
  contain all other dll references so I have to build .sln file.

Is there any other way I can fix this error?

Since your just build the whole solution with msbuild command line , it means that the parameters from your command line apply to all projects in the solution.

As your description, you have some class library projects in your solution which does not contains a static Main method, So it cannot be specified as a Windows application.

Projects in VS have three output types: Console Application and Windows Application contains a static Main function while Class Library Application does not contain it.

Conclusion

If you build a whole solution with the command line, you should make sure that all the parameters from the command line apply to all projects.

When you build a single project Windows Service project, just make sure the current project has a static main function and it actually has.

Solution

1) Since your solution contains only one winexe project and other class library projects, please delete OutputType=Winexe in the command line.

```<code>MSBuild SolutionName.sln /t:rebuild /p:Configuration=Release /clp:ErrorsOnly
</code>```

Hope it could help you.

Body:
I have a visual studio solution containing some class library projects and a windows service project.

I am trying to build it using the following msbuild command:

MSBuild SolutionName.sln /t:rebuild /p:Configuration=Release;OutputType=Winexe /clp:ErrorsOnly

However, I am getting the following error:

CSC : error CS5001: Program does not contain a static 'Main' method
  suitable for an entry point [C:..\BusinessObjects.csproj]

Somehow it tries to find an entry point inside a class library project instead of using the windows service project.

I believe if I try to build WindowsService.csproj instead of .sln file then it may fix the issue. However, WindowsService.CsProj does not contain all other dll references so I have to build .sln file.

Is there any other way I can fix this error?

Body:
I believe if I try to build WindowsService.csproj instead of .sln file
  then it may fix the issue. However, WindowsService.CsProj does not
  contain all other dll references so I have to build .sln file.

Is there any other way I can fix this error?

Since your just build the whole solution with msbuild command line , it means that the parameters from your command line apply to all projects in the solution.

As your description, you have some class library projects in your solution which does not contains a static Main method, So it cannot be specified as a Windows application.

Projects in VS have three output types: Console Application and Windows Application contains a static Main function while Class Library Application does not contain it.

Conclusion

If you build a whole solution with the command line, you should make sure that all the parameters from the command line apply to all projects.

When you build a single project Windows Service project, just make sure the current project has a static main function and it actually has.

Solution

1) Since your solution contains only one winexe project and other class library projects, please delete OutputType=Winexe in the command line.

MSBuild SolutionName.sln /t:rebuild /p:Configuration=Release /clp:ErrorsOnly

Hope it could help you.


问:
Remove or Filter values out of an Array using for loop or a function
I have an Array and i would like to  Filter or delete the following urls from my Array every time they appear:

```<code>"https://basueUrl.com/Claim"
"https://basueUrl.com/ExplanationOfBenefit"
</code>```

My Array

```<code>Array= [
        "https://basueUrl.com/Patient"
        "https://basueUrl.com/Organization"
        "https://basueUrl.com/Claim"
        "https://basueUrl.com/Practitioner"
        "https://basueUrl.com/Encounter"
        "https://basueUrl.com/Condition"
        "https://basueUrl.com/Claim"
        "https://basueUrl.com/ExplanationOfBenefit"
        "https://basueUrl.com/Claim"
        "https://basueUrl.com/ExplanationOfBenefit"
        "https://basueUrl.com/ExplanationOfBenefit"
        ]
</code>```

First Solution I have tried for loop but did not work?

```<code>   for( var i = 0; i < Array.length; i++){
   if ( Array[i] === "https://basueUrl.com/ExplanationOfBenefit" & "https://basueUrl.com/Claim") {
    Array.splice(i, 1);
    i--;
   }
}
console.log(Array);

</code>```

Second Solution I tried making a remove method did not work either.

```<code>function arrayRemove(Array, value) {

   return Array.filter(function(ele){
       return ele != value;
   });
}
var result = arrayRemove(Array,"https://basueUrl.com/ExplanationOfBenefit" & "https://basueUrl.com/Claim");

</code>```

Any suggestion please?

答:
var Array= [
        "https://basueUrl.com/Patient",
        "https://basueUrl.com/Organization",
        "https://basueUrl.com/Claim",
        "https://basueUrl.com/Practitioner",
        "https://basueUrl.com/Encounter",
        "https://basueUrl.com/Condition",
        "https://basueUrl.com/Claim",
        "https://basueUrl.com/ExplanationOfBenefit",
        "https://basueUrl.com/Claim",
        "https://basueUrl.com/ExplanationOfBenefit",
        "https://basueUrl.com/ExplanationOfBenefit"
        ];

var filteredArray = Array.filter(item => item !== "https://basueUrl.com/Claim" && item !== "https://basueUrl.com/ExplanationOfBenefit")

console.log(filteredArray)```

Body:
I have an Array and i would like to  Filter or delete the following urls from my Array every time they appear:

"https://basueUrl.com/Claim"
"https://basueUrl.com/ExplanationOfBenefit"

My Array

Array= [
        "https://basueUrl.com/Patient"
        "https://basueUrl.com/Organization"
        "https://basueUrl.com/Claim"
        "https://basueUrl.com/Practitioner"
        "https://basueUrl.com/Encounter"
        "https://basueUrl.com/Condition"
        "https://basueUrl.com/Claim"
        "https://basueUrl.com/ExplanationOfBenefit"
        "https://basueUrl.com/Claim"
        "https://basueUrl.com/ExplanationOfBenefit"
        "https://basueUrl.com/ExplanationOfBenefit"
        ]

First Solution I have tried for loop but did not work?

   for( var i = 0; i < Array.length; i++){
   if ( Array[i] === "https://basueUrl.com/ExplanationOfBenefit" & "https://basueUrl.com/Claim") {
    Array.splice(i, 1);
    i--;
   }
}
console.log(Array);

Second Solution I tried making a remove method did not work either.

function arrayRemove(Array, value) {

   return Array.filter(function(ele){
       return ele != value;
   });
}
var result = arrayRemove(Array,"https://basueUrl.com/ExplanationOfBenefit" & "https://basueUrl.com/Claim");

Any suggestion please?


问:
IIS Express Worker Process doesn't release assembly
I have a MVC 5 Project called MyApp which compiles into MyApp.dll
I'm using Visual Studio 2015 and compiling targeting .net Framework 4.5.1

After developing a while I can't compile anymore because the IIS Express Worker Process doesn't release the file \obj\Debug\MyApp.dll

Strange thing that if I do a full recompile afterwards somehow the assembly gets freed and i can then start debugging again, at least most of the time.

(And in some cases a recompile doesn't help anymore and i have to start killing the process)

Any Idea why the IIS Express Worker Process does block my assembly?

The Error Showing in VS 2015:

答:
I'm using VS 2019. I faced this problem in my asp core 3.1 system.
I closed all the open projects in VS and i restarted the PC and it works.

Try this, Maybe it'll help you.


答:
You can run the code below.  Hope this helps.</p>

```<code>// use this array instead on the original.  It creates a new array from the original
// array.
const newFilteredArray = Array.filter(url => url !== 'https://basueUrl.com/Claim' &&
   url !== 'https://basueUrl.com/ExplanationOfBenefit');
</code>```

Title: Remove or Filter values out of an Array using for loop or a function

Body:
You can run the code below.  Hope this helps.

// use this array instead on the original.  It creates a new array from the original
// array.
const newFilteredArray = Array.filter(url => url !== 'https://basueUrl.com/Claim' &&
   url !== 'https://basueUrl.com/ExplanationOfBenefit');


问:
Rails hidden field sessions possible?
Is it possible to pass a session via a hidden form field? (ie POST)

if so if it possible to between the standard method and field sessions on a per controller bases without losing information?

答:
If cookies are disabled, CGI:Sessions will automatically switch to using hidden fields, however, I'm not certain exactly how this behavior is supported in Rails. Moreover, changing this behavior to require the use of hidden fields may require modifying CGI:Session.

If the client has cookies disabled, the session id must be included as a parameter of all requests sent by the client to the server. The CGI::Session class in conjunction with the CGI class will transparently add the session id as a hidden input field to all forms generated using the CGI#form() HTML generation method. No built-in support is provided for other mechanisms, such as URL re-writing. The caller is responsible for extracting the session id from the session_id attribute and manually encoding it in URLs and adding it as a hidden input to HTML forms created by other mechanisms. Also, session expiry is not automatically handled.

Therefore, it should be possible to use this method, but as far as I know, it's not supported as a simple option in Rails.

To be clear, even ActiveRecord Session Store uses cookies, so don't equate session stores with how session data is handled by the client.

Finally, at one time there were plugins to support this behavior, but these plugins are old, don't appear to support Rails 3. See the "Non-cookie session" section of Sessions & Cookies in Ruby on Rails

Title: Rails hidden field sessions possible?


问:
How do i add values to a string array from a class?
I am trying to create a simple object-oriented program for a fictional movie theatre.
Therefore I am making a kind of list with all the movies. My issue is that I can not add genres to my genre array in the child classes to the Movies class.

Here is what I have made so far.

```<code>using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BentesBio
{
    class Program
    {
        static void Main(string[] args)
        {
            Movie[] moviesArray = new Movie[6];

            moviesArray[0] = new FeatureFilm { Director = "", Country = "", Budget = 0.0, BudgetCurrency = "", BudgetDKK = 0.0, Year = 0000, Score = "", Length = 00, Genre = { "", "" }, Cast = {} };
            moviesArray[1] = new FeatureFilm { Director = "", Country = "", Budget = 0.0, BudgetCurrency = "", BudgetDKK = 0.0, Year = 0000, Score = "", Length = 00 };
            moviesArray[2] = new FeatureFilm { Director = "", Country = "", Budget = 0.0, BudgetCurrency = "", BudgetDKK = 0.0, Year = 0000, Score = "", Length = 00 };
            moviesArray[3] = new FeatureFilm { Director = "", Country = "", Budget = 0.0, BudgetCurrency = "", BudgetDKK = 0.0, Year = 0000, Score = "", Length = 00 };
            moviesArray[4] = new Documentary { Director = "", Country = "", Budget = 0.0, BudgetCurrency = "", BudgetDKK = 0.0, Year = 0000, Score = "", Length = 00, Theme = { "", "" } };
            moviesArray[5] = new Documentary { Director = "", Country = "", Budget = 0.0, BudgetCurrency = "", BudgetDKK = 0.0, Year = 0000, Score = "", Length = 00 };

            Console.ReadKey();
        }
    }

    class Movie
    {
        public string Director { get; set; }
        public string Country { get; set; }
        public double Budget { get; set; }
        public string BudgetCurrency { get; set; }
        public double BudgetDKK { get; set; }
        public int Year { get; set; }
        public string Score { get; set; }
        public int Length { get; set; }
    }

    class FeatureFilm : Movie
    {
        public string[] Genre { get; set; }
        public string[] Cast { get; set; }
    }

    class Documentary : Movie
    {
        public string[] Theme { get; set; }
    }
}

</code>```

Any suggestions would be much appreciated.

答: Because of Movie has not got Genre you should cast Movie class to FeatureFilm class to work with Genre property. moviesArray is Movie array.</p>

Body:
I am trying to create a simple object-oriented program for a fictional movie theatre.
Therefore I am making a kind of list with all the movies. My issue is that I can not add genres to my genre array in the child classes to the Movies class.

Here is what I have made so far.

using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BentesBio
{
    class Program
    {
        static void Main(string[] args)
        {
            Movie[] moviesArray = new Movie[6];

            moviesArray[0] = new FeatureFilm { Director = "", Country = "", Budget = 0.0, BudgetCurrency = "", BudgetDKK = 0.0, Year = 0000, Score = "", Length = 00, Genre = { "", "" }, Cast = {} };
            moviesArray[1] = new FeatureFilm { Director = "", Country = "", Budget = 0.0, BudgetCurrency = "", BudgetDKK = 0.0, Year = 0000, Score = "", Length = 00 };
            moviesArray[2] = new FeatureFilm { Director = "", Country = "", Budget = 0.0, BudgetCurrency = "", BudgetDKK = 0.0, Year = 0000, Score = "", Length = 00 };
            moviesArray[3] = new FeatureFilm { Director = "", Country = "", Budget = 0.0, BudgetCurrency = "", BudgetDKK = 0.0, Year = 0000, Score = "", Length = 00 };
            moviesArray[4] = new Documentary { Director = "", Country = "", Budget = 0.0, BudgetCurrency = "", BudgetDKK = 0.0, Year = 0000, Score = "", Length = 00, Theme = { "", "" } };
            moviesArray[5] = new Documentary { Director = "", Country = "", Budget = 0.0, BudgetCurrency = "", BudgetDKK = 0.0, Year = 0000, Score = "", Length = 00 };

            Console.ReadKey();
        }
    }

    class Movie
    {
        public string Director { get; set; }
        public string Country { get; set; }
        public double Budget { get; set; }
        public string BudgetCurrency { get; set; }
        public double BudgetDKK { get; set; }
        public int Year { get; set; }
        public string Score { get; set; }
        public int Length { get; set; }
    }

    class FeatureFilm : Movie
    {
        public string[] Genre { get; set; }
        public string[] Cast { get; set; }
    }

    class Documentary : Movie
    {
        public string[] Theme { get; set; }
    }
}

Any suggestions would be much appreciated.


问:
webpack - MiniCssExtractPlugin set absolute path for .css file
remove relative URLs and use absolute URLs in CSS imports.

webpack code -

```<code> new MiniCssExtractPlugin({
            filename: '[name].[contenthash].css',
        }),
</code>```

bundle file in html is

this is relative path but i want to set abosolute path to this .css url from webpack config file using  MiniCssExtractPlugin

Impact
An attacker may trick browsers into importing JavaScript or HTML code as a stylesheet. This has been shown to enable a number of different attacks, including
cross-site scripting (XSS) and exfiltration of CSRF tokens.

webpack.config file

```<code>/* eslint-disable global-require */
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const WebpackCleanupPlugin = require('webpack-cleanup-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const webpackBundleAnalyzer = require('webpack-bundle-analyzer');

process.env.NODE_ENV = 'production';

module.exports = {
    mode: 'production',
    target: 'web',
    entry: {
        bundle: path.join(__dirname, 'src', 'index.jsx'),
    },
    output: {
        path: path.join(__dirname, 'build'),
        publicPath: '/',
        filename: '[name].[contenthash].js',
    },
    devtool: 'source-map',
    resolve: {
        modules: [path.resolve(__dirname, 'src'), 'node_modules'],
    },
    module: {
        rules: [
            {
                test: /.(js|jsx)$/,
                exclude: /node_modules\/(?!objectmodel).+/,
                loader: 'babel-loader',
                resolve: {
                    extensions: ['.js', '.jsx'],
                },
            },
            {
                test: /\.(s[ac]ss|css)$/i,
                use: [
                    MiniCssExtractPlugin.loader,
                    {
                        loader: 'css-loader',
                        options: { sourceMap: true },
                    },
                    {
                        loader: 'sass-loader',
                        options: { sourceMap: true },
                    },
                    {
                        loader: 'postcss-loader',
                        options: {
                            plugins: () => [require('cssnano')],
                            sourceMap: true,
                        },
                    },
                ],
            },
            {
                test: /\.(pdf|ico|png|jpg|svg)$/,
                use: 'file-loader?name=assets/[name].[ext]',
            },
        ],
    },
    plugins: [
        new WebpackCleanupPlugin(),
        new webpackBundleAnalyzer.BundleAnalyzerPlugin({ analyzerMode: 'static' }),
        new MiniCssExtractPlugin({
            filename: '[name].[contenthash].css',
        }),
        new webpack.DefinePlugin({
            'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
        }),
        new HtmlWebpackPlugin({
            filename: 'index.html',
            favicon: 'src/favicon.ico',
            template: path.join(__dirname, 'src', 'index.html'),
            minify: {
                removeComments: true,
                collapseWhitespace: true,
                removeRedundantAttributes: true,
                useShortDoctype: true,
                removeEmptyAttributes: true,
                removeStyleLinkTypeAttributes: true,
                keepClosingSlash: true,
                minifyJS: true,
                minifyCSS: true,
                minifyURLs: true,
            },
        }),
    ],
};
</code>```

答:
You can change your output.publicPath to the absolute prefix, it will change all of your assets (in html, in css) to be prefixed with it.

```<code>output: {
  path: path.join(__dirname, 'build'),
  publicPath: 'https://my-cdn.com/',
  filename: '[name].[contenthash].js',
},
</code>```

Body:
remove relative URLs and use absolute URLs in CSS imports.

webpack code -

 new MiniCssExtractPlugin({
            filename: '[name].[contenthash].css',
        }),

bundle file in html is

this is relative path but i want to set abosolute path to this .css url from webpack config file using  MiniCssExtractPlugin

Impact
An attacker may trick browsers into importing JavaScript or HTML code as a stylesheet. This has been shown to enable a number of different attacks, including
cross-site scripting (XSS) and exfiltration of CSRF tokens.

webpack.config file

/* eslint-disable global-require */
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const WebpackCleanupPlugin = require('webpack-cleanup-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const webpackBundleAnalyzer = require('webpack-bundle-analyzer');

process.env.NODE_ENV = 'production';

module.exports = {
    mode: 'production',
    target: 'web',
    entry: {
        bundle: path.join(__dirname, 'src', 'index.jsx'),
    },
    output: {
        path: path.join(__dirname, 'build'),
        publicPath: '/',
        filename: '[name].[contenthash].js',
    },
    devtool: 'source-map',
    resolve: {
        modules: [path.resolve(__dirname, 'src'), 'node_modules'],
    },
    module: {
        rules: [
            {
                test: /.(js|jsx)$/,
                exclude: /node_modules\/(?!objectmodel).+/,
                loader: 'babel-loader',
                resolve: {
                    extensions: ['.js', '.jsx'],
                },
            },
            {
                test: /\.(s[ac]ss|css)$/i,
                use: [
                    MiniCssExtractPlugin.loader,
                    {
                        loader: 'css-loader',
                        options: { sourceMap: true },
                    },
                    {
                        loader: 'sass-loader',
                        options: { sourceMap: true },
                    },
                    {
                        loader: 'postcss-loader',
                        options: {
                            plugins: () => [require('cssnano')],
                            sourceMap: true,
                        },
                    },
                ],
            },
            {
                test: /\.(pdf|ico|png|jpg|svg)$/,
                use: 'file-loader?name=assets/[name].[ext]',
            },
        ],
    },
    plugins: [
        new WebpackCleanupPlugin(),
        new webpackBundleAnalyzer.BundleAnalyzerPlugin({ analyzerMode: 'static' }),
        new MiniCssExtractPlugin({
            filename: '[name].[contenthash].css',
        }),
        new webpack.DefinePlugin({
            'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
        }),
        new HtmlWebpackPlugin({
            filename: 'index.html',
            favicon: 'src/favicon.ico',
            template: path.join(__dirname, 'src', 'index.html'),
            minify: {
                removeComments: true,
                collapseWhitespace: true,
                removeRedundantAttributes: true,
                useShortDoctype: true,
                removeEmptyAttributes: true,
                removeStyleLinkTypeAttributes: true,
                keepClosingSlash: true,
                minifyJS: true,
                minifyCSS: true,
                minifyURLs: true,
            },
        }),
    ],
};

Body:
You can change your output.publicPath to the absolute prefix, it will change all of your assets (in html, in css) to be prefixed with it.

output: {
  path: path.join(__dirname, 'build'),
  publicPath: 'https://my-cdn.com/',
  filename: '[name].[contenthash].js',
},


问:
git merge conflict after git amend - "Your branch and 'origin/master' have diverged"
This is what happens:

After a recent commit to remote master, I make a small trivial change to my local repo

I add git commit --amend and leave the same commit message as HEAD

I try to push the repo to master with git push

And now I get

```<code>On branch master
Your branch and 'origin/master' have diverged,
and have 1 and 1 different commit each, respectively.
  (use "git pull" to merge the remote branch into yours)
nothing to commit, working directory clean
</code>```

I want to understand:

Why this exactly happens?

What can I do to prevent this?

How do I reconcile master with local after a git amend?

答:
If you are the only one working on the project after your amend you could have run

```<code>git push -f origin master
</code>```

If you are not the only one working on the project be carefull of what you do because it's rewriting history.

Here is a great article about amend :

https://medium.com/@igor_marques/git-basics-adding-more-changes-to-your-last-commit-1629344cb9a8

Body:
This is what happens:

After a recent commit to remote master, I make a small trivial change to my local repo

I add git commit --amend and leave the same commit message as HEAD

I try to push the repo to master with git push

And now I get

On branch master
Your branch and 'origin/master' have diverged,
and have 1 and 1 different commit each, respectively.
  (use "git pull" to merge the remote branch into yours)
nothing to commit, working directory clean

I want to understand:

Why this exactly happens?

What can I do to prevent this?

How do I reconcile master with local after a git amend?

Body:
If you are the only one working on the project after your amend you could have run

git push -f origin master

If you are not the only one working on the project be carefull of what you do because it's rewriting history.

Here is a great article about amend :

https://medium.com/@igor_marques/git-basics-adding-more-changes-to-your-last-commit-1629344cb9a8


问:
showing only country code in material-select angular
I use this in HTML

```<code><mat-form-field style="width: 70px;margin-left: 50px;">
  <mat-label>Select an option</mat-label>
  <mat-select (openedChange)="toogleCountry()" [(value)]="selected">
    <mat-option value="+91">
      <span>{{"+91"}}</span>
      <span *ngIf="showCountry">{{"india"}}</span>
    </mat-option>
  </mat-select>
</mat-form-field>
</code>```

and this in component.ts by using (openChange) event of mat-select

```<code>showCountry = false;
toogleCountry() {
      this.showCountry = !this.showCountry;
  }
</code>```

but I am getting the desired result after I remove focus from mat select

答:
You can use mat-select-trigger to achieve what you want. You just have to define what should be visible after the user selected an option, e.g. <mat-select-trigger> {{ selected?.code }} </mat-select-trigger>.

<mat-form-field style="width: 70px;margin-left: 50px;">
    <mat-label>Select an option</mat-label>
    <mat-select [(value)]="selected">
        <mat-select-trigger>
            {{ selected?.code }}
        </mat-select-trigger>
        <mat-option *ngFor="let opt of countries" [value]="opt">{{opt.code}} - {{opt.name}}</mat-option>
    </mat-select>
</mat-form-field>
```

Have a look at this Stackblitz for a working example.

Body:
I use this in HTML

<mat-form-field style="width: 70px;margin-left: 50px;">
  <mat-label>Select an option</mat-label>
  <mat-select (openedChange)="toogleCountry()" [(value)]="selected">
    <mat-option value="+91">
      {{"+91"}}
      {{"india"}}
    </mat-option>
  </mat-select>
</mat-form-field>

and this in component.ts by using (openChange) event of mat-select

showCountry = false;
toogleCountry() {
      this.showCountry = !this.showCountry;
  }

but I am getting the desired result after I remove focus from mat select

Body:
You can use mat-select-trigger to achieve what you want. You just have to define what should be visible after the user selected an option, e.g. <mat-select-trigger> {{ selected?.code }} </mat-select-trigger>.

<mat-form-field style="width: 70px;margin-left: 50px;">
    <mat-label>Select an option</mat-label>
    <mat-select [(value)]="selected">
        <mat-select-trigger>
            {{ selected?.code }}
        </mat-select-trigger>
        <mat-option *ngFor="let opt of countries" [value]="opt">{{opt.code}} - {{opt.name}}</mat-option>
    </mat-select>
</mat-form-field>

Have a look at this Stackblitz for a working example.


答:
The first approach is modifying the array while the loop is being executed, which generates problem with the index because the array.length changes when you call Array.prototype.splice.

In the second approach, you're not passing what you think

console.log("https://basueUrl.com/ExplanationOfBenefit" & "https://basueUrl.com/Claim");
// A number? probably you want an array.```
</div>
</div>
</p>

<p>You can use the function <code>filter</code> and the function <code>includes</code> as follow:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let skip = ["https://basueUrl.com/Claim", "https://basueUrl.com/ExplanationOfBenefit"];
let arr = ["https://basueUrl.com/Patient","https://basueUrl.com/Organization","https://basueUrl.com/Claim","https://basueUrl.com/Practitioner","https://basueUrl.com/Encounter","https://basueUrl.com/Condition","https://basueUrl.com/Claim","https://basueUrl.com/ExplanationOfBenefit","https://basueUrl.com/Claim","https://basueUrl.com/ExplanationOfBenefit","https://basueUrl.com/ExplanationOfBenefit"];
let result = arr.filter(url => !skip.includes(url));

console.log(result);</code>```

Body:
The first approach is modifying the array while the loop is being executed, which generates problem with the index because the array.length changes when you call Array.prototype.splice.

In the second approach, you're not passing what you think

console.log("https://basueUrl.com/ExplanationOfBenefit" & "https://basueUrl.com/Claim");
// A number? probably you want an array.

You can use the function filter and the function includes as follow:

let skip = ["https://basueUrl.com/Claim", "https://basueUrl.com/ExplanationOfBenefit"];
let arr = ["https://basueUrl.com/Patient","https://basueUrl.com/Organization","https://basueUrl.com/Claim","https://basueUrl.com/Practitioner","https://basueUrl.com/Encounter","https://basueUrl.com/Condition","https://basueUrl.com/Claim","https://basueUrl.com/ExplanationOfBenefit","https://basueUrl.com/Claim","https://basueUrl.com/ExplanationOfBenefit","https://basueUrl.com/ExplanationOfBenefit"];
let result = arr.filter(url => !skip.includes(url));

console.log(result);