问:
how to add SSL certificates to okHttp mutual TLS connection?
I have a .pem and a .key files already that I dont want to install/import it locally, just tell my client to use them, is it possible? its not a self signed certificate

Basically, in my curl Im doing something like this:

```<code>curl --key mykey.key --cert mycert.pem https://someurl.com/my-endpoint
</code>```

I have checked this answer

How to make https request with ssl certificate in Retrofit

also this https://github.com/square/okhttp/blob/master/samples/guide/src/main/java/okhttp3/recipes/CustomTrust.java (but might not make sense since I dont get an object of the type I need)

Basically I have my okHttpClient

```<code>val okHttpClient = OkHttpClient.Builder()
    .sslSocketFactory(?, ?) //here I tried to call sslSocketFactory, trustManager following the example from the CustomTrust.java
    .build()
</code>```

Any ideas for a solution?

Have checked this documentation as well but again the ssl part is not completed nor at the samples

https://square.github.io/okhttp/https/#customizing-trusted-certificates-kt-java

So I tried doing this (base on the okhttp samples)

```<code>private fun trustedCertificatesInputStream(): InputStream {
        val comodoRsaCertificationAuthority = (""
            + "-----BEGIN CERTIFICATE-----\n" +
            "-----END CERTIFICATE-----")
        return Buffer()
            .writeUtf8(comodoRsaCertificationAuthority)
            .inputStream()
    }

    val loggingInterceptor = HttpLoggingInterceptor().apply {
        level = HttpLoggingInterceptor.Level.BODY
    }

    fun createClient() : OkHttpClient {

        val trustManager: X509TrustManager
        val sslSocketFactory: SSLSocketFactory
        try {
            trustManager = trustManagerForCertificates(trustedCertificatesInputStream())
            val sslContext = SSLContext.getInstance("TLS")
            sslContext.init(null, arrayOf<TrustManager>(trustManager), null)
            sslSocketFactory = sslContext.socketFactory

        } catch (e: GeneralSecurityException) {
            throw RuntimeException(e)
        }
        return OkHttpClient.Builder()
            .sslSocketFactory(sslSocketFactory, trustManager)
            .connectTimeout(45, TimeUnit.SECONDS)
            .readTimeout(45, TimeUnit.SECONDS)
            .protocols(listOf(Protocol.HTTP_1_1))
            .addInterceptor(loggingInterceptor)
            .build()
    }

    @Throws(GeneralSecurityException::class)
    private fun trustManagerForCertificates(input: InputStream): X509TrustManager {
        val certificateFactory: CertificateFactory = CertificateFactory.getInstance("X.509")
        val certificates: Collection<Certificate?> = certificateFactory.generateCertificates(input)
        val password = "password".toCharArray() // Any password will work.
        val keyStore = newEmptyKeyStore(password)

        for ((index, certificate) in certificates.withIndex()) {
            val certificateAlias = index.toString()
            keyStore.setCertificateEntry(certificateAlias, certificate)
        }
        // Use it to build an X509 trust manager.
        val keyManagerFactory: KeyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm())
        keyManagerFactory.init(keyStore, password)

        val trustManagerFactory: TrustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
        trustManagerFactory.init(keyStore)

        val trustManagers: Array<TrustManager> = trustManagerFactory.getTrustManagers()
        return trustManagers[0]!! as X509TrustManager
    }

    @Throws(GeneralSecurityException::class)
    private fun newEmptyKeyStore(password: CharArray): KeyStore {
        return try {
            val keyStore = KeyStore.getInstance(KeyStore.getDefaultType())
            val inputStream: InputStream? = null // By convention, 'null' creates an empty key store.
            keyStore.load(inputStream, password)
            keyStore
        } catch (e: IOException) {
            throw AssertionError(e)
        }

    }
</code>```

and I get an error of

```<code>javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
</code>```

searching about the error seems like I should install the SSL locally, which I should avoid to do it since I cannot install it that way in the server, is there any way I can make it work?

答:
I presume you want to configure TLS mutual auth, and that's what they key is for?

Take a look at okhttp-tls which has APIs for turning certificate and private keys into the corresponding Java objects.

Body:
I have a .pem and a .key files already that I dont want to install/import it locally, just tell my client to use them, is it possible? its not a self signed certificate

Basically, in my curl Im doing something like this:

curl --key mykey.key --cert mycert.pem https://someurl.com/my-endpoint

I have checked this answer

How to make https request with ssl certificate in Retrofit

also this https://github.com/square/okhttp/blob/master/samples/guide/src/main/java/okhttp3/recipes/CustomTrust.java (but might not make sense since I dont get an object of the type I need)

Basically I have my okHttpClient

val okHttpClient = OkHttpClient.Builder()
    .sslSocketFactory(?, ?) //here I tried to call sslSocketFactory, trustManager following the example from the CustomTrust.java
    .build()

Any ideas for a solution?

Have checked this documentation as well but again the ssl part is not completed nor at the samples

https://square.github.io/okhttp/https/#customizing-trusted-certificates-kt-java

So I tried doing this (base on the okhttp samples)

private fun trustedCertificatesInputStream(): InputStream {
        val comodoRsaCertificationAuthority = (""
            + "-----BEGIN CERTIFICATE-----\n" +
            "-----END CERTIFICATE-----")
        return Buffer()
            .writeUtf8(comodoRsaCertificationAuthority)
            .inputStream()
    }

    val loggingInterceptor = HttpLoggingInterceptor().apply {
        level = HttpLoggingInterceptor.Level.BODY
    }

    fun createClient() : OkHttpClient {

        val trustManager: X509TrustManager
        val sslSocketFactory: SSLSocketFactory
        try {
            trustManager = trustManagerForCertificates(trustedCertificatesInputStream())
            val sslContext = SSLContext.getInstance("TLS")
            sslContext.init(null, arrayOf<TrustManager>(trustManager), null)
            sslSocketFactory = sslContext.socketFactory

        } catch (e: GeneralSecurityException) {
            throw RuntimeException(e)
        }
        return OkHttpClient.Builder()
            .sslSocketFactory(sslSocketFactory, trustManager)
            .connectTimeout(45, TimeUnit.SECONDS)
            .readTimeout(45, TimeUnit.SECONDS)
            .protocols(listOf(Protocol.HTTP_1_1))
            .addInterceptor(loggingInterceptor)
            .build()
    }

    @Throws(GeneralSecurityException::class)
    private fun trustManagerForCertificates(input: InputStream): X509TrustManager {
        val certificateFactory: CertificateFactory = CertificateFactory.getInstance("X.509")
        val certificates: Collection<Certificate?> = certificateFactory.generateCertificates(input)
        val password = "password".toCharArray() // Any password will work.
        val keyStore = newEmptyKeyStore(password)

        for ((index, certificate) in certificates.withIndex()) {
            val certificateAlias = index.toString()
            keyStore.setCertificateEntry(certificateAlias, certificate)
        }
        // Use it to build an X509 trust manager.
        val keyManagerFactory: KeyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm())
        keyManagerFactory.init(keyStore, password)

        val trustManagerFactory: TrustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
        trustManagerFactory.init(keyStore)

        val trustManagers: Array<TrustManager> = trustManagerFactory.getTrustManagers()
        return trustManagers[0]!! as X509TrustManager
    }

    @Throws(GeneralSecurityException::class)
    private fun newEmptyKeyStore(password: CharArray): KeyStore {
        return try {
            val keyStore = KeyStore.getInstance(KeyStore.getDefaultType())
            val inputStream: InputStream? = null // By convention, 'null' creates an empty key store.
            keyStore.load(inputStream, password)
            keyStore
        } catch (e: IOException) {
            throw AssertionError(e)
        }

    }

and I get an error of

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

searching about the error seems like I should install the SSL locally, which I should avoid to do it since I cannot install it that way in the server, is there any way I can make it work?


来源: stackexchange

问:
shape recognition on picture taken from webcam
i would like to extract information is there a human hand on some photo taken from local webcam.
I get how to extract light information, find brightest points or few of them, but how to recognize shape on some image?

I have started C# project, and I'm using AForge library to apply some filters to captured images, but I'm pretty stuck with shape recognition.

Where should I start?

答:
You might have a look at the image recognition project over at codeplex.

http://www.codeplex.com/IR

It is an open source .NET project written in c#.  It should be a good place to start.

OwnerDisplayName: LILkillaBEE

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Khadaji


问:
ASP.NET MVC3 Code-First Error- attempting to update entity
I've checked this question and it seems to be related to what I need, but does not answer it exactly.

I have an entity (Sql Compact using EF Code First via MVC3- if that wasn't clear from the title) for an "Issue" (generic issue tracking, just for my own education understanding of how MVC3 works).  The Issue class has a CreatedBy property (Int reference to a User who Created the Issue) and a CreatedDate property (DateTime).  When I use the scaffolded code to update (modified only to prevent some updated date fields from being modified by the user):

```<code>        if (ModelState.IsValid)
        {
            issue.LastActivity = (DateTime?)DateTime.Now.Date;
            if (issue.ClosedBy != null) issue.ClosedDate = (DateTime?)DateTime.Now.Date;
            startingIssue = null;
            db.Entry(issue).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
</code>```

I receive the error mentioned in the linked question (conversion of a datetime2 data type to a datetime data type etc., etc.,)

When I step through the code, it appears my CreatedBy and CreatedDate properties are not contained in the instance of issue that the controller is passing around.  When I try to fix that by grabbing another copy of the issue from the db, and updating those to values:

```<code>        var startingIssue = db.Issues.Find(issue.IssueId);
        if (ModelState.IsValid)
        {
            if (issue.CreatedBy != startingIssue.CreatedBy) issue.CreatedBy = startingIssue.CreatedBy;
            if (issue.CreatedDate != startingIssue.CreatedDate) issue.CreatedDate = startingIssue.CreatedDate;
            issue.LastActivity = (DateTime?)DateTime.Now.Date;
            if (issue.ClosedBy != null) issue.ClosedDate = (DateTime?)DateTime.Now.Date;
            startingIssue = null;
            db.Entry(issue).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
</code>```

I get the concurrency violation: An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.

So, how do I get EF to see the date which is already set in the DB (so it doesn't try to update the CreatedDate to 1/1/0001) without violating concurrency?

Edit
Okay... I found it.  I was, apparently, looking for @Html.HiddenFor(model => model.[property]) and adding the editor to the view anyway.  That seems a little silly and round-about to me, but it does work without having to add custom code to detach one object and substitute an updated one.

答:
If the CreateDate and CreatedBy fields are not in the edit form, the update action object will not have the db values.

The additional call to the db and resetting, as Ed's answer describes, can be avoided if you include those fields in the edit form. Then the normal model binding should pick them up and give them back to you on the update.

ContentLicense: CC BY-SA 3.0

Body:
I've checked this question and it seems to be related to what I need, but does not answer it exactly.

I have an entity (Sql Compact using EF Code First via MVC3- if that wasn't clear from the title) for an "Issue" (generic issue tracking, just for my own education understanding of how MVC3 works).  The Issue class has a CreatedBy property (Int reference to a User who Created the Issue) and a CreatedDate property (DateTime).  When I use the scaffolded code to update (modified only to prevent some updated date fields from being modified by the user):

        if (ModelState.IsValid)
        {
            issue.LastActivity = (DateTime?)DateTime.Now.Date;
            if (issue.ClosedBy != null) issue.ClosedDate = (DateTime?)DateTime.Now.Date;
            startingIssue = null;
            db.Entry(issue).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }

I receive the error mentioned in the linked question (conversion of a datetime2 data type to a datetime data type etc., etc.,)

When I step through the code, it appears my CreatedBy and CreatedDate properties are not contained in the instance of issue that the controller is passing around.  When I try to fix that by grabbing another copy of the issue from the db, and updating those to values:

        var startingIssue = db.Issues.Find(issue.IssueId);
        if (ModelState.IsValid)
        {
            if (issue.CreatedBy != startingIssue.CreatedBy) issue.CreatedBy = startingIssue.CreatedBy;
            if (issue.CreatedDate != startingIssue.CreatedDate) issue.CreatedDate = startingIssue.CreatedDate;
            issue.LastActivity = (DateTime?)DateTime.Now.Date;
            if (issue.ClosedBy != null) issue.ClosedDate = (DateTime?)DateTime.Now.Date;
            startingIssue = null;
            db.Entry(issue).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }

I get the concurrency violation: An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.

So, how do I get EF to see the date which is already set in the DB (so it doesn't try to update the CreatedDate to 1/1/0001) without violating concurrency?

Edit
Okay... I found it.  I was, apparently, looking for @Html.HiddenFor(model => model.[property]) and adding the editor to the view anyway.  That seems a little silly and round-about to me, but it does work without having to add custom code to detach one object and substitute an updated one.


问:
What are TypeErrors? One of them appeared in my code
Why is this error coming? It is a TypeError. And also, what are TypeErrors anyways?

All the code needed:

```<code>from collections import namedtuple
account = namedtuple('person', 'password')

acc1 = account('example', 'passwordex1')
</code>```

And here is the error:

```<code>Traceback (most recent call last):
  File "C:\Users\user\Desktop\Python\Secret.py", line 4, in <module>
    acc1 = account('example', 'passwordex1')
TypeError: __new__() takes 2 positional arguments but 3 were given
</code>```

答:
namedtuple('person', 'password') creates a type person with one field (password). You want this instead:

```<code>account = namedtuple('account', ('person', 'password'))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Why is this error coming? It is a TypeError. And also, what are TypeErrors anyways?

All the code needed:

from collections import namedtuple
account = namedtuple('person', 'password')

acc1 = account('example', 'passwordex1')

And here is the error:

Traceback (most recent call last):
  File "C:\Users\user\Desktop\Python\Secret.py", line 4, in <module>
    acc1 = account('example', 'passwordex1')
TypeError: __new__() takes 2 positional arguments but 3 were given

Body:
namedtuple('person', 'password') creates a type person with one field (password). You want this instead:

account = namedtuple('account', ('person', 'password'))


问:
Which Dimensions and Metrics of Google Ad Manager account should be selected?
I am trying to create a report in Google Ad Manager account which can record all the ads of all the advertisers in a given website

I am not sure which dimensions and metrics should be selected in the Ad Manager account for generating this type of report

Taken help from this but didn't find anything relevant https://support.google.com/admanager/table/7531695?hl=en

Any help/suggestion will be highly appreciated.TIA

答:
here are the steps that will help you generate a report in the Google Ad Manager:

Go to the Home page and select Reporting. Click on New report.

Name the report and scroll down to Dimensions. Here, select Delivery and then Advertisers.

Then, scroll down to Metrics, and select the metrics you want to view. You can select multiple metrics at once such as Impressions, Revenue, Clicks, etc.


问:
Rollup Font Awesome CSS?
I'm including Font Awesome in a library project with:

```<code>import '@fortawesome/fontawesome-pro/css/all.min.css';
</code>```

When running locally, this works fine and I can use the Font Awesome classes to create icons.

But after I rollup the project and include I get the error:

Module not found: Can't resolve '@fortawesome/fontawesome-pro/css/all.min.css'

Other CSS files are being bundled into an output css file. Why not that one? Here's my rollup.config.js.

```<code>import babel from 'rollup-plugin-babel';
import css from 'rollup-plugin-css-only';

export default {
  input: 'src/index.js',
  output: {
    file: 'bundle.js',
    format: 'cjs'
  },

  external: [
    'react',
    'react-dom',
    'lodash',
    'moment',
    'react-router-dom',
  ],

  plugins: [
    babel({
      exclude: "node_modules/**",
      presets: ["@babel/preset-react", "@babel/preset-env"],
    }),
    css({
      output: 'bundle.css'
    })
  ],
};
</code>```

答:
This is likely caused by Rollup not being able to resolve the bare module specifier ('@fortawesome/fontawesome-pro...' instead of ./path/to/@fortawesome...').

Try adding the @rollup/plugin-node-resolve plugin:

import resolve from '@rollup/plugin-node-resolve';

export default {
  //...
  plugins: [
    babel({
      exclude: "node_modules/**",
      presets: ["@babel/preset-react", "@babel/preset-env"],
    }),
    resolve(),
    css({
      output: 'bundle.css'
    })
  ],
};
``
```

Title: Rollup Font Awesome CSS?

Body:
I'm including Font Awesome in a library project with:

import '@fortawesome/fontawesome-pro/css/all.min.css';

When running locally, this works fine and I can use the Font Awesome classes to create icons.

But after I rollup the project and include I get the error:

Module not found: Can't resolve '@fortawesome/fontawesome-pro/css/all.min.css'

Other CSS files are being bundled into an output css file. Why not that one? Here's my rollup.config.js.

import babel from 'rollup-plugin-babel';
import css from 'rollup-plugin-css-only';

export default {
  input: 'src/index.js',
  output: {
    file: 'bundle.js',
    format: 'cjs'
  },

  external: [
    'react',
    'react-dom',
    'lodash',
    'moment',
    'react-router-dom',
  ],

  plugins: [
    babel({
      exclude: "node_modules/**",
      presets: ["@babel/preset-react", "@babel/preset-env"],
    }),
    css({
      output: 'bundle.css'
    })
  ],
};


问:
Uicollection view dynamic height but fixed width
I am working with UICollectionView I have 4 different kind of cells. Every cell is designed in xib file . when i load them in collection view it goes out of screen. i don't know why it is happening. Some cells have fixed height while some have dynamic height (depends on data coming from API). So is there any possible way to solve this issue.
i have tried Estimate size automatic to dynamic

```<code>override func awakeFromNib() {
    super.awakeFromNib()
    self.contentView.translatesAutoresizingMaskIntoConstraints = false
    let screenwidth = UIScreen.main.bounds.size.width
    widthAnchor.constraint(equalToConstant: screenwidth-20)
}

func setSize () {
    let layout = mainCollection.collectionViewLayout as! UICollectionViewFlowLayout
    layout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)}
</code>```

}

答:
try this!</p>

```<code>let screenWidth = self.CollecionView.frame.width
</code>```

Body:
I am working with UICollectionView I have 4 different kind of cells. Every cell is designed in xib file . when i load them in collection view it goes out of screen. i don't know why it is happening. Some cells have fixed height while some have dynamic height (depends on data coming from API). So is there any possible way to solve this issue.
i have tried Estimate size automatic to dynamic

override func awakeFromNib() {
    super.awakeFromNib()
    self.contentView.translatesAutoresizingMaskIntoConstraints = false
    let screenwidth = UIScreen.main.bounds.size.width
    widthAnchor.constraint(equalToConstant: screenwidth-20)
}

func setSize () {
    let layout = mainCollection.collectionViewLayout as! UICollectionViewFlowLayout
    layout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)}

}

Body:
try this!

let screenWidth = self.CollecionView.frame.width


问:
Can Javascript detect difference between server down and off line?
I have had an instance recently were our webserver (host website and app api) turned its toes up and the redundancy did not kick in.

This highlighted a vital missing element of our app which is missing. The App reported 'poor or missing connection' based on XMLHttpRequest.readyState = 0 when infact the server was offline.

Is there a viable method to report if a server is off line or the problem is client end (poor signal)?

答:
The best option is to have another always present and reliable server that monitorizes the non-reliable servers with ping or whatever is necessary. I would use your own server instead of third party because third party can be down, fail or change apis without previous notification.

Althought there are some tricks and network apis that can help like doing ping like in Is it possible to ping a server from Javascript? and reading the error types, however seems to be not very wide-browser compatible sollution or dns queries like in https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/dns/resolve which directly are not compatible with other browsers than Firefox.


问:
Custom context path in external tomcat
I made a Spring-Boot application that I want to run in an external tomcat 8.

In a Spring-Boot application , the context-path can be chosen using the property server.context-path in application.properties but as I am using an external tomcat 8, this property is not used.

Hence, I took a look at the tomcat-8 documentation which states:

If you want to deploy a WAR file or a directory using a context path that is not related to the base file name then one of the following options must be used to prevent double-deployment:

Disable autoDeploy and deployOnStartup and define all Contexts in server.xml

Locate the WAR and/or directory outside of the Host's appBase and use a context.xml file with a docBase attribute to define it.

As I do not want to pollute server.xml, I chose the second option. Hence, I located the war in /home/myuser/myapp/application-1.0.0.war and I placed a context file name application-1.0.0.xml under conf/Catalina/localhost. This file contains only those 2 lines :

```<code><?xml version="1.0" encoding="UTF-8"?>
<Context path="/myapp" docBase="/home/myuser/myapp"/>
</code>```

I can see in the logs that tomcat8 starts successfully, the application appears to be deployed in the tomcat manager but :

The path is /application-1.0.0 instead of /myapp.

Moreover, a directory application-1.0.0 appears in the work directory but stays empty.

The logs does not show any spring related logs as if the application had never been initialized.

Note : I know that the war is correct because it works if I place it in the webapp directory (with the default context path though).

Note : If I rename application-1.0.0.xml to foo.xml, the tomcat manager shows that the application is deployed under context-path /foo (but it is still never started).

Any ideas?

答:
If it helps someone, following (placed inside conf\Catalina\localhost\service-discovery.xml) works for me on on Tomcat 9</p>

```<code><?xml version="1.0" encoding="UTF-8"?>
<Context path="/service-discovery" docBase="D:/Projects/codebase/apps/service-discovery/target/service-discovery.war"/>
</code>```

Title: Custom context path in external tomcat

Body:
I made a Spring-Boot application that I want to run in an external tomcat 8.

In a Spring-Boot application , the context-path can be chosen using the property server.context-path in application.properties but as I am using an external tomcat 8, this property is not used.

Hence, I took a look at the tomcat-8 documentation which states:

If you want to deploy a WAR file or a directory using a context path that is not related to the base file name then one of the following options must be used to prevent double-deployment:

Disable autoDeploy and deployOnStartup and define all Contexts in server.xml

Locate the WAR and/or directory outside of the Host's appBase and use a context.xml file with a docBase attribute to define it.

As I do not want to pollute server.xml, I chose the second option. Hence, I located the war in /home/myuser/myapp/application-1.0.0.war and I placed a context file name application-1.0.0.xml under conf/Catalina/localhost. This file contains only those 2 lines :

<?xml version="1.0" encoding="UTF-8"?>
<Context path="/myapp" docBase="/home/myuser/myapp"/>

I can see in the logs that tomcat8 starts successfully, the application appears to be deployed in the tomcat manager but :

The path is /application-1.0.0 instead of /myapp.

Moreover, a directory application-1.0.0 appears in the work directory but stays empty.

The logs does not show any spring related logs as if the application had never been initialized.

Note : I know that the war is correct because it works if I place it in the webapp directory (with the default context path though).

Note : If I rename application-1.0.0.xml to foo.xml, the tomcat manager shows that the application is deployed under context-path /foo (but it is still never started).

Any ideas?

Body:
If it helps someone, following (placed inside conf\Catalina\localhost\service-discovery.xml) works for me on on Tomcat 9

<?xml version="1.0" encoding="UTF-8"?>
<Context path="/service-discovery" docBase="D:/Projects/codebase/apps/service-discovery/target/service-discovery.war"/>


问:
Input value not updated with JQuery datepicker in Angular 7
I am using Angular 7 with a JQuery datepicker : https://github.com/uxsolutions/bootstrap-datepicker

```<code>           <div class="col-lg-2">
              <div class="form-group">
                <div class="input-group">
                  <input class="form-control form-control-lg" data-provide="datepicker" data-date-language="fr" type="text" data-date-format="dd/mm/yyyy" placeholder="From" [(ngModel)]="from" name="from" />
                  <div class="input-group-append">
                    <span class="input-group-text"><i class="fa fa-calendar" aria-hidden="true"></i></span>
                  </div>
                </div>
              </div>
            </div>
</code>```

But in the component, this value I receive in this.from is undefined..

```<code>export class SearchBarComponent implements OnInit {
  constructor(
    private router: Router
  ) { }

  search: string;
  from: string;
  to: string;

  ngOnInit() {
  }

  onSubmit() {
    console.log(this.from)
  }
}
</code>```

I do not want to use bundle like ng-boostrap or ngx-boostrap because I do not want to trick with the navbar to get it working. And I prefer to control the dependencies of Boostrap.

Is there a simple way to watch for changes of this input value please ? I did not find this answer clearly in the questions that can exist.

答:
```<code>$('#data').datepicker({
    onSelect: (dateText: any, object: any) => {
        this.formulario.get('data').setValue(dateText);
    }
});
</code>```

Body:
I am using Angular 7 with a JQuery datepicker : https://github.com/uxsolutions/bootstrap-datepicker

                  <input class="form-control form-control-lg" data-provide="datepicker" data-date-language="fr" type="text" data-date-format="dd/mm/yyyy" placeholder="From" [(ngModel)]="from" name="from" />

But in the component, this value I receive in this.from is undefined..

export class SearchBarComponent implements OnInit {
  constructor(
    private router: Router
  ) { }

  search: string;
  from: string;
  to: string;

  ngOnInit() {
  }

  onSubmit() {
    console.log(this.from)
  }
}

I do not want to use bundle like ng-boostrap or ngx-boostrap because I do not want to trick with the navbar to get it working. And I prefer to control the dependencies of Boostrap.

Is there a simple way to watch for changes of this input value please ? I did not find this answer clearly in the questions that can exist.


问:
How to replace specific dictionary value based on key using LINQ
I tried below code but somehow it is not working.

```<code> employeesList.ForEach(x => x.ToDictionary(y => y.Key, W => W.Key == "DeptID" ? (W.Value == "1" ? "ECE" : "EEE") : W.Value));
</code>```

I have a key called DeptID in Dictionary. It has values like 1 or 2.
So, my requirement is if DeptID value is 1 then I need to replace 1 with ECE else replace with EEE.

I tried above code but not working.

Did I made any mistake?

Update 1:

I have a List<Dictionary<string, string>>() with few items. I want to modify values of DeptID key.

My requirement can be achieved using below code.

```<code>        foreach (var a in employeesList)
        {
           if (a.ContainsKey("DeptID")) {
              if (a.ContainsValue("1")) { a["DeptID"] = "ECE"; }
              else if (a.ContainsValue("2")) { a["DeptID"] = "ECE"; }
                }
            }
</code>```

I want to get same result with very fewer lines of code.

答:
What you are trying to do with LINQ is better left to imperative code, as others have mentioned in comments that LINQ queries data but is not for mutating it.

Furthermore, your original LINQ statement creates temporary dictionaries and discards them.

However, if you still want to go with a LINQ-based solution here's a way it can be done.

```<code>employeesList.Where(employee => employee.ContainsKey("DeptID") && (employee.ContainsValue("1") || employee.ContainsValue("2"))
    .Select(employee =>
    {
        employee["DeptID"] = employee.ContainsValue("1") ? "ECE" : "EEE";
        return employee;
    });
</code>```

Body:
I tried below code but somehow it is not working.

 employeesList.ForEach(x => x.ToDictionary(y => y.Key, W => W.Key == "DeptID" ? (W.Value == "1" ? "ECE" : "EEE") : W.Value));

I have a key called DeptID in Dictionary. It has values like 1 or 2.
So, my requirement is if DeptID value is 1 then I need to replace 1 with ECE else replace with EEE.

I tried above code but not working.

Did I made any mistake?

Update 1:

I have a List<Dictionary<string, string>>() with few items. I want to modify values of DeptID key.

My requirement can be achieved using below code.

        foreach (var a in employeesList)
        {
           if (a.ContainsKey("DeptID")) {
              if (a.ContainsValue("1")) { a["DeptID"] = "ECE"; }
              else if (a.ContainsValue("2")) { a["DeptID"] = "ECE"; }
                }
            }

I want to get same result with very fewer lines of code.

Body:
What you are trying to do with LINQ is better left to imperative code, as others have mentioned in comments that LINQ queries data but is not for mutating it.

Furthermore, your original LINQ statement creates temporary dictionaries and discards them.

However, if you still want to go with a LINQ-based solution here's a way it can be done.

employeesList.Where(employee => employee.ContainsKey("DeptID") && (employee.ContainsValue("1") || employee.ContainsValue("2"))
    .Select(employee =>
    {
        employee["DeptID"] = employee.ContainsValue("1") ? "ECE" : "EEE";
        return employee;
    });


答:
I'm making some assumptions but I think this is what you are trying to do:

```<code>employeesList.ForEach(x => x["DeptID"] = x["DeptID"] == "1" ? "ECE" : "EEE");
</code>```

See JSFiddle

However I personally do not think it is a good style to mutate the data using LINQ and other approaches should be considered. Depending on your design you might wish to consider using objects for your employees rather than dictionaries of key/value pairs.

Title: How to replace specific dictionary value based on key using LINQ

Body:
I'm making some assumptions but I think this is what you are trying to do:

employeesList.ForEach(x => x["DeptID"] = x["DeptID"] == "1" ? "ECE" : "EEE");

See JSFiddle

However I personally do not think it is a good style to mutate the data using LINQ and other approaches should be considered. Depending on your design you might wish to consider using objects for your employees rather than dictionaries of key/value pairs.


问:
Creating Instagram Bot using selenium library
So I am trying to create insta bot that opens up a specific hashtag in search bar and then navigates to it. I have been having a problem to navigate bot to search bar it always tells me that path is not able to be found, any ideas how can I make bot target search bar and send hashtag keys to it? here is my code:</p>

```<code>from selenium import webdriver
from time import sleep
from insta import username,password,hashtag

class InstaBot():
def __init__(self):
    self.driver = webdriver.Chrome()

def login(self):
    self.driver.get('https://www.instagram.com/')

    sleep(3)

    #loggin in to instagram with facebook
    fb_btn = self.driver.find_element_by_xpath('//*[@id="react-root"]/section/main/article/div[2]/div[1]/div/form/div[1]/button')
    fb_btn.click()

    #logging into acc
    email = self.driver.find_element_by_xpath('//*[@id="email"]')
    email.send_keys(username)

    pswd = self.driver.find_element_by_xpath('//*[@id="pass"]')
    pswd.send_keys(password)

    login_btn = self.driver.find_element_by_xpath('//*[@id="loginbutton"]')
    login_btn.click()
    sleep(4)

    self.driver.find_element_by_xpath("//button[contains(text(), 'Not Now')]")\
        .click()

    #navigating to search bar and sending hashtag into it
    hashtag = self.driver.find_element_by_xpath('//*[@id="react-root"]/section/nav/div[2]/div/div/div[3]/div/div[1]/a/svg')
    hashtag.send_keys(hashtag)
</code>```

答:
you can direct send the page,for ex:

```<code>https://www.instagram.com/explore/tags/{hastags}/
</code>```

so

when you run the program sometimes ıt can click different buttons ıdk why when ı made the same program ıt does that :) when you directly send the lınk for hastags ıt goes there even the program click different buttons

Body:
So I am trying to create insta bot that opens up a specific hashtag in search bar and then navigates to it. I have been having a problem to navigate bot to search bar it always tells me that path is not able to be found, any ideas how can I make bot target search bar and send hashtag keys to it? here is my code:

from selenium import webdriver
from time import sleep
from insta import username,password,hashtag

class InstaBot():
def __init__(self):
    self.driver = webdriver.Chrome()

def login(self):
    self.driver.get('https://www.instagram.com/')

    sleep(3)

    #loggin in to instagram with facebook
    fb_btn = self.driver.find_element_by_xpath('//*[@id="react-root"]/section/main/article/div[2]/div[1]/div/form/div[1]/button')
    fb_btn.click()

    #logging into acc
    email = self.driver.find_element_by_xpath('//*[@id="email"]')
    email.send_keys(username)

    pswd = self.driver.find_element_by_xpath('//*[@id="pass"]')
    pswd.send_keys(password)

    login_btn = self.driver.find_element_by_xpath('//*[@id="loginbutton"]')
    login_btn.click()
    sleep(4)

    self.driver.find_element_by_xpath("//button[contains(text(), 'Not Now')]")\
        .click()

    #navigating to search bar and sending hashtag into it
    hashtag = self.driver.find_element_by_xpath('//*[@id="react-root"]/section/nav/div[2]/div/div/div[3]/div/div[1]/a/svg')
    hashtag.send_keys(hashtag)

Body:
you can direct send the page,for ex:

https://www.instagram.com/explore/tags/{hastags}/

so

when you run the program sometimes ıt can click different buttons ıdk why when ı made the same program ıt does that :) when you directly send the lınk for hastags ıt goes there even the program click different buttons


问:
How to use pdfkit in AWS Lambda?
I'm using AWS Lambda to generate pdf file using a ninja2 template. I am trying to use pdfkit to convert my HTML into pdf. I realize pdfkit has an internal dependency - wkhtmltopdf which needs to be used as a binary or installed via a package manager. I am not sure how to make this work on AWS Lambda?

With my current template and python code using pdfkit, I am getting the following error -

```<code>{
  "errorMessage": "No wkhtmltopdf executable found: \"b''\"\nIf this file exists please check that this process can read it. Otherwise please install wkhtmltopdf - https://github.com/JazzCore/python-pdfkit/wiki/Installing-wkhtmltopdf",
  "errorType": "OSError",
.....
.....
}
</code>```

Any ideas on how can I make pdfkit work on lambda?

Any suggestions for wkhtmltopdf replacements?

Thanks

答: I've made a simple demo on using PDFKit using Serverless framework using layer. Checkout https://medium.com/@crespo.wang/create-pdf-using-pdfkit-on-serverless-aws-lambda-with-layer-721ca86724b2</p>

Title: How to use pdfkit in AWS Lambda?

Body:
I'm using AWS Lambda to generate pdf file using a ninja2 template. I am trying to use pdfkit to convert my HTML into pdf. I realize pdfkit has an internal dependency - wkhtmltopdf which needs to be used as a binary or installed via a package manager. I am not sure how to make this work on AWS Lambda?

With my current template and python code using pdfkit, I am getting the following error -

{
  "errorMessage": "No wkhtmltopdf executable found: \"b''\"\nIf this file exists please check that this process can read it. Otherwise please install wkhtmltopdf - https://github.com/JazzCore/python-pdfkit/wiki/Installing-wkhtmltopdf",
  "errorType": "OSError",
.....
.....
}

Any ideas on how can I make pdfkit work on lambda?

Any suggestions for wkhtmltopdf replacements?

Thanks


问:
STM32 IAR no ITM trace output unless printf is included in the code
I have a small project that I added my own custom debug functions to so I could have some extra functionality.  They have been working great, and use the following method to send the data:

```<code>while(*bp)
  ITM_SendChar(*bp++);
</code>```

I finally got around to switching over all the printf statements to use my own function and all the output just stopped.  A little playing around and I figured out as long as I have one single printf function compiled in, no matter where, ITM_SendChar works right out the gate.

It would seem there is some functionality compiled in when printf is used in the project that allows ITM_SendChar to work.

It is not a huge deal but I am fairly curious as to why this is.  Is there perhaps another way to initialize the ITM (Instrumentation Trace Macrocell) system without having to stick in a dummy printf?

答:
I came across the same problem and I tried everything with correct configuration of the ITM Registers. But I couldn't figure it out.

My solution to not use memory intense printf, is to use putchar:

```<code>while(*bp)
  putchar(*bp++);
</code>```

It even works, when I just have one putchar somewhere in the code which outputs one character and then output the other things with ITM_SendChar()

I assume the IAR automatically adds some configuration function as soon as the putchar function is included.

Body:
I have a small project that I added my own custom debug functions to so I could have some extra functionality.  They have been working great, and use the following method to send the data:

while(*bp)
  ITM_SendChar(*bp++);

I finally got around to switching over all the printf statements to use my own function and all the output just stopped.  A little playing around and I figured out as long as I have one single printf function compiled in, no matter where, ITM_SendChar works right out the gate.

It would seem there is some functionality compiled in when printf is used in the project that allows ITM_SendChar to work.

It is not a huge deal but I am fairly curious as to why this is.  Is there perhaps another way to initialize the ITM (Instrumentation Trace Macrocell) system without having to stick in a dummy printf?

Body:
I came across the same problem and I tried everything with correct configuration of the ITM Registers. But I couldn't figure it out.

My solution to not use memory intense printf, is to use putchar:

while(*bp)
  putchar(*bp++);

It even works, when I just have one putchar somewhere in the code which outputs one character and then output the other things with ITM_SendChar()

I assume the IAR automatically adds some configuration function as soon as the putchar function is included.


问:
Angular ngxs unit test dispatch doesn't work
I try to run unit tests for NGXS State but when I run dispatch with Action classs function it doesn't run

```<code>  @Action(GetProductsAction)
  loadProductPage(ctx: StateContext<ProductStateModel>, { page, size }: GetProductsAction) {
</code>```

this is my unit test code:

```<code>  it('should create an action and get not empty pageProduct', () => {
spyOn(httpClient, 'get').and.returnValue(of({totalElements: 2}));
store.dispatch(new GetProductsAction(1, 20))
store.select(state => state.product.pageProduct).subscribe((pageProduct: PageProduct) => {
  console.log(pageProduct)
  expect(pageProduct.totalElements).toEqual(2);
});
const x = store.selectSnapshot(state => state.product.pageProduct);
console.log('xxx '+ JSON.stringify(x));

expect(x).toEqual({})
</code>```

});

anyone have idea why it doesn't work?

答:
dispatch returns an Observable that should be subscribed to or awaited using toPromise method.

You retrieve the snapshot right after dispatch, so I think the action is simply not handled.

Body:
I try to run unit tests for NGXS State but when I run dispatch with Action classs function it doesn't run

  @Action(GetProductsAction)
  loadProductPage(ctx: StateContext<ProductStateModel>, { page, size }: GetProductsAction) {

this is my unit test code:

  it('should create an action and get not empty pageProduct', () => {
spyOn(httpClient, 'get').and.returnValue(of({totalElements: 2}));
store.dispatch(new GetProductsAction(1, 20))
store.select(state => state.product.pageProduct).subscribe((pageProduct: PageProduct) => {
  console.log(pageProduct)
  expect(pageProduct.totalElements).toEqual(2);
});
const x = store.selectSnapshot(state => state.product.pageProduct);
console.log('xxx '+ JSON.stringify(x));

expect(x).toEqual({})

});

anyone have idea why it doesn't work?


问:
Solr: List results by distance
I'd like to pass some parameters to Solr that should afflict the weighting of the results (I do not want to filter away results that do not match these criterias).

E.g. I'd like to have a language attribute, and if i pass the user's language to the search engine I'd like to have the results matching the language listed first. As a newbie to Solr I'd like to know if and how this is possible!

答: Yes, that's possible by using boost functions. See this FAQ entry or the description of boost functions for the DisMaxQueryPlugin (the dismax query parser is the default parser).</p>

Title: Solr: List results by distance


问:
Failed to edit Key Vault API connection
I am using Azure Key Vault connector in the logic apps and for deploying the logic apps using ARM templates.

In the ARM templates I have added the Microsoft.Web/connections resource to include Key Vault API connection.

The API Connection gets successfully deployed, but when I open it on the portal to Authorize it I get an error :- "Failed to edit Api connection "keyvault"".

The resource template of the key vault looks like below :-

```<code>{
  "type": "Microsoft.Web/connections",
  "apiVersion": "2016-06-01",
  "name": "[parameters('connections_keyvault_name')]",
  "location": "[parameters('location')]",
  "properties": {
    "api": {
      "id": "[concat('/subscriptions/',subscription().subscriptionId,'/providers/Microsoft.Web/locations/', parameters('location'), '/managedApis/', parameters('connections_keyvault_name'))]"
    },
    "displayName": "",
    "customParameterValues": {}
  }
}
</code>```

The status of the API connection after deployment always shows "Error". However, I am using office365 API connection as well which works fine after deployment i.e. when I authorize it, it allows me to save it.

Can anyone please help me with this issue? This is blocking us to move this logic app to production.

Thanks,

Archana Kolte

答:
You have to add the key vault name to connect to by setting the vaultName property under properties.paramaterValues.

Also, the end of the properties.api.id is the same for all Key Vault API Connections and should be /managedApis/keyvault.

Your ARM template would look something like this

```
{
  "type": "Microsoft.Web/connections",
  "apiVersion": "2016-06-01",
  "name": "[parameters('connections_keyvault_name')]",
  "location": "[parameters('location')]",
  "properties": {
    "api": {
      "id": "[concat('/subscriptions/',subscription().subscriptionId,'/providers/Microsoft.Web/locations/', parameters('location'), <b>'/managedApis/keyvault'</b>)]"
    },
    "displayName": "",
    <b>"parameterValues": {
      "vaultName": "<name-of-your-key-vault>"
    }</b>
  }
}
```

Title: Failed to edit Key Vault API connection

Body:
I am using Azure Key Vault connector in the logic apps and for deploying the logic apps using ARM templates.

In the ARM templates I have added the Microsoft.Web/connections resource to include Key Vault API connection.

The API Connection gets successfully deployed, but when I open it on the portal to Authorize it I get an error :- "Failed to edit Api connection "keyvault"".

The resource template of the key vault looks like below :-

{
  "type": "Microsoft.Web/connections",
  "apiVersion": "2016-06-01",
  "name": "[parameters('connections_keyvault_name')]",
  "location": "[parameters('location')]",
  "properties": {
    "api": {
      "id": "[concat('/subscriptions/',subscription().subscriptionId,'/providers/Microsoft.Web/locations/', parameters('location'), '/managedApis/', parameters('connections_keyvault_name'))]"
    },
    "displayName": "",
    "customParameterValues": {}
  }
}

The status of the API connection after deployment always shows "Error". However, I am using office365 API connection as well which works fine after deployment i.e. when I authorize it, it allows me to save it.

Can anyone please help me with this issue? This is blocking us to move this logic app to production.

Thanks,

Archana Kolte

Body:
You have to add the key vault name to connect to by setting the vaultName property under properties.paramaterValues.

Also, the end of the properties.api.id is the same for all Key Vault API Connections and should be /managedApis/keyvault.

Your ARM template would look something like this

{
  "type": "Microsoft.Web/connections",
  "apiVersion": "2016-06-01",
  "name": "[parameters('connections_keyvault_name')]",
  "location": "[parameters('location')]",
  "properties": {
    "api": {
      "id": "[concat('/subscriptions/',subscription().subscriptionId,'/providers/Microsoft.Web/locations/', parameters('location'), '/managedApis/keyvault')]"
    },
    "displayName": "",
    "parameterValues": {
      "vaultName": "<name-of-your-key-vault>"
    }
  }
}


问:
Nodejs - Calling a method from other file properly
I'm new to this domain and want to fix this error, I have two classes, 'Ticket.js' where I put my routes and 'support.js' where my websockets methods are declared,
I just want to use the method delared in 2nd file in 1st file,
here's the strucutre of code of both files :

```<code>class SupportTicketRouter  {
.
.
.
    sendMessagesSocket = (req, res, next) => {
        const SUPPORT_SOCKET = require('app/routes/socket/support');
        const MESSAGES       = req.api.support.messages;

        SUPPORT_SOCKET.sendModifiedTicket(MESSAGES);

        next();
    }
}

</code>```

in the other file :

```<code>const SUPPORT_SOCKET = (MQTT_CLIENT, REDIS_CLIENT, IO_SERVER, IO_CLIENT) => {

   // EntryPoints

   // Exit points
   SUPPORT_SOCKET.sendModifiedTicket = (data) => {
       IO_SERVER.in(data[0]._id).emit('OneTicketReload', data);
       Logger.info('%s%s', 'Ticket sent to room ', data[0]._id);
   };

</code>```

so basically I just want to call sendModifiedTicket from other file.

Thanks in advance

答:
Controller.js

```<code>export class Controller {
   constructor(){
        this.method  = this.method.bind(this)
   }

    method (req, res) {....}
}
</code>```

OtherFile.js

function otherMethod () {
     const controller = new Controller();
     controller.method()
}
```

Body:
I'm new to this domain and want to fix this error, I have two classes, 'Ticket.js' where I put my routes and 'support.js' where my websockets methods are declared,
I just want to use the method delared in 2nd file in 1st file,
here's the strucutre of code of both files :

class SupportTicketRouter  {
.
.
.
    sendMessagesSocket = (req, res, next) => {
        const SUPPORT_SOCKET = require('app/routes/socket/support');
        const MESSAGES       = req.api.support.messages;

        SUPPORT_SOCKET.sendModifiedTicket(MESSAGES);

        next();
    }
}

in the other file :

const SUPPORT_SOCKET = (MQTT_CLIENT, REDIS_CLIENT, IO_SERVER, IO_CLIENT) => {

   // EntryPoints

   // Exit points
   SUPPORT_SOCKET.sendModifiedTicket = (data) => {
       IO_SERVER.in(data[0]._id).emit('OneTicketReload', data);
       Logger.info('%s%s', 'Ticket sent to room ', data[0]._id);
   };

so basically I just want to call sendModifiedTicket from other file.

Thanks in advance

Body:
Controller.js

export class Controller {
   constructor(){
        this.method  = this.method.bind(this)
   }

    method (req, res) {....}
}

OtherFile.js

function otherMethod () {
     const controller = new Controller();
     controller.method()
}


问:
Could not find matching close tag for "<%"
I am trying to access variables passed from the server to the client with ejs

My server file:

```<code>router.get('/', function (req, res, next) {
    res.render('chat', {user: req.user, message: null});
});

</code>```

My client file:

```<code><!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" const="text/html;charset=UTF-8"/>
    <link href="http://fonts.googleapis.com/css?family=Comfortaa" rel="stylesheet" type="text/css">
    <link rel="stylesheet" type="text/css" href="style.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.4/socket.io.js"></script>
    <title>Simple Chat App</title>
</head>

<body>
<header>
    <h1>Super Chat</h1>
</header>

<section>
    <div id="change_username">
        <input id="username" type="text"/>
        <button id="send_username" type="button">Change username</button>
    </div>
</section>

<section id="chatroom">
    <section id="feedback"></section>
</section>

<section id="input_zone">
    <input id="message" class="vertical-align" type="text"/>
    <button id="send_message" class="vertical-align" type="button">Send</button>
</section>

<script src="http://code.jquery.com/jquery-latest.min.js"></script>

<script type="text/javascript">
    <% var user = <% user %> %>
    console.log(user);
</script>
<script src="chat.js"></script>
</body>
</html>

</code>```

I get an error:

```<code>Could not find matching close tag for "<%".

</code>```

How do I fix this?

答:
```<code><% var user = <% user %> %>
</code>```

You can't nest <% %> blocks. You are either inside EJS mode or outside it. You can't go into Extra Deep EJS Mode.

Aside, you also can't just output a variable into client-side JS. You need to generate JavaScript source code from the variable. JSON.stringify is a good way to generate object, array and string literals from objects, arrays and strings.

```<code><script>
    const user = <%- JSON.stringify(user); %>
    console.log(user);
</script>
</code>```

Note that use of <%- to output without escaping for HTML.

Body:
I am trying to access variables passed from the server to the client with ejs

My server file:

router.get('/', function (req, res, next) {
    res.render('chat', {user: req.user, message: null});
});

My client file:

<!DOCTYPE html>

    <meta http-equiv="Content-Type" const="text/html;charset=UTF-8"/>
    <link href="http://fonts.googleapis.com/css?family=Comfortaa" rel="stylesheet" type="text/css">
    <link rel="stylesheet" type="text/css" href="style.css">

    <title>Simple Chat App</title>

Super Chat

        <input id="username" type="text"/>
        <button id="send_username" type="button">Change username</button>

    <input id="message" class="vertical-align" type="text"/>
    <button id="send_message" class="vertical-align" type="button">Send</button>

I get an error:

Could not find matching close tag for "<%".

How do I fix this?

Body:
<% var user = <% user %> %>

You can't nest <% %> blocks. You are either inside EJS mode or outside it. You can't go into Extra Deep EJS Mode.

Aside, you also can't just output a variable into client-side JS. You need to generate JavaScript source code from the variable. JSON.stringify is a good way to generate object, array and string literals from objects, arrays and strings.

<script>
    const user = <%- JSON.stringify(user); %>
    console.log(user);
</script>

Note that use of <%- to output without escaping for HTML.


问:
How to get distinct values from MongoDB?
I am new in MongoDB and troubling to get distinct values from there.

This is documents in collection, where I want to distinct by "CustomerAccountNo" (this is duplicate values = 165)

```<code>   {
        "_id": "5e3eaf3ef5aab73568bd8494",
        "CustomerAccountNo": "123",
        "Customer": "Lucy Thom"
    },
    {
        "_id": "5e3eaf40f5aab73568bd8495",
        "CustomerAccountNo": "325",
        "Customer": "Nick Granger"
    },
    {
        "_id": "5e3eaf42f5aab73568bd8496",
        "CustomerAccountNo": "658",
        "Customer": "Tommy Tee"
    },
    {
        "_id": "5e3eaf44f5aab73568bd8497",
        "CustomerAccountNo": "6513",
        "Customer": "Carlos Nolasco"
    },
    {
        "_id": "5e3eaf49f5aab73568bd8498",
        "CustomerAccountNo": "165",
        "Customer": "Hungarian Pastry shop"
    },
    {
        "_id": "5e4660e9f57ea925a42b4ba2",
        "CustomerAccountNo": "165",
        "Customer": "Hungarian Pastry shop"
    }
</code>```

And want the output like:

```<code>    {
        "_id": "5e3eaf3ef5aab73568bd8494",
        "CustomerAccountNo": "123",
        "Customer": "Lucy Thom"
    },
    {
        "_id": "5e3eaf40f5aab73568bd8495",
        "CustomerAccountNo": "325",
        "Customer": "Nick Granger"
    },
    {
        "_id": "5e3eaf42f5aab73568bd8496",
        "CustomerAccountNo": "658",
        "Customer": "Tommy Tee"
    },
    {
        "_id": "5e3eaf44f5aab73568bd8497",
        "CustomerAccountNo": "6513",
        "Customer": "Carlos Nolasco"
    },
    {
        "_id": "5e3eaf49f5aab73568bd8498",
        "CustomerAccountNo": "165",
        "Customer": "Hungarian Pastry shop"
    }
</code>```

And i am trying the below code to get the above response,

```<code>collectionName.distinct("CustomerAccountNo")
</code>```

or

```<code>collectionName.aggregate([
  { $group: { _id: { CustomerAccountNo: "$CustomerAccountNo", Customer: "$Customer" } } }
]);
</code>```

but both the above code not archive the correct response as I want, and I don't know what I am doing wrong.

答:
This aggregation will get the required result:</p>

```<code>db.test.aggregate( [
  { $group: { _id: "$CustomerAccountNo", doc: { $first: "$$ROOT" } } },
  { $replaceRoot: { newRoot: "$doc" } }
] ).pretty()
</code>```

Body:
I am new in MongoDB and troubling to get distinct values from there.

This is documents in collection, where I want to distinct by "CustomerAccountNo" (this is duplicate values = 165)

   {
        "_id": "5e3eaf3ef5aab73568bd8494",
        "CustomerAccountNo": "123",
        "Customer": "Lucy Thom"
    },
    {
        "_id": "5e3eaf40f5aab73568bd8495",
        "CustomerAccountNo": "325",
        "Customer": "Nick Granger"
    },
    {
        "_id": "5e3eaf42f5aab73568bd8496",
        "CustomerAccountNo": "658",
        "Customer": "Tommy Tee"
    },
    {
        "_id": "5e3eaf44f5aab73568bd8497",
        "CustomerAccountNo": "6513",
        "Customer": "Carlos Nolasco"
    },
    {
        "_id": "5e3eaf49f5aab73568bd8498",
        "CustomerAccountNo": "165",
        "Customer": "Hungarian Pastry shop"
    },
    {
        "_id": "5e4660e9f57ea925a42b4ba2",
        "CustomerAccountNo": "165",
        "Customer": "Hungarian Pastry shop"
    }

And want the output like:

    {
        "_id": "5e3eaf3ef5aab73568bd8494",
        "CustomerAccountNo": "123",
        "Customer": "Lucy Thom"
    },
    {
        "_id": "5e3eaf40f5aab73568bd8495",
        "CustomerAccountNo": "325",
        "Customer": "Nick Granger"
    },
    {
        "_id": "5e3eaf42f5aab73568bd8496",
        "CustomerAccountNo": "658",
        "Customer": "Tommy Tee"
    },
    {
        "_id": "5e3eaf44f5aab73568bd8497",
        "CustomerAccountNo": "6513",
        "Customer": "Carlos Nolasco"
    },
    {
        "_id": "5e3eaf49f5aab73568bd8498",
        "CustomerAccountNo": "165",
        "Customer": "Hungarian Pastry shop"
    }

And i am trying the below code to get the above response,

collectionName.distinct("CustomerAccountNo")

or

collectionName.aggregate([
  { $group: { _id: { CustomerAccountNo: "$CustomerAccountNo", Customer: "$Customer" } } }
]);

but both the above code not archive the correct response as I want, and I don't know what I am doing wrong.

Body:
This aggregation will get the required result:

db.test.aggregate( [
  { $group: { _id: "$CustomerAccountNo", doc: { $first: "$$ROOT" } } },
  { $replaceRoot: { newRoot: "$doc" } }
] ).pretty()


问:
Why store whole records in audit tables?
I worked in several companies and in each of them audit tables have been storing full snapshots of records for every change.

To my understanding it's enough to store only changed columns to recreate record in any given point of time. It will obviously reduce storage space. Moreover I suppose it would improve performance as we would need to write much smaller amount of data.

As I've seen it in across different databases and frameworks, I'm not putting any specific tag here.

I'd gladly understand reasoning behind this approach.

答:
Here are some important reasons.

First, storage is becoming cheaper and cheaper.  So there is little financial benefit in reducing the number of records or their size.

Second, the "context" around a change can be very helpful.  Reconstructing records as they look when the change occurs can be tricky.

Third, the logic to detect changes is tricker than it seems.  This is particularly true when you have NULL values.  If there is a bug in the code, then you lose the archive.  Entire records are less error-prone.

Fourth, remember that (2) and (3) need to be implemented for every table being archived, further introducing the possibility of error.

I might summarize this as saying that storing the entire record uses fewer lines of code.  Fewer lines of code are easier to maintain and less error-prone.  And those savings outweigh the benefits of reducing the size of the archive.


答:
it says that it cannot find closing tag for your ejs template.
you don't need the surrounding ejs template notation in script.

```<code><script type="text/javascript">
var user = '<%= user %>'
console.log(user);
</script>
</code>```

Try this.
GOOD LUCK. :)

Title: Could not find matching close tag for "<%"

Body:
it says that it cannot find closing tag for your ejs template.
you don't need the surrounding ejs template notation in script.

<script type="text/javascript">
var user = '<%= user %>'
console.log(user);
</script>

Try this.
GOOD LUCK. :)


问:
The Network Adapter could not establish the connection Vendor code 17002 on SQL developer all versions
I get the above error when connecting to a new schema.
Note that when my VPN is connected initially all the connections(C1,C2,C3...) work fine. I then start working on one connection(C1) and after say 2 hours if i try to connect to C2 I have this error.

I have to disconnect and reconnect to the VPN every time, which is very annoying when you have to do it at least 15-20 times in a day.
Any idea why I could have this issue?

答:
One reason could be the services OracleServiceORCL and OracleOra...Listener have been off, Check the service running on your computer and turn this two services on, then the problem might be solved.
To avoid this from happening again, try to change the property of the service to automatically run. </p>


问:
How can I recursively print a File Array?
I would like to know how to recursively print a File[]. I have made a program but it seems that the program is going out of bounds and I don't know how to fix it. Can someone please give me a few pointers or hints on how to solve this problem? Thanks.

```<code>import java.io.*;

public class RecursiveDir {

static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

public static void main(String[]args) throws IOException {
    System.out.print("Please enter a directory name: ");
    File f = new File(br.readLine());

    FileFilter filter = new FileFilter() {

        public boolean accept(File f) {
            if(f.isDirectory()) {
                return true;
            }
            return false;
        }

    };

    File[] list = f.listFiles(filter);
    System.out.println(returnDir(list,list.length));
}

public static File returnDir(File[] file,int counter) {
    File f = file[counter];
    if(counter == 0) {
        return file[0];
    }else {
        return f = returnDir(file,counter--);
    }
}
}
</code>```

EDIT: I followed the comments below and changed return f = returnDir(file,counter--); to
return f = returnDir(file,--counter); and also changed returnDir(list,list.length); to
returnDir(list,list.length-1);, my code runs fine but now nothing is printing.

答:
Your initial call to returnDir should be

```<code>returnDir(list,list.length-1);
</code>```

Paul

Body:
I would like to know how to recursively print a File[]. I have made a program but it seems that the program is going out of bounds and I don't know how to fix it. Can someone please give me a few pointers or hints on how to solve this problem? Thanks.

import java.io.*;

public class RecursiveDir {

static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

public static void main(String[]args) throws IOException {
    System.out.print("Please enter a directory name: ");
    File f = new File(br.readLine());

    FileFilter filter = new FileFilter() {

        public boolean accept(File f) {
            if(f.isDirectory()) {
                return true;
            }
            return false;
        }

    };

    File[] list = f.listFiles(filter);
    System.out.println(returnDir(list,list.length));
}

public static File returnDir(File[] file,int counter) {
    File f = file[counter];
    if(counter == 0) {
        return file[0];
    }else {
        return f = returnDir(file,counter--);
    }
}
}

EDIT: I followed the comments below and changed return f = returnDir(file,counter--); to
return f = returnDir(file,--counter); and also changed returnDir(list,list.length); to
returnDir(list,list.length-1);, my code runs fine but now nothing is printing.

Body:
Your initial call to returnDir should be

returnDir(list,list.length-1);

Paul


答:
Just think this way:

[(1, 1024),(1, 1024),(1, 1024)...(1, 1024)]

to select a single element here you will need 3 things: position in the list, the n in (n, 1024) and k in (1, k). This is a 3 dimensional data structure.

use np.stack  or convert your list with np.array and  np.reshape(len(list),1024). This way you`ll have a unique array of shape (n, 1024).

Title: Python: array of 2 dim shape (1,1024) is read as 3 dim array

Body:
In python, I have a list a of arrays, each of shape (1, 1024) and a list b of ints {1,0,0,1…]
Now I want to train a basic SVM with that.
I always receive this error message:

ValueError: Found array with dim 3. Estimator expected <= 2.

But doesnt the shape tell me, that I have a 2 Dim shape?
There is probably something wrong with my array but I don`t understand, what.
I am glad for any help.

clf = svm.SVC(kernel='linear')
clf.fit(lista, listb)

First 10 items of the array:

[array([[-0.00381735, -0.02317988, -0.06664753, ..., -0.03608917,
         0.06382023,  0.02493868]], dtype=float32), array([[-0.00381735, -0.02317988, -0.06664753, ..., -0.00363029,
         0.04429551,  0.04517733]], dtype=float32), array([[-0.00381735, -0.02317988, -0.06664753, ..., -0.01848865,
         0.03857033, -0.04184096]], dtype=float32), array([[-0.00381735, -0.02317988, -0.06664753, ..., -0.00812042,
        -0.01121382, -0.07293765]], dtype=float32), array([[-0.00381735, -0.02317988, -0.06664753, ...,  0.0026521 ,
        -0.00911874,  0.02558753]], dtype=float32), array([[-0.00381735, -0.02317988, -0.06664753, ...,  0.0128456 ,
        -0.00659914, -0.05465406]], dtype=float32), array([[-0.00381735, -0.02317988, -0.06664753, ..., -0.00801555,
        -0.06554729, -0.04112517]], dtype=float32), array([[-0.00381735, -0.02317988, -0.06664753, ...,  0.0015485 ,
        -0.03974668,  0.03871798]], dtype=float32), array([[-0.00381735, -0.02317988, -0.06664753, ...,  0.03571296,
         0.0097717 , -0.02939025]], dtype=float32), array([[-0.00381735, -0.02317988, -0.06664753, ..., -0.00178309,
        -0.00751928, -0.00501447]], dtype=float32)]


问:
Angular ng-click : Only want user to click once not multiple times on a rating system
Objective : Only want user to click once not multiple times on a rating system

```<code><div class="votingButton" ng-click="upVoteOrder(order)">
                            </div>
</code>```

is this easily achievable on the html or the controller ?

答:
              <form #ref="ngForm" (ngSubmit)="addfirst(ref3.value)">

GENERAL

                    EMP NUMBER
                    <input type="number" class="form-control round3 " id="empno" placeholder=" Emp Number"
                       name="empnober" ngModel #ref1="ngModel" required>

 *emp num field is mandatory

                     FIRST NAME
                    <input type="text" class="form-control round3 " id="firstname" placeholder="FIRST NAME" name="firstname"
                       ngModel #ref2="ngModel" required>

 *firstname field is mandatory

                    LAST NAME
                    <input type="text" class="form-control round3 " id="lastname" placeholder="LAST NAME " name="lastname" ngModel
                       #ref3="ngModel" required>

 *last name field is mandatory

                   MIDDLE NAME
                  <input type="text" class="form-control round3 " id="middlename" placeholder="MIDDLE NAME " name="middlename" ngModel
                     #ref4="ngModel" required>

 *middle name field is mandatory

                 ADDRESS
                <input type="text" class="form-control round3 " id="address" placeholder="ADDRESS" name="address" ngModel
                   #ref5="ngModel" required>

 *address  field is mandatory

               ADDRESS 2
              <input type="text" class="form-control round3 " id="address2" placeholder="ADDRESS 2" name="address2" ngModel
                 #ref6="ngModel" required>

 *address2  field is mandatory

             POST CODE
            <input type="number" class="form-control round3 " id="postcode" placeholder=" POSTCODE " name="postcode" ngModel
               #ref7="ngModel" required>

 *postcode  field is mandatory

            CITY
          <input type="text" class="form-control round3 " id="city" placeholder="CITY " name="city" ngModel
             #ref8="ngModel" required>

 *city field is mandatory

         PHONE NUMBER
        <input type="number" class="form-control round3 " id="phnumber" placeholder="PHONE NUMBER " name="phnumber" ngModel
           #ref9="ngModel" required>

 *phone number field is mandatory

       MOBILE NUMBER
      <input type="number" class="form-control round3 " id="mblnumber" placeholder="MOBILE NUMBER " name="mblnumber" ngModel
         #ref10="ngModel" required>

 *mobilenumber field is mandatory

     REPORTING TO
    <input type="text" class="form-control round3 " id="reportingto" placeholder=" REPORTING TO " name="reportingto" ngModel
       #ref11="ngModel" required>

 *reporting to field is mandatory

   REPORTING NAME
  <input type="text" class="form-control round3 " id="reportingname" placeholder="REPORTING NAME" name="reportingname" ngModel
     #ref12="ngModel" required>

 *reporting name field is mandatory

     GENDER
<input type="radio" value="male" name="gender" [(ngModel)]="gender"  #ref13="ngModel" required #genderControl="ngModel"> Male
<input type="radio" value="female" name="gender" [(ngModel)]="gender"  #ref13="ngModel" required> Female
<input type="radio" value="others" name="gender" [(ngModel)]="gender"  #ref13="ngModel" required> others

 *select gender mandatory

   LOCATION CODE
  <input type="text" class="form-control round3 " id="lctncode" placeholder="LOCATION CODE" name="lctncode" ngModel
     #ref14="ngModel" required>

 *location code field is mandatory

    <button class="btn btn-success" type="button" (click)="next()">Next</button>

              </form>

<form #ref1="ngForm">

COMMUNICATION

     PHONE NUMBER
    <input type="number" class="form-control round3 " id="phnumber" placeholder="PHONE NUMBER " name="phnumber" ngModel
       #ref15="ngModel" required>

 *phone number field is mandatory

   MOBILE NUMBER
  <input type="number" class="form-control round3 " id="mblnumber" placeholder="MOBILE NUMBER " name="mblnumber" ngModel
     #ref16="ngModel" required>

 *mobilenumber field is mandatory

     E-MAIL
    <input type="email" class="form-control round3 " id="email" placeholder="E-MAIL ADDRESS" name="email" ngModel
       #ref17="ngModel" required>

 *email field is mandatory

     COMPANY E-MAIL
    <input type="email" class="form-control round3 " id="cemail" placeholder="COMPANY E-MAIL ADDRESS" name="cemail" ngModel
       #ref18="ngModel" required>

 *company email field is mandatory

    <button class="btn btn-success" type="button" (click)="secondNext()">Next</button>

</form>

<form #ref2="ngForm">

ADMINISTRATION

        DESIGNATION
        <input type="text" class="form-control round3 " id="designation" placeholder="DESIGNATION" name="designation" ngModel
           #ref19="ngModel" required>

 *designation field is mandatory

        QUALIFICATION
        <input type="text" class="form-control round3 " id="qualification" placeholder="QUALIFICATION" name="qualification" ngModel
           #ref20="ngModel" required>

 *qualification field is mandatory

        HEIGHT
        <input type="number" class="form-control round3 " id="height" placeholder="HEIGHT" name="height" ngModel
           #ref21="ngModel" required>

 *height field is mandatory

         WEIGHT
        <input type="number" class="form-control round3 " id="weight" placeholder="WEIGHT" name="weight" ngModel
           #ref22="ngModel" required>

 *weight field is mandatory

         EXPERIENCE
        <input type="number" class="form-control round3 " id="experience" placeholder="EXPERIENCE" name="experience" ngModel
           #ref23="ngModel" required>

 *experience field is mandatory

        <button class="btn btn-success" type="button" (click)="thirdNext()">Next</button>

</form>

<form #ref2="ngForm">

PERSONAL

     DATE OF BIRTH
    <input type="date" class="form-control round3 " id="dob" placeholder="DATE OF BIRTH" name="dob" ngModel
       #ref24="ngModel" required>

 *date of birth field is mandatory

     FATHER/HUSBAND NAME
    <input type="text" class="form-control round3 " id="fhname" placeholder="FATHER/HUSBAND NAME" name="fhname" ngModel
       #ref25="ngModel" required>

 *father/husband  field is mandatory

     CURRENT AGE (YEARS)
    <input type="number" class="form-control round3 " id="cage" placeholder="CURRENT AGE (YEARS)" name="cage" ngModel
       #ref26="ngModel" required>

 *current age (years) field is mandatory

     CURRENT AGE (MONTHS)
    <input type="number" class="form-control round3 " id="cagem" placeholder="CURRENT AGE (MONTHS)" name="cagem" ngModel
       #ref27="ngModel" required>

 *current age (months) field is mandatory

     BLOOD GROUP
    <input type="text" class="form-control round3 " id="bloodgrp" placeholder="BLOOD GROUP" name="bloodgrp" ngModel
       #ref28="ngModel" required>

 *bloodgroup field is mandatory

     NATIONALITY
    <input type="text" class="form-control round3 " id="nationality" placeholder="NATIONALITY" name="nationality" ngModel
       #ref29="ngModel" required>

 *nationality field is mandatory

     PRESENT ADDRESS
    <input type="text" class="form-control round3 " id="paddress" placeholder="PRESENT ADDRESS" name="paddress" ngModel
       #ref30="ngModel" required>

 *presentaddress  field is mandatory

  PRESENT ADDRESS 2
  <input type="text" class="form-control round3 " id="paddress2" placeholder="PRESENT ADDRESS 2" name="paddress2" ngModel
     #ref31="ngModel" required>

 *presentaddress2  field is mandatory

    PRESENT CITY
    <input type="text" class="form-control round3 " id="pcity" placeholder="PRESENT CITY" name="pcity" ngModel
       #ref32="ngModel" required>

 *presentcity  field is mandatory

      PRESENT POST CODE
      <input type="number" class="form-control round3 " id="pccode" placeholder="PRESENT CITY CODE" name="pccode" ngModel
         #ref33="ngModel" required>

 *presentcitycode  field is mandatory

        PRESENT COUNTRY
        <input type="text" class="form-control round3 " id="pcountry" placeholder="PRESENT COUNTRY" name="pcountry" ngModel
           #ref34="ngModel" required>

 *presentcountry  field is mandatory

          PRESENT PHONE NUMBER
          <input type="number" class="form-control round3 " id="pphnno" placeholder="PRESENT PHONE NUMBER" name="pphnno" ngModel
             #ref35="ngModel" required>

 *presentphonenumber  field is mandatory

            ADDHAAR NUMBER
            <input type="number" class="form-control round3 " id="aadhaar" placeholder="ADDHAAR NUMBER" name="aadhaar" ngModel
               #ref36="ngModel" required>

 *aadhaar  field is mandatory

               PAN NUMBER
              <input type="text" class="form-control round3 " id="pannumber" placeholder=" PAN NUMBER " name="pannumber" ngModel
                 #ref41="ngModel" required>

 *pan number  field is mandatory

              <button class="btn btn-success" type="button" (click)="fourthNext()">Next</button>

</form>
<form #ref3="ngForm">

 PAY METHOD

       BANK NAME
      <input type="text" class="form-control round3 " id="bankname" placeholder="BANK NAME" name="bankname" ngModel
         #ref37="ngModel" required>

 *bankname  field is mandatory

     BANK IFSC CODE
    <input type="text" class="form-control round3 " id="bankifsccode" placeholder="BANK IFSC CODE" name="bankifsccode" ngModel
       #ref38="ngModel" required>

 *bankifsccode  field is mandatory

     ACCOUNT TYPE
    <input type="text" class="form-control round3 " id="accounttype" placeholder="ACCOUNT TYPE" name="accounttype" ngModel
       #ref39="ngModel" required>

 *accounttype  field is mandatory

     ACCOUNT NUMBER
    <input type="text" class="form-control round3 " id="accountnumber" placeholder=" ACCOUNT NUMBER " name="accountnumber" ngModel
       #ref40="ngModel" required>

 *accountnumber  field is mandatory

    <button class="btn btn-success" type="submit">submit</button>

 </form>

```

Body:
Objective : Only want user to click once not multiple times on a rating system

is this easily achievable on the html or the controller ?

Body:
    <div class="container ">

        <div class="row">

           <div class="col-md-3"></div>
           <div class="col-md-6">

              <form #ref="ngForm" (ngSubmit)="addfirst(ref3.value)">

<!-- GENERAL -->
<div *ngIf="!b"> <h3 class="text-primary">GENERAL</h3>
                 <div class="form-group">
                    <label>EMP NUMBER</label>
                    <input type="number" class="form-control round3 " id="empno" placeholder=" Emp Number"
                       name="empnober" ngModel #ref1="ngModel" required>
                    <label *ngIf="ref1.invalid && ref1.touched ">
                       <div class="text-danger"> *emp num field is mandatory </div>
                    </label>
                 </div>
                 <div class="form-group">
                    <label> FIRST NAME</label>
                    <input type="text" class="form-control round3 " id="firstname" placeholder="FIRST NAME" name="firstname"
                       ngModel #ref2="ngModel" required>
                    <label *ngIf="ref2.invalid && (ref2.dirty || ref2.touched )">
                       <div class="text-danger"> *firstname field is mandatory </div>
                    </label>
                 </div>
                 <div class="form-group">
                 <div class="LAST NAME">
                    <label>LAST NAME  </label>
                    <input type="text" class="form-control round3 " id="lastname" placeholder="LAST NAME " name="lastname" ngModel
                       #ref3="ngModel" required>
                    <label *ngIf="ref3.invalid && (ref3.dirty || ref3.touched )">
                       <div class="text-danger"> *last name field is mandatory </div>
                    </label>
                 </div>
                 </div>

                 <div class="form-group">
                  <label> MIDDLE NAME </label>
                  <input type="text" class="form-control round3 " id="middlename" placeholder="MIDDLE NAME " name="middlename" ngModel
                     #ref4="ngModel" required>
                  <label *ngIf="ref4.invalid && (ref4.dirty || ref4.touched )">
                     <div class="text-danger"> *middle name field is mandatory </div>
                  </label>
               </div>

               <div class="form-group">
                <label> ADDRESS </label>
                <input type="text" class="form-control round3 " id="address" placeholder="ADDRESS" name="address" ngModel
                   #ref5="ngModel" required>
                <label *ngIf="ref5.invalid && (ref5.dirty || ref5.touched )">
                   <div class="text-danger"> *address  field is mandatory </div>
                </label>
             </div>

             <div class="form-group">
              <label> ADDRESS 2 </label>
              <input type="text" class="form-control round3 " id="address2" placeholder="ADDRESS 2" name="address2" ngModel
                 #ref6="ngModel" required>
              <label *ngIf="ref6.invalid && (ref6.dirty || ref6.touched )">
                 <div class="text-danger"> *address2  field is mandatory </div>
              </label>
           </div>

<!-- <div class="text-right">
<a href="#" class="next">Next &raquo;</a>
</div> -->

<div >

           <div class="form-group">
            <label> POST CODE </label>
            <input type="number" class="form-control round3 " id="postcode" placeholder=" POSTCODE " name="postcode" ngModel
               #ref7="ngModel" required>
            <label *ngIf="ref7.invalid && (ref7.dirty || ref7.touched )">
               <div class="text-danger"> *postcode  field is mandatory </div>
            </label>
         </div>

         <div class="form-group">
          <label>  CITY </label>
          <input type="text" class="form-control round3 " id="city" placeholder="CITY " name="city" ngModel
             #ref8="ngModel" required>
          <label *ngIf="ref8.invalid && (ref8.dirty || ref8.touched )">
             <div class="text-danger"> *city field is mandatory </div>
          </label>
       </div>

       <div class="form-group">
        <label> PHONE NUMBER  </label>
        <input type="number" class="form-control round3 " id="phnumber" placeholder="PHONE NUMBER " name="phnumber" ngModel
           #ref9="ngModel" required>
        <label *ngIf="ref9.invalid && (ref9.dirty || ref9.touched )">
           <div class="text-danger"> *phone number field is mandatory </div>
        </label>
     </div>

     <div class="form-group">
      <label> MOBILE NUMBER  </label>
      <input type="number" class="form-control round3 " id="mblnumber" placeholder="MOBILE NUMBER " name="mblnumber" ngModel
         #ref10="ngModel" required>
      <label *ngIf="ref10.invalid && (ref10.dirty || ref10.touched )">
         <div class="text-danger"> *mobilenumber field is mandatory </div>
      </label>
   </div>

   <div class="form-group">
    <label> REPORTING TO </label>
    <input type="text" class="form-control round3 " id="reportingto" placeholder=" REPORTING TO " name="reportingto" ngModel
       #ref11="ngModel" required>
    <label *ngIf="ref11.invalid && (ref11.dirty || ref11.touched )">
       <div class="text-danger"> *reporting to field is mandatory </div>
    </label>
 </div>

<div class="form-group">
  <label> REPORTING NAME </label>
  <input type="text" class="form-control round3 " id="reportingname" placeholder="REPORTING NAME" name="reportingname" ngModel
     #ref12="ngModel" required>
  <label *ngIf="ref12.invalid && (ref12.dirty || ref12.touched )">
     <div class="text-danger"> *reporting name field is mandatory </div>
  </label>
</div>

<div class="form-group">
    <label> GENDER </label>&nbsp;&nbsp;&nbsp;&nbsp;
<input type="radio" value="male" name="gender" [(ngModel)]="gender"  #ref13="ngModel" required #genderControl="ngModel"> Male &nbsp;
<input type="radio" value="female" name="gender" [(ngModel)]="gender"  #ref13="ngModel" required> Female  &nbsp;
<input type="radio" value="others" name="gender" [(ngModel)]="gender"  #ref13="ngModel" required> others &nbsp;
<label *ngIf="ref13.invalid && (ref13.dirty || ref13.untouched )">
    <div class="text-danger"> *select gender mandatory </div>
 </label>
</div>
<div class="form-group">
  <label> LOCATION CODE </label>
  <input type="text" class="form-control round3 " id="lctncode" placeholder="LOCATION CODE" name="lctncode" ngModel
     #ref14="ngModel" required>
  <label *ngIf="ref14.invalid && (ref14.dirty || ref14.touched )">
     <div class="text-danger"> *location code field is mandatory </div>
  </label>
</div>
<div class="text-right">
    <button class="btn btn-success" type="button" (click)="next()">Next</button> </div>

</div>

</div>
              </form>

<!-- COMMUNICATION -->
<form #ref1="ngForm">
<div *ngIf="b && !communication" >
<h3 class="text-primary">COMMUNICATION</h3>
<div class="form-group">
    <label> PHONE NUMBER  </label>
    <input type="number" class="form-control round3 " id="phnumber" placeholder="PHONE NUMBER " name="phnumber" ngModel
       #ref15="ngModel" required>
    <label *ngIf="ref15.invalid && (ref15.dirty || ref15.touched )">
       <div class="text-danger"> *phone number field is mandatory </div>
    </label>
 </div>
 <div class="form-group">
  <label> MOBILE NUMBER  </label>
  <input type="number" class="form-control round3 " id="mblnumber" placeholder="MOBILE NUMBER " name="mblnumber" ngModel
     #ref16="ngModel" required>
  <label *ngIf="ref16.invalid && (ref16.dirty || ref16.touched )">
     <div class="text-danger"> *mobilenumber field is mandatory </div>
  </label>
</div>

<div class="form-group">
    <label> E-MAIL  </label>
    <input type="email" class="form-control round3 " id="email" placeholder="E-MAIL ADDRESS" name="email" ngModel
       #ref17="ngModel" required>
    <label *ngIf="ref17.invalid && (ref17.dirty || ref17.touched )">
       <div class="text-danger"> *email field is mandatory </div>
    </label>
 </div>

 <div class="form-group">
    <label> COMPANY E-MAIL  </label>
    <input type="email" class="form-control round3 " id="cemail" placeholder="COMPANY E-MAIL ADDRESS" name="cemail" ngModel
       #ref18="ngModel" required>
    <label *ngIf="ref18.invalid && (ref18.dirty || ref18.touched )">
       <div class="text-danger"> *company email field is mandatory </div>
    </label>
 </div>
 <div class="text-right">
    <button class="btn btn-success" type="button" (click)="secondNext()">Next</button>

</div>
</div>
</form>
<!-- ADMINISTRATION -->
<form #ref2="ngForm">

<div *ngIf="communication && !administration">
 <h3 class="text-primary">ADMINISTRATION</h3>

    <div class="form-group">
        <label>DESIGNATION  </label>
        <input type="text" class="form-control round3 " id="designation" placeholder="DESIGNATION" name="designation" ngModel
           #ref19="ngModel" required>
        <label *ngIf="ref19.invalid && (ref19.dirty || ref19.touched )">
           <div class="text-danger"> *designation field is mandatory </div>
        </label>
     </div>

     <div class="form-group">
        <label>QUALIFICATION  </label>
        <input type="text" class="form-control round3 " id="qualification" placeholder="QUALIFICATION" name="qualification" ngModel
           #ref20="ngModel" required>
        <label *ngIf="ref19.invalid && (ref20.dirty || ref20.touched )">
           <div class="text-danger"> *qualification field is mandatory </div>
        </label>
     </div>

     <div class="form-group">
        <label>HEIGHT  </label>
        <input type="number" class="form-control round3 " id="height" placeholder="HEIGHT" name="height" ngModel
           #ref21="ngModel" required>
        <label *ngIf="ref21.invalid && (ref21.dirty || ref21.touched )">
           <div class="text-danger"> *height field is mandatory </div>
        </label>
     </div>

     <div class="form-group">
        <label> WEIGHT  </label>
        <input type="number" class="form-control round3 " id="weight" placeholder="WEIGHT" name="weight" ngModel
           #ref22="ngModel" required>
        <label *ngIf="ref22.invalid && (ref22.dirty || ref22.touched )">
           <div class="text-danger"> *weight field is mandatory </div>
        </label>
     </div>

     <div class="form-group">
        <label> EXPERIENCE </label>
        <input type="number" class="form-control round3 " id="experience" placeholder="EXPERIENCE" name="experience" ngModel
           #ref23="ngModel" required>
        <label *ngIf="ref23.invalid && (ref23.dirty || ref23.touched )">
           <div class="text-danger"> *experience field is mandatory </div>
        </label>
     </div>
     <div class="text-right">
        <button class="btn btn-success" type="button" (click)="thirdNext()">Next</button>

    </div>
</div>
</form>
<!-- PERSONAL -->
<form #ref2="ngForm">
<div *ngIf="administration && !paymethod">
<h3 class="text-primary" >PERSONAL</h3>

<div class="form-group">
    <label> DATE OF BIRTH</label>
    <input type="date" class="form-control round3 " id="dob" placeholder="DATE OF BIRTH" name="dob" ngModel
       #ref24="ngModel" required>
    <label *ngIf="ref24.invalid && (ref24.dirty || ref24.touched )">
       <div class="text-danger"> *date of birth field is mandatory </div>
    </label>
 </div>

 <div class="form-group">
    <label> FATHER/HUSBAND NAME </label>
    <input type="text" class="form-control round3 " id="fhname" placeholder="FATHER/HUSBAND NAME" name="fhname" ngModel
       #ref25="ngModel" required>
    <label *ngIf="ref25.invalid && (ref25.dirty || ref25.touched )">
       <div class="text-danger"> *father/husband  field is mandatory </div>
    </label>
 </div>

 <div class="form-group">
    <label> CURRENT AGE (YEARS)</label>
    <input type="number" class="form-control round3 " id="cage" placeholder="CURRENT AGE (YEARS)" name="cage" ngModel
       #ref26="ngModel" required>
    <label *ngIf="ref26.invalid && (ref26.dirty || ref26.touched )">
       <div class="text-danger"> *current age (years) field is mandatory </div>
    </label>
 </div>

 <div class="form-group">
    <label> CURRENT AGE (MONTHS)</label>
    <input type="number" class="form-control round3 " id="cagem" placeholder="CURRENT AGE (MONTHS)" name="cagem" ngModel
       #ref27="ngModel" required>
    <label *ngIf="ref27.invalid && (ref27.dirty || ref27.touched )">
       <div class="text-danger"> *current age (months) field is mandatory </div>
    </label>
 </div>

 <div class="form-group">
    <label> BLOOD GROUP</label>
    <input type="text" class="form-control round3 " id="bloodgrp" placeholder="BLOOD GROUP" name="bloodgrp" ngModel
       #ref28="ngModel" required>
    <label *ngIf="ref28.invalid && (ref28.dirty || ref28.touched )">
       <div class="text-danger"> *bloodgroup field is mandatory </div>
    </label>
 </div>

 <div class="form-group">
    <label> NATIONALITY</label>
    <input type="text" class="form-control round3 " id="nationality" placeholder="NATIONALITY" name="nationality" ngModel
       #ref29="ngModel" required>
    <label *ngIf="ref29.invalid && (ref29.dirty || ref28.touched )">
       <div class="text-danger"> *nationality field is mandatory </div>
    </label>
 </div>

 <div class="form-group">
    <label> PRESENT ADDRESS </label>
    <input type="text" class="form-control round3 " id="paddress" placeholder="PRESENT ADDRESS" name="paddress" ngModel
       #ref30="ngModel" required>
    <label *ngIf="ref30.invalid && (ref30.dirty || ref30.touched )">
       <div class="text-danger"> *presentaddress  field is mandatory </div>
    </label>
 </div>

 <div class="form-group">
  <label>PRESENT ADDRESS 2 </label>
  <input type="text" class="form-control round3 " id="paddress2" placeholder="PRESENT ADDRESS 2" name="paddress2" ngModel
     #ref31="ngModel" required>
  <label *ngIf="ref31.invalid && (ref31.dirty || ref31.touched )">
     <div class="text-danger"> *presentaddress2  field is mandatory </div>
  </label>
</div>

<div class="form-group">
    <label>PRESENT CITY</label>
    <input type="text" class="form-control round3 " id="pcity" placeholder="PRESENT CITY" name="pcity" ngModel
       #ref32="ngModel" required>
    <label *ngIf="ref32.invalid && (ref32.dirty || ref32.touched )">
       <div class="text-danger"> *presentcity  field is mandatory </div>
    </label>
  </div>

  <div class="form-group">
      <label>PRESENT POST CODE </label>
      <input type="number" class="form-control round3 " id="pccode" placeholder="PRESENT CITY CODE" name="pccode" ngModel
         #ref33="ngModel" required>
      <label *ngIf="ref33.invalid && (ref33.dirty || ref33.touched )">
         <div class="text-danger"> *presentcitycode  field is mandatory </div>
      </label>
    </div>

    <div class="form-group">
        <label>PRESENT COUNTRY</label>
        <input type="text" class="form-control round3 " id="pcountry" placeholder="PRESENT COUNTRY" name="pcountry" ngModel
           #ref34="ngModel" required>
        <label *ngIf="ref34.invalid && (ref34.dirty || ref34.touched )">
           <div class="text-danger"> *presentcountry  field is mandatory </div>
        </label>
      </div>

      <div class="form-group">
          <label>PRESENT PHONE NUMBER</label>
          <input type="number" class="form-control round3 " id="pphnno" placeholder="PRESENT PHONE NUMBER" name="pphnno" ngModel
             #ref35="ngModel" required>
          <label *ngIf="ref35.invalid && (ref35.dirty || ref35.touched )">
             <div class="text-danger"> *presentphonenumber  field is mandatory </div>
          </label>
        </div>

        <div class="form-group">
            <label>ADDHAAR NUMBER</label>
            <input type="number" class="form-control round3 " id="aadhaar" placeholder="ADDHAAR NUMBER" name="aadhaar" ngModel
               #ref36="ngModel" required>
            <label *ngIf="ref36.invalid && (ref36.dirty || ref36.touched )">
               <div class="text-danger"> *aadhaar  field is mandatory </div>
            </label>
          </div>

          <div class="form-group">
              <label> PAN NUMBER  </label>
              <input type="text" class="form-control round3 " id="pannumber" placeholder=" PAN NUMBER " name="pannumber" ngModel
                 #ref41="ngModel" required>
              <label *ngIf="ref41.invalid && (ref41.dirty || ref41.touched )">
                 <div class="text-danger"> *pan number  field is mandatory </div>
              </label>
          </div>

          <div class="text-right">
              <button class="btn btn-success" type="button" (click)="fourthNext()">Next</button>

          </div>
</div>
</form>
<form #ref3="ngForm">
<!-- pay method -->
<div *ngIf="paymethod">
<h3  class="text-primary"> PAY METHOD </h3>
<div class="form-group">
      <label> BANK NAME </label>
      <input type="text" class="form-control round3 " id="bankname" placeholder="BANK NAME" name="bankname" ngModel
         #ref37="ngModel" required>
      <label *ngIf="ref37.invalid && (ref37.dirty || ref37.touched )">
         <div class="text-danger"> *bankname  field is mandatory </div>
      </label>
</div>
<div class="form-group">
    <label> BANK IFSC CODE </label>
    <input type="text" class="form-control round3 " id="bankifsccode" placeholder="BANK IFSC CODE" name="bankifsccode" ngModel
       #ref38="ngModel" required>
    <label *ngIf="ref38.invalid && (ref38.dirty || ref38.touched )">
       <div class="text-danger"> *bankifsccode  field is mandatory </div>
    </label>
</div>

<div class="form-group">
    <label> ACCOUNT TYPE</label>
    <input type="text" class="form-control round3 " id="accounttype" placeholder="ACCOUNT TYPE" name="accounttype" ngModel
       #ref39="ngModel" required>
    <label *ngIf="ref39.invalid && (ref39.dirty || ref39.touched )">
       <div class="text-danger"> *accounttype  field is mandatory </div>
    </label>
</div>

<div class="form-group">
    <label> ACCOUNT NUMBER  </label>
    <input type="text" class="form-control round3 " id="accountnumber" placeholder=" ACCOUNT NUMBER " name="accountnumber" ngModel
       #ref40="ngModel" required>
    <label *ngIf="ref40.invalid && (ref40.dirty || ref40.touched )">
       <div class="text-danger"> *accountnumber  field is mandatory </div>
    </label>
</div>

<div class="text-right">
    <button class="btn btn-success" type="submit">submit</button>
 </div>
</div>
 </form>
           </div>


答: What do expect to happen here? You don't seem to be doing anything with the files as you visit them. There is no need for recursion to loop through the files in the directory, the recursion is needed when you hit a file in the list that is a directory.

Title: How can I recursively print a File Array?


问:
Scaffold-DbContext : A positional parameter cannot be found that accepts argument 'Models
enter image description hereI am experience this issue on my Nuget console, while running this command below. Please help me further thanks.</p>

```<code>scaffold-DBContext "Data Source=(LocalDb)\MSSQLLocalDB; Catalog=eNtsaOnlineRegistrationDB;Integrated Security=True" Microsoft.EntityFrameworkCore.SqlServer-OutputDir Models
</code>```

答:
Please check you scaffold command.
You can use -ContextDir (PMC) and --context-dir (CLI) to scaffold the DbContext class into a separate directory from the entity type classes.

Try following command in PMC.

Scaffold-DbContext 'Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Chinook' Microsoft.EntityFrameworkCore.SqlServer -ContextDir Data -OutputDir Models

Also check your Models folder in project root directory with all folder access [read/edit] rights.check single space  -OutputDir Models

You can find more detail on this link Reverse Engineering (Scaffolding)

Body:
enter image description hereI am experience this issue on my Nuget console, while running this command below. Please help me further thanks.

scaffold-DBContext "Data Source=(LocalDb)\MSSQLLocalDB; Catalog=eNtsaOnlineRegistrationDB;Integrated Security=True" Microsoft.EntityFrameworkCore.SqlServer-OutputDir Models