问:
CORS error with the Access-Controll-Allow-Origin * - NodeJS and Angular
I'm doing a web app with Angular and when I connect the backend with the front it gives me a CORS error:
 Access to XMLHttpRequest at 'http://localhost:3700/api/save-project' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

I know what the CORS is but I don't know why this error because in my app.js in the backend I have the code for blocking CORS

How can I fix this issue?

Code:

app.js
    'use strict'

```<code>var express = require('express');
var bodyParser = require('body-parser');

var app = express();

// cargar archivo Rutas
var routes = require('./routes/product');

// Middlewares
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json()); // Content-Type: image/jpg

// Configurar cabeceras y cors
app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Authorization, X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Allow-Request-Method');
    res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE');
    res.header('Allow', 'GET, POST, OPTIONS, PUT, DELETE');
    next();
});

// Rutas
app.use('/api', routes);

// exportar
module.exports = app;
</code>```

component in Angular:

```<code>import { Component, OnInit } from '@angular/core';
import { ProductService } from 'src/app/services/products.service';
import { Product } from 'src/app/models/product';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'crear',
  templateUrl: './create.component.html',
  styleUrls: ['./create.component.css'],
  providers: [HttpClient, ProductService]
})
export class CreateComponent implements OnInit {
  public producto: Product;
  public product: any;

   constructor(
    //,
    //private http: HttpClient
    private _productService: ProductService
  ) {
    this.producto = new Product('','','','',2,2);
  }

  ngOnInit(): void {
  }

  onSubmit(form){
    this._productService.saveProduct(this.producto).subscribe(
      response => {
        if(response.producto){

          form.reset();

          this.product = this.producto._id;
        }else{
        alert("No se ha podido");
      };
      }
    )
  }

}
</code>```

Service:

```<code>import { Injectable } from "@angular/core";
import { Observable } from 'rxjs';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Product } from '../models/product';
import { Global } from './global.service';

@Injectable()
export class ProductService{
    public url: String;

    constructor(
        private _http: HttpClient
    ){
        this.url = Global.url;
    }

    saveProduct(product: Product): Observable<any>{
        var params = JSON.stringify(product);
        let headers =  new HttpHeaders().set('Content-Type', 'application/json');

        return this._http.post(this.url+'save-project', params, {headers: headers});
    }
}
</code>```

Thanks for all

答:
Try to add these if statement after set the CORS headers in app.js
(I needed this in graphQL and hopefully, it works!)</p>

```<code>if (req.method === "OPTIONS") {
    res.send(200);
  }
</code>```

```<code>app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Authorization, X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Allow-Request-Method');
    res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE');
    res.header('Allow', 'GET, POST, OPTIONS, PUT, DELETE');
  if (req.method === "OPTIONS") {
    res.send(200);
  }
    next();
});
</code>```

Body:
I'm doing a web app with Angular and when I connect the backend with the front it gives me a CORS error:
 Access to XMLHttpRequest at 'http://localhost:3700/api/save-project' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

I know what the CORS is but I don't know why this error because in my app.js in the backend I have the code for blocking CORS

How can I fix this issue?

Code:

app.js
    'use strict'

var express = require('express');
var bodyParser = require('body-parser');

var app = express();

// cargar archivo Rutas
var routes = require('./routes/product');

// Middlewares
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json()); // Content-Type: image/jpg

// Configurar cabeceras y cors
app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Authorization, X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Allow-Request-Method');
    res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE');
    res.header('Allow', 'GET, POST, OPTIONS, PUT, DELETE');
    next();
});

// Rutas
app.use('/api', routes);

// exportar
module.exports = app;

component in Angular:

import { Component, OnInit } from '@angular/core';
import { ProductService } from 'src/app/services/products.service';
import { Product } from 'src/app/models/product';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'crear',
  templateUrl: './create.component.html',
  styleUrls: ['./create.component.css'],
  providers: [HttpClient, ProductService]
})
export class CreateComponent implements OnInit {
  public producto: Product;
  public product: any;

   constructor(
    //,
    //private http: HttpClient
    private _productService: ProductService
  ) {
    this.producto = new Product('','','','',2,2);
  }

  ngOnInit(): void {
  }

  onSubmit(form){
    this._productService.saveProduct(this.producto).subscribe(
      response => {
        if(response.producto){

          form.reset();

          this.product = this.producto._id;
        }else{
        alert("No se ha podido");
      };
      }
    )
  }

}

Service:

import { Injectable } from "@angular/core";
import { Observable } from 'rxjs';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Product } from '../models/product';
import { Global } from './global.service';

@Injectable()
export class ProductService{
    public url: String;

    constructor(
        private _http: HttpClient
    ){
        this.url = Global.url;
    }

    saveProduct(product: Product): Observable<any>{
        var params = JSON.stringify(product);
        let headers =  new HttpHeaders().set('Content-Type', 'application/json');

        return this._http.post(this.url+'save-project', params, {headers: headers});
    }
}

Thanks for all

Body:
Try to add these if statement after set the CORS headers in app.js
(I needed this in graphQL and hopefully, it works!)

if (req.method === "OPTIONS") {
    res.send(200);
  }

app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Authorization, X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Allow-Request-Method');
    res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE');
    res.header('Allow', 'GET, POST, OPTIONS, PUT, DELETE');
  if (req.method === "OPTIONS") {
    res.send(200);
  }
    next();
});


来源: stackexchange

问:
C# WPF Best Practice to share a model across viewmodels

I am writing a small scientific program. It has lots of variables as input.

The user has to enter all the input variables in the window (or user interface). But, I cannot fit all the input in a single window (XAML). Thus, I have created several Views where the user just press the NEXT button to enter data in the next View.

All of these Views have associated ViewModels. They all inherit from a base ViewModel.

So, my question is: Do I write the properties of all the variables inside the base ViewModel? Like this:

```<code>namespace ScienceProgram
{
    public abstract class BaseViewModel : INotifyPropertyChanged
    {

        #region Usual Boiler-plate stuff for BindableBase

        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged([CallerMemberName] string name = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
        }
        #endregion

        #region Properties (All scientific parameters and calculations )

        public double ParamA { get; set; }
        public double ParamB { get; set;  }
        // ...
        // Lots of parameters //
        // ...
        public double ParamA23 { get; set;  }

        public double TotalLength()
        {
            return ParamA + ParamB + ParamA23;
        }

        // ...
        // Lots of other methods
        // ...

        #endregion

    }
}
</code>```

Or do I create a separate class (e.g. ScienceParameters.cs) for all input parameters and do as follows (this is what I am doing):

```<code>namespace ScienceProgram
{
    public abstract class BaseViewModel : INotifyPropertyChanged
    {

        // Global Parameter // Shared across ViewModels //
        public static ScienceParameters scienceParameters = new ScienceParameters ();

        #region Usual Boiler-plate stuff for BindableBase

        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged([CallerMemberName] string name = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
        }
        #endregion

    }
}
</code>```

I am using the latter approach. When the user enters the data in the textbox, I simply store it as:

```<code>namespace ScienceProgram
{
    public class UserInputView1ViewModel : BaseViewModel
    {
        #region User Input
        private double _paramA;
        public double ParamA
        {
            get { return _paramA; }
            set
            {
                _paramA = value;
                OnPropertyChanged("ParamA");

                // Store Value //
                scienceParameters.ParamA = value;
            }
        }
    }
}
        #endregion
</code>```

Which is the the right way? Or is there a better way?

I have been looking for some best practices, but I keep getting directed to EventAggregator and using a singleton. I don't think I need those.

I think the solution is "to pass a model into constructor of a view model.", as many have said. But I am a bit confused on how to do it. Wouldn't that create a new instance in each viewModel?

Sorry, if this sounds like a silly question, but I have been looking for a straight answer for the past week, and have not yet figured out the solution.

Many thanks in advance.

答:
You're close. I see areas where you are duplicating storage of data that could cause maintenance problems.  Based on what you've stated, I think your approach with having a BaseViewModel is unnecessary (but if you follow through my answer here, I show you how you could make a BaseViewModel more useful than what you're using it for).

If I understand correctly, you have multiple Views because you want the user to press 'NEXT' to get to the next navigated View.  Each View has one associated ViewModel.  But underneath the hood, you want to collect all of the properties into one class instance.

To me, the best practice here is to learn the MVVM architecture.  The key learning that comes from MVVM is understanding "separation of concerns".  Mainly, your data (i.e. all of the user's input values, aka the "Model") has nothing to do with the Views and ViewModels that you present to them in the UI.  Read up on this and you will get a better handle on this good practice.

Here's how I would do it.

1) Create a Model class (ScienceParameters.cs), this will hold ALL of the properties that you expect the user to enter. Example:

```<code>public class ScienceParameters
{
        public double ParamA { get; set; }
        public double ParamB { get; set;  }
        // ...
        // Lots of parameters //
        // ...
        public double ParamA23 { get; set;  }

        public double TotalLength()
        {
            return ParamA + ParamB + ParamA23;
        }
}

</code>```

Then on each UI that you present to the user, you will show them one View and one associated ViewModel that gives them access to "see/get" or "store/set" PORTIONS of this data.  Example:

```<code>public class UserInput1ViewModel: INotifyPropertyChanged
{
        public UserInput1ViewModel(ScienceParameters model)
        {
            this.Model = model;
        }

        public ScienceParameters Model { get; private set; }

        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged([CallerMemberName] string name = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
        }

        public double ParamA
        {
            get { return this.Model.ParamA; }
            set
            {
                // Store the user's data directly into the Model, not the ViewModel!
                this.Model.ParamA = value;
                OnPropertyChanged(nameof(this.ParamA));  // <-- avoid magic words like "ParamA" in quotes, this is bad coding and can cause maintenance issues.
            }
        }

}
public class UserInput2ViewModel: INotifyPropertyChanged
{
        public UserInput2ViewModel(ScienceParameters model)
        {
            this.Model = model;
        }

        public ScienceParameters Model { get; private set; }

        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged([CallerMemberName] string name = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
        }

        public double ParamB
        {
            get { return this.Model.ParamB; }
            set
            {
                this.Model.ParamB = value;
                OnPropertyChanged(nameof(this.ParamB));
            }
        }

}

</code>```

Extra Credit:

If you want to remove the repetitiveness of writing the PropertyChanged junk in each ViewModel, then put it into a BaseViewModel.

```<code>public class BaseViewModel : INotifyPropertyChanged
{
        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged([CallerMemberName] string name = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
        }
}
</code>```

Then remove all those PropertyChanged lines from your ViewModels and instead define each ViewModel with the base:

```<code>public class UserInput1ViewModel: BaseViewModel
{
   // ...
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am writing a small scientific program. It has lots of variables as input.

The user has to enter all the input variables in the window (or user interface). But, I cannot fit all the input in a single window (XAML). Thus, I have created several Views where the user just press the NEXT button to enter data in the next View.

All of these Views have associated ViewModels. They all inherit from a base ViewModel.

So, my question is: Do I write the properties of all the variables inside the base ViewModel? Like this:

namespace ScienceProgram
{
    public abstract class BaseViewModel : INotifyPropertyChanged
    {

        #region Usual Boiler-plate stuff for BindableBase

        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged([CallerMemberName] string name = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
        }
        #endregion

        #region Properties (All scientific parameters and calculations )

        public double ParamA { get; set; }
        public double ParamB { get; set;  }
        // ...
        // Lots of parameters //
        // ...
        public double ParamA23 { get; set;  }

        public double TotalLength()
        {
            return ParamA + ParamB + ParamA23;
        }

        // ...
        // Lots of other methods
        // ...

        #endregion

    }
}

Or do I create a separate class (e.g. ScienceParameters.cs) for all input parameters and do as follows (this is what I am doing):

namespace ScienceProgram
{
    public abstract class BaseViewModel : INotifyPropertyChanged
    {

        // Global Parameter // Shared across ViewModels //
        public static ScienceParameters scienceParameters = new ScienceParameters ();

        #region Usual Boiler-plate stuff for BindableBase

        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged([CallerMemberName] string name = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
        }
        #endregion

    }
}

I am using the latter approach. When the user enters the data in the textbox, I simply store it as:

namespace ScienceProgram
{
    public class UserInputView1ViewModel : BaseViewModel
    {
        #region User Input
        private double _paramA;
        public double ParamA
        {
            get { return _paramA; }
            set
            {
                _paramA = value;
                OnPropertyChanged("ParamA");

                // Store Value //
                scienceParameters.ParamA = value;
            }
        }
    }
}
        #endregion

Which is the the right way? Or is there a better way?

I have been looking for some best practices, but I keep getting directed to EventAggregator and using a singleton. I don't think I need those.

I think the solution is "to pass a model into constructor of a view model.", as many have said. But I am a bit confused on how to do it. Wouldn't that create a new instance in each viewModel?

Sorry, if this sounds like a silly question, but I have been looking for a straight answer for the past week, and have not yet figured out the solution.

Many thanks in advance.

Body:
You're close. I see areas where you are duplicating storage of data that could cause maintenance problems.  Based on what you've stated, I think your approach with having a BaseViewModel is unnecessary (but if you follow through my answer here, I show you how you could make a BaseViewModel more useful than what you're using it for).

If I understand correctly, you have multiple Views because you want the user to press 'NEXT' to get to the next navigated View.  Each View has one associated ViewModel.  But underneath the hood, you want to collect all of the properties into one class instance.

To me, the best practice here is to learn the MVVM architecture.  The key learning that comes from MVVM is understanding "separation of concerns".  Mainly, your data (i.e. all of the user's input values, aka the "Model") has nothing to do with the Views and ViewModels that you present to them in the UI.  Read up on this and you will get a better handle on this good practice.

Here's how I would do it.

1) Create a Model class (ScienceParameters.cs), this will hold ALL of the properties that you expect the user to enter. Example:

public class ScienceParameters
{
        public double ParamA { get; set; }
        public double ParamB { get; set;  }
        // ...
        // Lots of parameters //
        // ...
        public double ParamA23 { get; set;  }

        public double TotalLength()
        {
            return ParamA + ParamB + ParamA23;
        }
}

Then on each UI that you present to the user, you will show them one View and one associated ViewModel that gives them access to "see/get" or "store/set" PORTIONS of this data.  Example:

public class UserInput1ViewModel: INotifyPropertyChanged
{
        public UserInput1ViewModel(ScienceParameters model)
        {
            this.Model = model;
        }

        public ScienceParameters Model { get; private set; }

        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged([CallerMemberName] string name = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
        }

        public double ParamA
        {
            get { return this.Model.ParamA; }
            set
            {
                // Store the user's data directly into the Model, not the ViewModel!
                this.Model.ParamA = value;
                OnPropertyChanged(nameof(this.ParamA));  // <-- avoid magic words like "ParamA" in quotes, this is bad coding and can cause maintenance issues.
            }
        }

}
public class UserInput2ViewModel: INotifyPropertyChanged
{
        public UserInput2ViewModel(ScienceParameters model)
        {
            this.Model = model;
        }

        public ScienceParameters Model { get; private set; }

        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged([CallerMemberName] string name = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
        }

        public double ParamB
        {
            get { return this.Model.ParamB; }
            set
            {
                this.Model.ParamB = value;
                OnPropertyChanged(nameof(this.ParamB));
            }
        }

}

Extra Credit:

If you want to remove the repetitiveness of writing the PropertyChanged junk in each ViewModel, then put it into a BaseViewModel.

public class BaseViewModel : INotifyPropertyChanged
{
        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged([CallerMemberName] string name = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
        }
}

Then remove all those PropertyChanged lines from your ViewModels and instead define each ViewModel with the base:

public class UserInput1ViewModel: BaseViewModel
{
   // ...
}


问:
Create class column in data.table given a numeric vector
Currently I have a data.table like this:

```<code>item    dummyvar
4q7C0o     1
2BrKY63    1
3drUy6I    1
G5ALtO    1000
G5G859    1000
PAP589    2000
</code>```

And using a defined function I find out that the rows where there is a significant change in the dummyvar are in a numeric vector called imbalance = 4 6. What I would like to do is to create a new column in my data table such that all the rows below the given numbers given by imbalance are in a given class, for ex. something like this:

```<code>item    dummyvar   Class
4q7C0o     1         1
2BrKY63    1         1
3drUy6I    1         1
G5ALtO    1000       2
G5G859    1000       2
PAP589    2000       3
</code>```

答: Perhaps your_data_table[, Class := cumsum(.I %in% imbalance)]? I'm assuming imbalance is a vector of the row numbers where you want Class to increment. (This version starts at 0, but you could stick a + 1 on it to start at 1)

Body:
Currently I have a data.table like this:

item    dummyvar
4q7C0o     1
2BrKY63    1
3drUy6I    1
G5ALtO    1000
G5G859    1000
PAP589    2000

And using a defined function I find out that the rows where there is a significant change in the dummyvar are in a numeric vector called imbalance = 4 6. What I would like to do is to create a new column in my data table such that all the rows below the given numbers given by imbalance are in a given class, for ex. something like this:

item    dummyvar   Class
4q7C0o     1         1
2BrKY63    1         1
3drUy6I    1         1
G5ALtO    1000       2
G5G859    1000       2
PAP589    2000       3


问:
Styling the placeholder in a TextField
The TextField API doesn't mention anything about how one could style the pseudo placeholder element of the input element.

Basically, I would like to change the default styling of the placeholder text, and the normal bag of tricks doesn't work, as I cannot access the element.

Is there a way I can get to it? And if so, what is the JSS/React/DOM equivalent way of writing ::-webkit-input-placeholder?

答:
With styled components I just use:</p>

```<code>const StyledTextField = styled(TextField)`
    label {
        font-style: italic;
    }
`;
</code>```

ContentLicense: CC BY-SA 3.0

Title: Styling the placeholder in a TextField

Body:
With styled components I just use:

const StyledTextField = styled(TextField)`
    label {
        font-style: italic;
    }
`;


问:
Bazel Golang combined coverage report
I'm trying to generate a combined coverage report for my golang files using

```<code>bazel coverage --combined_report=lcov  //...
</code>```

but it always fails with the same message:

```<code>Executed 0 out of 11 tests: 11 tests pass.
There were tests whose specified size is too big. Use the --test_verbose_timeout_warnings command line option to see which ones these are.
</code>```

Naturally I used the flag --test_verbose_timeout_warnings and I get the error

```<code>//pkg/util:go_default_test                                      (cached) PASSED in 4.4s
WARNING: //pkg/util:go_default_test: Test execution time (4.4s excluding execution overhead) outside of range for MODERATE tests. Consider setting timeout="short" or size="small".
</code>```

I then tried it with --nocache_test_results but nothing different.

I've tried it with

```<code>bazel coverage --combined_report=lcov --test_size_filters=small //...
</code>```

This is what I get:

```<code>WARNING: All specified test targets were excluded by filters
INFO: Build option --instrumentation_filter has changed, discarding analysis cache.
INFO: Analyzed 52 targets (0 packages loaded, 8254 targets configured).
INFO: Found 52 targets and 0 test targets...
</code>```

Using bazel coverage --combined_report=lcov --test_size_filters=small,medium --nocache_test_results //... results in this

```<code>INFO: Using default value for --instrumentation_filter: "//internal[/:],//pkg[/:]".
INFO: Override the above default with --instrumentation_filter
INFO: Build option --instrumentation_filter has changed, discarding analysis cache.
INFO: Analyzed 52 targets (0 packages loaded, 8254 targets configured).
INFO: Found 41 targets and 11 test targets...
INFO: LCOV coverage report is located at /path/to/bazel-out/_coverage/_coverage_report.dat
 and execpath is bazel-out/_coverage/_coverage_report.dat
INFO: From CoverageReport _coverage/_coverage_report.dat:
März 31, 2020 11:05:17 VORM. com.google.devtools.coverageoutputgenerator.Main getTracefiles
INFORMATION: Found 11 tracefiles.
März 31, 2020 11:05:17 VORM. com.google.devtools.coverageoutputgenerator.Main parseFiles
SCHWERWIEGEND: Parsing file bazel-out/darwin-fastbuild/testlogs/pkg/logger/go_default_test/coverage.dat
März 31, 2020 11:05:17 VORM. com.google.devtools.coverageoutputgenerator.Main parseFiles
SCHWERWIEGEND: Parsing file bazel-out/darwin-fastbuild/testlogs/pkg/util/go_default_test/coverage.dat
März 31, 2020 11:05:17 VORM. com.google.devtools.coverageoutputgenerator.Main parseFiles
SCHWERWIEGEND: Parsing file bazel-out/darwin-fastbuild/testlogs/internal/company/go_default_test/coverage.dat
März 31, 2020 11:05:17 VORM. com.google.devtools.coverageoutputgenerator.Main parseFiles
SCHWERWIEGEND: Parsing file bazel-out/darwin-fastbuild/testlogs/internal/video/go_default_test/coverage.dat
März 31, 2020 11:05:17 VORM. com.google.devtools.coverageoutputgenerator.Main parseFiles
SCHWERWIEGEND: Parsing file bazel-out/darwin-fastbuild/testlogs/internal/person/go_default_test/coverage.dat
März 31, 2020 11:05:17 VORM. com.google.devtools.coverageoutputgenerator.Main parseFiles
SCHWERWIEGEND: Parsing file bazel-out/darwin-fastbuild/testlogs/internal/db/go_default_test/coverage.dat
März 31, 2020 11:05:17 VORM. com.google.devtools.coverageoutputgenerator.Main parseFiles
SCHWERWIEGEND: Parsing file bazel-out/darwin-fastbuild/testlogs/internal/movie/go_default_test/coverage.dat
März 31, 2020 11:05:17 VORM. com.google.devtools.coverageoutputgenerator.Main parseFiles
SCHWERWIEGEND: Parsing file bazel-out/darwin-fastbuild/testlogs/internal/game/go_default_test/coverage.dat
März 31, 2020 11:05:17 VORM. com.google.devtools.coverageoutputgenerator.Main parseFiles
SCHWERWIEGEND: Parsing file bazel-out/darwin-fastbuild/testlogs/internal/mapper/go_default_test/coverage.dat
März 31, 2020 11:05:17 VORM. com.google.devtools.coverageoutputgenerator.Main parseFiles
SCHWERWIEGEND: Parsing file bazel-out/darwin-fastbuild/testlogs/internal/shared/go_default_test/coverage.dat
März 31, 2020 11:05:17 VORM. com.google.devtools.coverageoutputgenerator.Main parseFiles
SCHWERWIEGEND: Parsing file bazel-out/darwin-fastbuild/testlogs/internal/music/go_default_test/coverage.dat
März 31, 2020 11:05:17 VORM. com.google.devtools.coverageoutputgenerator.Main getGcovInfoFiles
INFORMATION: No gcov info file found.
März 31, 2020 11:05:17 VORM. com.google.devtools.coverageoutputgenerator.Main getProfdataFileOrNull
INFORMATION: No .profdata file found.
März 31, 2020 11:05:17 VORM. com.google.devtools.coverageoutputgenerator.Main main
WARNUNG: There was no coverage found.
ERROR: output '_coverage/_coverage_report.dat' was not created
ERROR: not all outputs were created or valid
INFO: Elapsed time: 33.842s, Critical Path: 32.39s
INFO: 196 processes: 196 darwin-sandbox.
FAILED: Build did NOT complete successfully
//internal/company:go_default_test                                       PASSED in 5.6s
  /path/to/bazel-out/darwin-fastbuild/testlogs/internal/company/go_default_test/coverage.dat
//internal/db:go_default_test                                            PASSED in 1.5s
  /path/to/bazel-out/darwin-fastbuild/testlogs/internal/db/go_default_test/coverage.dat
//internal/game:go_default_test                                          PASSED in 8.5s
  /path/to/bazel-out/darwin-fastbuild/testlogs/internal/game/go_default_test/coverage.dat
//internal/mapper:go_default_test                                        PASSED in 1.3s
  /path/to/bazel-out/darwin-fastbuild/testlogs/internal/mapper/go_default_test/coverage.dat
//internal/movie:go_default_test                                         PASSED in 24.8s
  /path/to/bazel-out/darwin-fastbuild/testlogs/internal/movie/go_default_test/coverage.dat
//internal/music:go_default_test                                         PASSED in 10.0s
  /path/to/bazel-out/darwin-fastbuild/testlogs/internal/music/go_default_test/coverage.dat
//internal/person:go_default_test                                        PASSED in 6.6s
  /path/to/bazel-out/darwin-fastbuild/testlogs/internal/person/go_default_test/coverage.dat
//internal/shared:go_default_test                                        PASSED in 3.0s
  /path/to/bazel-out/darwin-fastbuild/testlogs/internal/shared/go_default_test/coverage.dat
//internal/video:go_default_test                                         PASSED in 8.9s
  /path/to/bazel-out/darwin-fastbuild/testlogs/internal/video/go_default_test/coverage.dat
//pkg/logger:go_default_test                                             PASSED in 0.8s
  /path/to/bazel-out/darwin-fastbuild/testlogs/pkg/logger/go_default_test/coverage.dat
//pkg/util:go_default_test                                               PASSED in 0.9s
  /path/to/bazel-out/darwin-fastbuild/testlogs/pkg/util/go_default_test/coverage.dat

Executed 11 out of 11 tests: 11 tests pass.
There were tests whose specified size is too big. Use the --test_verbose_timeout_warnings command line option to see which ones these are.
All tests passed but there were other errors during the build.
FAILED: Build did NOT complete successfully

</code>```

I can't seem to get a combined coverage report.

答: You might be on an old version of bazel. Try using 2.1.0 or later.</p>

Title: Bazel Golang combined coverage report

Body:
I'm trying to generate a combined coverage report for my golang files using

bazel coverage --combined_report=lcov  //...

but it always fails with the same message:

Executed 0 out of 11 tests: 11 tests pass.
There were tests whose specified size is too big. Use the --test_verbose_timeout_warnings command line option to see which ones these are.

Naturally I used the flag --test_verbose_timeout_warnings and I get the error

//pkg/util:go_default_test                                      (cached) PASSED in 4.4s
WARNING: //pkg/util:go_default_test: Test execution time (4.4s excluding execution overhead) outside of range for MODERATE tests. Consider setting timeout="short" or size="small".

I then tried it with --nocache_test_results but nothing different.

I've tried it with

bazel coverage --combined_report=lcov --test_size_filters=small //...

This is what I get:

WARNING: All specified test targets were excluded by filters
INFO: Build option --instrumentation_filter has changed, discarding analysis cache.
INFO: Analyzed 52 targets (0 packages loaded, 8254 targets configured).
INFO: Found 52 targets and 0 test targets...

Using bazel coverage --combined_report=lcov --test_size_filters=small,medium --nocache_test_results //... results in this

INFO: Using default value for --instrumentation_filter: "//internal[/:],//pkg[/:]".
INFO: Override the above default with --instrumentation_filter
INFO: Build option --instrumentation_filter has changed, discarding analysis cache.
INFO: Analyzed 52 targets (0 packages loaded, 8254 targets configured).
INFO: Found 41 targets and 11 test targets...
INFO: LCOV coverage report is located at /path/to/bazel-out/_coverage/_coverage_report.dat
 and execpath is bazel-out/_coverage/_coverage_report.dat
INFO: From CoverageReport _coverage/_coverage_report.dat:
März 31, 2020 11:05:17 VORM. com.google.devtools.coverageoutputgenerator.Main getTracefiles
INFORMATION: Found 11 tracefiles.
März 31, 2020 11:05:17 VORM. com.google.devtools.coverageoutputgenerator.Main parseFiles
SCHWERWIEGEND: Parsing file bazel-out/darwin-fastbuild/testlogs/pkg/logger/go_default_test/coverage.dat
März 31, 2020 11:05:17 VORM. com.google.devtools.coverageoutputgenerator.Main parseFiles
SCHWERWIEGEND: Parsing file bazel-out/darwin-fastbuild/testlogs/pkg/util/go_default_test/coverage.dat
März 31, 2020 11:05:17 VORM. com.google.devtools.coverageoutputgenerator.Main parseFiles
SCHWERWIEGEND: Parsing file bazel-out/darwin-fastbuild/testlogs/internal/company/go_default_test/coverage.dat
März 31, 2020 11:05:17 VORM. com.google.devtools.coverageoutputgenerator.Main parseFiles
SCHWERWIEGEND: Parsing file bazel-out/darwin-fastbuild/testlogs/internal/video/go_default_test/coverage.dat
März 31, 2020 11:05:17 VORM. com.google.devtools.coverageoutputgenerator.Main parseFiles
SCHWERWIEGEND: Parsing file bazel-out/darwin-fastbuild/testlogs/internal/person/go_default_test/coverage.dat
März 31, 2020 11:05:17 VORM. com.google.devtools.coverageoutputgenerator.Main parseFiles
SCHWERWIEGEND: Parsing file bazel-out/darwin-fastbuild/testlogs/internal/db/go_default_test/coverage.dat
März 31, 2020 11:05:17 VORM. com.google.devtools.coverageoutputgenerator.Main parseFiles
SCHWERWIEGEND: Parsing file bazel-out/darwin-fastbuild/testlogs/internal/movie/go_default_test/coverage.dat
März 31, 2020 11:05:17 VORM. com.google.devtools.coverageoutputgenerator.Main parseFiles
SCHWERWIEGEND: Parsing file bazel-out/darwin-fastbuild/testlogs/internal/game/go_default_test/coverage.dat
März 31, 2020 11:05:17 VORM. com.google.devtools.coverageoutputgenerator.Main parseFiles
SCHWERWIEGEND: Parsing file bazel-out/darwin-fastbuild/testlogs/internal/mapper/go_default_test/coverage.dat
März 31, 2020 11:05:17 VORM. com.google.devtools.coverageoutputgenerator.Main parseFiles
SCHWERWIEGEND: Parsing file bazel-out/darwin-fastbuild/testlogs/internal/shared/go_default_test/coverage.dat
März 31, 2020 11:05:17 VORM. com.google.devtools.coverageoutputgenerator.Main parseFiles
SCHWERWIEGEND: Parsing file bazel-out/darwin-fastbuild/testlogs/internal/music/go_default_test/coverage.dat
März 31, 2020 11:05:17 VORM. com.google.devtools.coverageoutputgenerator.Main getGcovInfoFiles
INFORMATION: No gcov info file found.
März 31, 2020 11:05:17 VORM. com.google.devtools.coverageoutputgenerator.Main getProfdataFileOrNull
INFORMATION: No .profdata file found.
März 31, 2020 11:05:17 VORM. com.google.devtools.coverageoutputgenerator.Main main
WARNUNG: There was no coverage found.
ERROR: output '_coverage/_coverage_report.dat' was not created
ERROR: not all outputs were created or valid
INFO: Elapsed time: 33.842s, Critical Path: 32.39s
INFO: 196 processes: 196 darwin-sandbox.
FAILED: Build did NOT complete successfully
//internal/company:go_default_test                                       PASSED in 5.6s
  /path/to/bazel-out/darwin-fastbuild/testlogs/internal/company/go_default_test/coverage.dat
//internal/db:go_default_test                                            PASSED in 1.5s
  /path/to/bazel-out/darwin-fastbuild/testlogs/internal/db/go_default_test/coverage.dat
//internal/game:go_default_test                                          PASSED in 8.5s
  /path/to/bazel-out/darwin-fastbuild/testlogs/internal/game/go_default_test/coverage.dat
//internal/mapper:go_default_test                                        PASSED in 1.3s
  /path/to/bazel-out/darwin-fastbuild/testlogs/internal/mapper/go_default_test/coverage.dat
//internal/movie:go_default_test                                         PASSED in 24.8s
  /path/to/bazel-out/darwin-fastbuild/testlogs/internal/movie/go_default_test/coverage.dat
//internal/music:go_default_test                                         PASSED in 10.0s
  /path/to/bazel-out/darwin-fastbuild/testlogs/internal/music/go_default_test/coverage.dat
//internal/person:go_default_test                                        PASSED in 6.6s
  /path/to/bazel-out/darwin-fastbuild/testlogs/internal/person/go_default_test/coverage.dat
//internal/shared:go_default_test                                        PASSED in 3.0s
  /path/to/bazel-out/darwin-fastbuild/testlogs/internal/shared/go_default_test/coverage.dat
//internal/video:go_default_test                                         PASSED in 8.9s
  /path/to/bazel-out/darwin-fastbuild/testlogs/internal/video/go_default_test/coverage.dat
//pkg/logger:go_default_test                                             PASSED in 0.8s
  /path/to/bazel-out/darwin-fastbuild/testlogs/pkg/logger/go_default_test/coverage.dat
//pkg/util:go_default_test                                               PASSED in 0.9s
  /path/to/bazel-out/darwin-fastbuild/testlogs/pkg/util/go_default_test/coverage.dat

Executed 11 out of 11 tests: 11 tests pass.
There were tests whose specified size is too big. Use the --test_verbose_timeout_warnings command line option to see which ones these are.
All tests passed but there were other errors during the build.
FAILED: Build did NOT complete successfully

I can't seem to get a combined coverage report.


问:
How do I import react-modal into existing application?
I've been slowly trying to migrate some pieces of an existing, large php/jquery project to use ReactJS, especially using some reusable components. ReactJS has been working well for me, but today I tried to import a library using npm, which is completely new to me.

After running npm install react-modal I see that node_modules\react-modal (along with several other folders) were created. So far, so good.

However, I cannot seem to include that component into my project. If I try import ReactModal from 'react-modal'; at the top of my component's .js file, I get: Uncaught ReferenceError: require is not defined. I get errors thrown if I try to include the node_modules\react-modal\lib\components\Modal.js file directly, which I realize is probably the wrong approach but I'm grasping at straws here. I suspect I'm missing something basic, but I just can't seem to figure this one out. Does anyone have any ideas?

Edit: here is how I include React into my project currently:

```<code><!-- Load React. -->
{if $env=="prod"}
    <script src="https://unpkg.com/react@16/umd/react.production.min.js" crossorigin></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js" crossorigin></script>

    {* tabs support *}
    <script src="https://unpkg.com/prop-types/prop-types.js"></script>
    <script src="https://unpkg.com/react-tabs@3/dist/react-tabs.production.min.js"></script>
    <link href="https://unpkg.com/react-tabs@3/style/react-tabs.css" rel="stylesheet">

{else}

    <script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>

    {* tabs support *}
    <script src="https://unpkg.com/prop-types/prop-types.js"></script>
    <script src="https://unpkg.com/react-tabs@3/dist/react-tabs.development.js"></script>
    <link href="https://unpkg.com/react-tabs@3/style/react-tabs.css" rel="stylesheet">

{/if}

{* Babel support *}
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
</code>```

This is the full component (contents of the matchSelector.js file):

```<code>import Modal from 'react-modal';

/**
 * Select a match with hooks to return the proper match info to the instantiator
 */
class MatchSelector extends React.Component {
    /**
     * Class Constructor
     *
     * props expected:
     *      className - (optional) use if you want to style the picker button/icon differently. Note that
     *      if given, all standard classes will be overrided.
     *
     *      type - (optional) can be "text", "icon", "both". Default is "both".
     *
     *      text - (optional) if type is "text" or "both", the text to use on the button. Default is "Select Match"
     *
     */
    constructor(props) {
        super(props);       // let Dad know what's up

        this.state = {showDialog:false}

        this.handleClick = this.handleClick.bind(this);
        this.handleClose = this.handleClose.bind(this);
    }

    handleClick(event) {
        event.preventDefault();

        this.setState({showDialog:true});
    }

    handleClose() {
        this.setState({showDialog:false});
    }

    render() {
        const defaultClassName = "ui-state-default ui-corner-all ui-button compressed";
        let className = (odcmp.empty(this.props.className)?defaultClassName:this.props.className);

        return (
                <React.Fragment>
                    <button
                        className={className}
                        onClick={this.handleClick}>
                            {this.buttonContent()}
                    </button>
                    <MatchSearchDialog
                        show={this.state.showDialog} />
                </React.Fragment>
        );
    }

    buttonContent() {
        var text = (odcmp.empty(this.props.text)?"Select Match":this.props.text);

        if (odcmp.empty(this.props.type) || (this.props.type.toLowerCase()=="both")) {
            return (
                <span><span className="ui-icon ui-icon-search inline"></span>{text}</span>
            );
        } else if (this.props.type.toLowerCase()=="icon") {
            return (
                <span className="ui-icon ui-icon-search inline"></span>
            );
        } else {
            return text;
        }
    }
}

class MatchSearchDialog extends React.Component {
    constructor(props) {
        super(props);
    }

    render() {
        return (
            <ReactModal isOpen={false}><div>hi</div></ReactModal>
        );
    }
}
</code>```

答:
In case anyone runs into this, I wanted to add my resolution.

I was trying to run a bare bones REACTJS project without webpack. react-modal depends on webpack (as does, I'm sure, many React components). As I'm trying to stay light and agile, I removed the react-modal module and "rolled my own" modal dialog.

FYI, the clue is the "require not defined" error in the console - indicating a non-browser (node.js) function was hit. It was expecting to compile (webpack) into a separate js file using the node.js terminology.

Body:
I've been slowly trying to migrate some pieces of an existing, large php/jquery project to use ReactJS, especially using some reusable components. ReactJS has been working well for me, but today I tried to import a library using npm, which is completely new to me.

After running npm install react-modal I see that node_modules\react-modal (along with several other folders) were created. So far, so good.

However, I cannot seem to include that component into my project. If I try import ReactModal from 'react-modal'; at the top of my component's .js file, I get: Uncaught ReferenceError: require is not defined. I get errors thrown if I try to include the node_modules\react-modal\lib\components\Modal.js file directly, which I realize is probably the wrong approach but I'm grasping at straws here. I suspect I'm missing something basic, but I just can't seem to figure this one out. Does anyone have any ideas?

Edit: here is how I include React into my project currently:

{if $env=="prod"}

    {* tabs support *}

    <link href="https://unpkg.com/react-tabs@3/style/react-tabs.css" rel="stylesheet">

{else}

    {* tabs support *}

    <link href="https://unpkg.com/react-tabs@3/style/react-tabs.css" rel="stylesheet">

{/if}

{* Babel support *}

This is the full component (contents of the matchSelector.js file):

import Modal from 'react-modal';

/**
 * Select a match with hooks to return the proper match info to the instantiator
 */
class MatchSelector extends React.Component {
    /**
     * Class Constructor
     *
     * props expected:
     *      className - (optional) use if you want to style the picker button/icon differently. Note that
     *      if given, all standard classes will be overrided.
     *
     *      type - (optional) can be "text", "icon", "both". Default is "both".
     *
     *      text - (optional) if type is "text" or "both", the text to use on the button. Default is "Select Match"
     *
     */
    constructor(props) {
        super(props);       // let Dad know what's up

        this.state = {showDialog:false}

        this.handleClick = this.handleClick.bind(this);
        this.handleClose = this.handleClose.bind(this);
    }

    handleClick(event) {
        event.preventDefault();

        this.setState({showDialog:true});
    }

    handleClose() {
        this.setState({showDialog:false});
    }

    render() {
        const defaultClassName = "ui-state-default ui-corner-all ui-button compressed";
        let className = (odcmp.empty(this.props.className)?defaultClassName:this.props.className);

        return (
                <React.Fragment>
                    <button
                        className={className}
                        onClick={this.handleClick}>
                            {this.buttonContent()}
                    </button>
                    <MatchSearchDialog
                        show={this.state.showDialog} />
                </React.Fragment>
        );
    }

    buttonContent() {
        var text = (odcmp.empty(this.props.text)?"Select Match":this.props.text);

        if (odcmp.empty(this.props.type) || (this.props.type.toLowerCase()=="both")) {
            return (
                {text}
            );
        } else if (this.props.type.toLowerCase()=="icon") {
            return (

            );
        } else {
            return text;
        }
    }
}

class MatchSearchDialog extends React.Component {
    constructor(props) {
        super(props);
    }

    render() {
        return (
            <ReactModal isOpen={false}>
hi
</ReactModal>
        );
    }
}


问:
How do I check if something is an elem of a qw?
According to the documentation b c d e> and qw|a b c d e| are similar, and furthermore they both make lists, which means they should be equivalent to ('a', 'b', 'c', 'd', 'e').

Why then am I not able to do this: '2' (elem) <1 2 3 4 5>?

2 (elem) <1 2 3 4 5> doesn't work either, but 'a' (elem) b c d e> DOES.

What's going on? Shouldn't I be able to check the existence of the number like anything else?

答:
So first off <…> is actually the same as:

q:w:v < … >
```

<p>Or more verbosely:</p>

<pre class="lang-raku prettyprint-override"><code>Q :single :words :val < … >
</code>```

The q or :single is how you specify the semantics of single quotes.

'abc'
q 'abc'
Q :q 'abc'
Q :single 'abc'
```

<p>The <code>:w</code> or <code>:words</code> specifies that you want the string to be split on whitespace.</p>

<pre class="lang-raku prettyprint-override"><code>Q :w     ' a b   c '    eqv    'a', 'b', 'c'
Q :words ' a b   c '    eqv    'a', 'b', 'c'
</code>```

The :v or :val specifies that you want val() semantics.

Using val will turn a string representing a number into something that is both a string and a number.

Q :v   '123'
Q :val '123'
val( '123' )
IntStr.new( 123, '123' )
```

<p>Note that you can combine <code>Q</code>, <code>q</code>, or <code>qq</code> with a single character option</p>

<pre class="lang-raku prettyprint-override"><code>qw 'a b'   =:=   q:w 'a b'  =:=  q:words 'a b'
qb 'a\n'   =:=   q:b 'a\n'  =:=  q:backslash 'a\n'
qs 'a$_'   =:=   q:s 'a$_'  =:=  q:scalar 'a$_'
</code>```

(It is probably a bug that qv'' doesn't work.)

At any rate (elem) and all Set/Bag/Mix operators deal with specific things, not generalities.

1.0    (elem)   1,2,3; # False
1      (elem)   1,2,3; # True
```

<p>So if anything is different, those operators treat them as different things.</p>

<pre class="lang-raku prettyprint-override"><code>q:v '1'   (elem)   1; # False
q:v '1'   (elem)   IntStr.new(1,'1'); # True

<1>   (elem)   1; # False
<1>   (elem)   IntStr.new(1,'1'); # True
</code>```

As we've established <1> wouldn't return an Int, it returns an IntStr.

An IntStr isn't exactly the same as an Int so it doesn't match an Int.

Presumably you want numeric things to only be numeric.

.duckmap:  -> Numeric $_ { +$_ }
```

<p>This goes through the list and anything that is already Numeric will get this function called on it.<br>
The function does only one thing, call <code>prefix:« + »</code> which calls <code>.Numeric</code> on the value.</p>

<p>Since an <code>IntStr</code> is an <code>Int</code> which does <code>Numeric</code>, the function will be called on those values.</p>

<hr>

<p>You may be wondering why <code><…></code> uses <code>val</code> semantics.</p>

<p>The reason is there is no way to know if you plan on giving it to a function that needs a <code>Str</code> or something <code>Numeric</code>.</p>

<pre class="lang-raku prettyprint-override"><code>sub foo ( Str ){}
sub bar ( Int ){}

foo <1>;
bar <1>;

foo 1;   # Failure
bar '1'; # Failure
</code>```

Body:
According to the documentation  and qw|a b c d e| are similar, and furthermore they both make lists, which means they should be equivalent to ('a', 'b', 'c', 'd', 'e').

Why then am I not able to do this: '2' (elem) <1 2 3 4 5>?

2 (elem) <1 2 3 4 5> doesn't work either, but 'a' (elem)  DOES.

What's going on? Shouldn't I be able to check the existence of the number like anything else?

Body:
So first off <…> is actually the same as:

q:w:v < … >

Or more verbosely:

Q :single :words :val < … >

The q or :single is how you specify the semantics of single quotes.

'abc'
q 'abc'
Q :q 'abc'
Q :single 'abc'

The :w or :words specifies that you want the string to be split on whitespace.

Q :w     ' a b   c '    eqv    'a', 'b', 'c'
Q :words ' a b   c '    eqv    'a', 'b', 'c'

The :v or :val specifies that you want val() semantics.

Using val will turn a string representing a number into something that is both a string and a number.

Q :v   '123'
Q :val '123'
val( '123' )
IntStr.new( 123, '123' )

Note that you can combine Q, q, or qq with a single character option

qw 'a b'   =:=   q:w 'a b'  =:=  q:words 'a b'
qb 'a\n'   =:=   q:b 'a\n'  =:=  q:backslash 'a\n'
qs 'a$_'   =:=   q:s 'a$_'  =:=  q:scalar 'a$_'

(It is probably a bug that qv'' doesn't work.)

At any rate (elem) and all Set/Bag/Mix operators deal with specific things, not generalities.

1.0    (elem)   1,2,3; # False
1      (elem)   1,2,3; # True

So if anything is different, those operators treat them as different things.

q:v '1'   (elem)   1; # False
q:v '1'   (elem)   IntStr.new(1,'1'); # True

<1>   (elem)   1; # False
<1>   (elem)   IntStr.new(1,'1'); # True

As we've established <1> wouldn't return an Int, it returns an IntStr.

An IntStr isn't exactly the same as an Int so it doesn't match an Int.

Presumably you want numeric things to only be numeric.

< a b c 1 2 3 >.duckmap:  -> Numeric $_ { +$_ }

This goes through the list and anything that is already Numeric will get this function called on it.

The function does only one thing, call prefix:« + » which calls .Numeric on the value.

Since an IntStr is an Int which does Numeric, the function will be called on those values.

You may be wondering why <…> uses val semantics.

The reason is there is no way to know if you plan on giving it to a function that needs a Str or something Numeric.

sub foo ( Str ){}
sub bar ( Int ){}

foo <1>;
bar <1>;

foo 1;   # Failure
bar '1'; # Failure


问:
AWS RDS performance is very very low
There are two databases, AWS RDS and Digitalocean $ 5 VPS.
I imported the same .sql file to both databases, the performance difference between them is almost 66000%

```<code>select count(special_cargo_id) from special_cargos;
</code>```

AWS RDS elapsed time = 35.681seconds

DO 5$ VPS on Mysql elapsed time = 0.086seconds

Details:

Table Lenght

1.85GB Rows ~260k

MySQL Version 8

Table Engine InnoDB

RDS OUTPUT

```<code>CREATE TABLE `special_cargos` (
  `special_cargo_id` int(11) NOT NULL AUTO_INCREMENT,
  `barcode` varchar(20) DEFAULT '',
  `salesCode` varchar(15) NOT NULL,
  `price` varchar(15) NOT NULL,
  `para` varchar(3) DEFAULT NULL,
  `postaceki` varchar(25) DEFAULT '',
  `iban` varchar(30) DEFAULT NULL,
  `send_type` tinyint(1) unsigned NOT NULL,
  `customer_id` int(11) NOT NULL,
  `address_id` int(11) NOT NULL,
  `height` varchar(5) DEFAULT '',
  `weight` varchar(5) DEFAULT '',
  `width` varchar(5) NOT NULL DEFAULT '',
  `desi` varchar(5) DEFAULT '',
  `length` varchar(255) DEFAULT '',
  `customer_firstname` varchar(32) NOT NULL,
  `customer_lastname` varchar(32) NOT NULL,
  `customer_company` varchar(40) NOT NULL,
  `customer_address` varchar(255) NOT NULL,
  `customer_city` int(11) NOT NULL DEFAULT '0',
  `customer_city_name` varchar(55) DEFAULT '',
  `customer_zone_id` int(11) NOT NULL DEFAULT '0',
  `customer_zone_name` varchar(55) DEFAULT '',
  `customer_postcode` varchar(10) NOT NULL,
  `firstname` varchar(32) NOT NULL,
  `lastname` varchar(32) NOT NULL,
  `company` varchar(40) DEFAULT '',
  `address` varchar(255) NOT NULL,
  `country_id` int(5) DEFAULT NULL,
  `country_name` varchar(64) DEFAULT NULL,
  `city_id` int(11) NOT NULL,
  `city_name` varchar(55) NOT NULL,
  `district_id` int(11) NOT NULL,
  `district_name` varchar(64) NOT NULL,
  `email` varchar(96) NOT NULL,
  `phone` varchar(55) NOT NULL,
  `postcode` varchar(10) DEFAULT '',
  `product` text,
  `sendText` text,
  `returnText` text,
  `created_at` datetime DEFAULT NULL,
  `updated_at` datetime DEFAULT NULL,
  `deleted_at` datetime DEFAULT NULL,
  `cargo_firm` tinyint(1) NOT NULL DEFAULT '0',
  `ups_barcode_link` text,
  `status` tinyint(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`special_cargo_id`),
  KEY `customer_id` (`customer_id`),
  KEY `special_cargo_id` (`special_cargo_id`),
  KEY `barcode` (`barcode`),
  KEY `salesCode` (`salesCode`),
  KEY `price` (`price`),
  KEY `postaceki` (`postaceki`),
  KEY `customer_firstname` (`customer_firstname`),
  KEY `customer_lastname` (`customer_lastname`),
  KEY `firstname` (`firstname`),
  KEY `lastname` (`lastname`),
  KEY `customer_company` (`customer_company`),
  KEY `customer_address` (`customer_address`),
  KEY `customer_city_name` (`customer_city_name`),
  KEY `customer_zone_name` (`customer_zone_name`),
  KEY `company` (`company`),
  KEY `address` (`address`),
  KEY `city_name` (`city_name`),
  KEY `district_name` (`district_name`),
  KEY `email` (`email`),
  KEY `phone` (`phone`),
  KEY `postcode` (`postcode`),
  KEY `index_special_cargos` (`special_cargo_id`)
) ENGINE=InnoDB AUTO_INCREMENT=497539 DEFAULT CHARSET=utf8

+-----------------------+----------+
|Variable_name          |Value     |
+-----------------------+----------+
|innodb_buffer_pool_size|1073741824|
+-----------------------+----------+

+--+-----------+--------------+----------+-----+-------------+-----------+-------+----+------+--------+-----------+
|id|select_type|table         |partitions|type |possible_keys|key        |key_len|ref |rows  |filtered|Extra      |
+--+-----------+--------------+----------+-----+-------------+-----------+-------+----+------+--------+-----------+
|1 |SIMPLE     |special_cargos|NULL      |index|NULL         |customer_id|4      |NULL|146973|100     |Using index|
+--+-----------+--------------+----------+-----+-------------+-----------+-------+----+------+--------+-----------+
</code>```

SIMPLE VPS ON MYSQL OUTPUT

```<code>CREATE TABLE `special_cargos` (
  `special_cargo_id` int(11) NOT NULL AUTO_INCREMENT,
  `barcode` varchar(20) NOT NULL,
  `salesCode` varchar(15) NOT NULL,
  `price` varchar(15) NOT NULL,
  `para` varchar(3) DEFAULT NULL,
  `postaceki` varchar(25) NOT NULL,
  `iban` varchar(30) DEFAULT NULL,
  `send_type` tinyint(1) unsigned NOT NULL,
  `customer_id` int(11) NOT NULL,
  `address_id` int(11) NOT NULL,
  `height` varchar(5) NOT NULL,
  `weight` varchar(5) NOT NULL,
  `width` varchar(5) NOT NULL,
  `desi` varchar(5) NOT NULL,
  `length` varchar(255) NOT NULL,
  `customer_firstname` varchar(32) NOT NULL,
  `customer_lastname` varchar(32) NOT NULL,
  `customer_company` varchar(40) NOT NULL,
  `customer_address` varchar(255) NOT NULL,
  `customer_city` int(11) NOT NULL,
  `customer_city_name` varchar(55) NOT NULL,
  `customer_zone_id` int(11) NOT NULL,
  `customer_zone_name` varchar(55) NOT NULL,
  `customer_postcode` varchar(10) NOT NULL,
  `firstname` varchar(32) NOT NULL,
  `lastname` varchar(32) NOT NULL,
  `company` varchar(40) NOT NULL,
  `address` varchar(255) NOT NULL,
  `country_id` int(5) DEFAULT NULL,
  `country_name` varchar(64) DEFAULT NULL,
  `city_id` int(11) NOT NULL,
  `city_name` varchar(55) NOT NULL,
  `district_id` int(11) NOT NULL,
  `district_name` varchar(64) NOT NULL,
  `email` varchar(96) NOT NULL,
  `phone` varchar(55) NOT NULL,
  `postcode` varchar(10) NOT NULL,
  `product` text,
  `sendText` text NOT NULL,
  `returnText` text NOT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` datetime NOT NULL,
  `deleted_at` datetime DEFAULT NULL,
  `cargo_firm` int(1) NOT NULL DEFAULT '0',
  `ups_barcode_link` text,
  `status` int(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`special_cargo_id`),
  KEY `customer_id` (`customer_id`),
  KEY `special_cargo_id` (`special_cargo_id`),
  KEY `barcode` (`barcode`),
  KEY `salesCode` (`salesCode`),
  KEY `price` (`price`),
  KEY `postaceki` (`postaceki`),
  KEY `customer_firstname` (`customer_firstname`),
  KEY `customer_lastname` (`customer_lastname`),
  KEY `firstname` (`firstname`),
  KEY `lastname` (`lastname`),
  KEY `customer_company` (`customer_company`),
  KEY `customer_address` (`customer_address`),
  KEY `customer_city_name` (`customer_city_name`),
  KEY `customer_zone_name` (`customer_zone_name`),
  KEY `company` (`company`),
  KEY `address` (`address`),
  KEY `city_name` (`city_name`),
  KEY `district_name` (`district_name`),
  KEY `email` (`email`),
  KEY `phone` (`phone`),
  KEY `postcode` (`postcode`)
) ENGINE=InnoDB AUTO_INCREMENT=497037 DEFAULT CHARSET=utf8

+-----------------------+---------+
|Variable_name          |Value    |
+-----------------------+---------+
|innodb_buffer_pool_size|134217728|
+-----------------------+---------+

+--+-----------+--------------+----------+-----+-------------+-----------+-------+----+------+--------+-----------+
|id|select_type|table         |partitions|type |possible_keys|key        |key_len|ref |rows  |filtered|Extra      |
+--+-----------+--------------+----------+-----+-------------+-----------+-------+----+------+--------+-----------+
|1 |SIMPLE     |special_cargos|NULL      |index|NULL         |customer_id|4      |NULL|133967|100     |Using index|
+--+-----------+--------------+----------+-----+-------------+-----------+-------+----+------+--------+-----------+
</code>```

答:
There are two aspects of the problem here.
Aspect one and more important IMO is the query - it's bad. It does full index scan (yes, PRIMARY is also an index). Its performance scales linearly vs better and desired the B+tree's nlog(n).

Aspect two. Why the difference in the execution time. It can be related to caching (in DO's case the query was served from the buffer pool while in RDS from disk(=EBS)). It can be related to MySQL optimizer (DO and RDS could pick different indexes to serve the query PRIMARY vs smaller secondary index). But all that doesn't matter much due to the problems with the query itself.

Title: AWS RDS performance is very very low

Body:
There are two databases, AWS RDS and Digitalocean $ 5 VPS.
I imported the same .sql file to both databases, the performance difference between them is almost 66000%

select count(special_cargo_id) from special_cargos;

AWS RDS elapsed time = 35.681seconds

DO 5$ VPS on Mysql elapsed time = 0.086seconds

Details:

Table Lenght

1.85GB Rows ~260k

MySQL Version 8

Table Engine InnoDB

RDS OUTPUT

CREATE TABLE `special_cargos` (
  `special_cargo_id` int(11) NOT NULL AUTO_INCREMENT,
  `barcode` varchar(20) DEFAULT '',
  `salesCode` varchar(15) NOT NULL,
  `price` varchar(15) NOT NULL,
  `para` varchar(3) DEFAULT NULL,
  `postaceki` varchar(25) DEFAULT '',
  `iban` varchar(30) DEFAULT NULL,
  `send_type` tinyint(1) unsigned NOT NULL,
  `customer_id` int(11) NOT NULL,
  `address_id` int(11) NOT NULL,
  `height` varchar(5) DEFAULT '',
  `weight` varchar(5) DEFAULT '',
  `width` varchar(5) NOT NULL DEFAULT '',
  `desi` varchar(5) DEFAULT '',
  `length` varchar(255) DEFAULT '',
  `customer_firstname` varchar(32) NOT NULL,
  `customer_lastname` varchar(32) NOT NULL,
  `customer_company` varchar(40) NOT NULL,
  `customer_address` varchar(255) NOT NULL,
  `customer_city` int(11) NOT NULL DEFAULT '0',
  `customer_city_name` varchar(55) DEFAULT '',
  `customer_zone_id` int(11) NOT NULL DEFAULT '0',
  `customer_zone_name` varchar(55) DEFAULT '',
  `customer_postcode` varchar(10) NOT NULL,
  `firstname` varchar(32) NOT NULL,
  `lastname` varchar(32) NOT NULL,
  `company` varchar(40) DEFAULT '',
  `address` varchar(255) NOT NULL,
  `country_id` int(5) DEFAULT NULL,
  `country_name` varchar(64) DEFAULT NULL,
  `city_id` int(11) NOT NULL,
  `city_name` varchar(55) NOT NULL,
  `district_id` int(11) NOT NULL,
  `district_name` varchar(64) NOT NULL,
  `email` varchar(96) NOT NULL,
  `phone` varchar(55) NOT NULL,
  `postcode` varchar(10) DEFAULT '',
  `product` text,
  `sendText` text,
  `returnText` text,
  `created_at` datetime DEFAULT NULL,
  `updated_at` datetime DEFAULT NULL,
  `deleted_at` datetime DEFAULT NULL,
  `cargo_firm` tinyint(1) NOT NULL DEFAULT '0',
  `ups_barcode_link` text,
  `status` tinyint(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`special_cargo_id`),
  KEY `customer_id` (`customer_id`),
  KEY `special_cargo_id` (`special_cargo_id`),
  KEY `barcode` (`barcode`),
  KEY `salesCode` (`salesCode`),
  KEY `price` (`price`),
  KEY `postaceki` (`postaceki`),
  KEY `customer_firstname` (`customer_firstname`),
  KEY `customer_lastname` (`customer_lastname`),
  KEY `firstname` (`firstname`),
  KEY `lastname` (`lastname`),
  KEY `customer_company` (`customer_company`),
  KEY `customer_address` (`customer_address`),
  KEY `customer_city_name` (`customer_city_name`),
  KEY `customer_zone_name` (`customer_zone_name`),
  KEY `company` (`company`),
  KEY `address` (`address`),
  KEY `city_name` (`city_name`),
  KEY `district_name` (`district_name`),
  KEY `email` (`email`),
  KEY `phone` (`phone`),
  KEY `postcode` (`postcode`),
  KEY `index_special_cargos` (`special_cargo_id`)
) ENGINE=InnoDB AUTO_INCREMENT=497539 DEFAULT CHARSET=utf8

+-----------------------+----------+
|Variable_name          |Value     |
+-----------------------+----------+
|innodb_buffer_pool_size|1073741824|
+-----------------------+----------+

+--+-----------+--------------+----------+-----+-------------+-----------+-------+----+------+--------+-----------+
|id|select_type|table         |partitions|type |possible_keys|key        |key_len|ref |rows  |filtered|Extra      |
+--+-----------+--------------+----------+-----+-------------+-----------+-------+----+------+--------+-----------+
|1 |SIMPLE     |special_cargos|NULL      |index|NULL         |customer_id|4      |NULL|146973|100     |Using index|
+--+-----------+--------------+----------+-----+-------------+-----------+-------+----+------+--------+-----------+

SIMPLE VPS ON MYSQL OUTPUT

CREATE TABLE `special_cargos` (
  `special_cargo_id` int(11) NOT NULL AUTO_INCREMENT,
  `barcode` varchar(20) NOT NULL,
  `salesCode` varchar(15) NOT NULL,
  `price` varchar(15) NOT NULL,
  `para` varchar(3) DEFAULT NULL,
  `postaceki` varchar(25) NOT NULL,
  `iban` varchar(30) DEFAULT NULL,
  `send_type` tinyint(1) unsigned NOT NULL,
  `customer_id` int(11) NOT NULL,
  `address_id` int(11) NOT NULL,
  `height` varchar(5) NOT NULL,
  `weight` varchar(5) NOT NULL,
  `width` varchar(5) NOT NULL,
  `desi` varchar(5) NOT NULL,
  `length` varchar(255) NOT NULL,
  `customer_firstname` varchar(32) NOT NULL,
  `customer_lastname` varchar(32) NOT NULL,
  `customer_company` varchar(40) NOT NULL,
  `customer_address` varchar(255) NOT NULL,
  `customer_city` int(11) NOT NULL,
  `customer_city_name` varchar(55) NOT NULL,
  `customer_zone_id` int(11) NOT NULL,
  `customer_zone_name` varchar(55) NOT NULL,
  `customer_postcode` varchar(10) NOT NULL,
  `firstname` varchar(32) NOT NULL,
  `lastname` varchar(32) NOT NULL,
  `company` varchar(40) NOT NULL,
  `address` varchar(255) NOT NULL,
  `country_id` int(5) DEFAULT NULL,
  `country_name` varchar(64) DEFAULT NULL,
  `city_id` int(11) NOT NULL,
  `city_name` varchar(55) NOT NULL,
  `district_id` int(11) NOT NULL,
  `district_name` varchar(64) NOT NULL,
  `email` varchar(96) NOT NULL,
  `phone` varchar(55) NOT NULL,
  `postcode` varchar(10) NOT NULL,
  `product` text,
  `sendText` text NOT NULL,
  `returnText` text NOT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` datetime NOT NULL,
  `deleted_at` datetime DEFAULT NULL,
  `cargo_firm` int(1) NOT NULL DEFAULT '0',
  `ups_barcode_link` text,
  `status` int(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`special_cargo_id`),
  KEY `customer_id` (`customer_id`),
  KEY `special_cargo_id` (`special_cargo_id`),
  KEY `barcode` (`barcode`),
  KEY `salesCode` (`salesCode`),
  KEY `price` (`price`),
  KEY `postaceki` (`postaceki`),
  KEY `customer_firstname` (`customer_firstname`),
  KEY `customer_lastname` (`customer_lastname`),
  KEY `firstname` (`firstname`),
  KEY `lastname` (`lastname`),
  KEY `customer_company` (`customer_company`),
  KEY `customer_address` (`customer_address`),
  KEY `customer_city_name` (`customer_city_name`),
  KEY `customer_zone_name` (`customer_zone_name`),
  KEY `company` (`company`),
  KEY `address` (`address`),
  KEY `city_name` (`city_name`),
  KEY `district_name` (`district_name`),
  KEY `email` (`email`),
  KEY `phone` (`phone`),
  KEY `postcode` (`postcode`)
) ENGINE=InnoDB AUTO_INCREMENT=497037 DEFAULT CHARSET=utf8

+-----------------------+---------+
|Variable_name          |Value    |
+-----------------------+---------+
|innodb_buffer_pool_size|134217728|
+-----------------------+---------+

+--+-----------+--------------+----------+-----+-------------+-----------+-------+----+------+--------+-----------+
|id|select_type|table         |partitions|type |possible_keys|key        |key_len|ref |rows  |filtered|Extra      |
+--+-----------+--------------+----------+-----+-------------+-----------+-------+----+------+--------+-----------+
|1 |SIMPLE     |special_cargos|NULL      |index|NULL         |customer_id|4      |NULL|133967|100     |Using index|
+--+-----------+--------------+----------+-----+-------------+-----------+-------+----+------+--------+-----------+


问:
How can I re-import DeliveryAPI result in kentico kontent
I want to try kontent-sample-blog-travel-vue project in github, and it has JSON contents under 'sample-data' directory in Delivery API format.

I made my new Kontent project, and try to use ManagementAPI to import json, but it becomes error because of wrong JSON format.

Please tell me how can I re-import JSON, which exported in Delivery API format.

答:
you are right, to import data from Delivery API to Management API, you need to make the transformations.

I have started with the pull request, which should guide people on how to import data using backup manager CLI, or via template manager UI.

Once the pull request is merged, I will update this answer.

EDIT:

OK, the pull request is closed and now the Vue travel blog sample site is ready to be used as a template.

In the readme, you can find instructions on how to create your own Kontent project as data source.

If you have any more questions/issues, feel free to submit an issue (or pull request) right in the repository.

This repository was also submitted as one of the templates in the Kontent template manager.


问:
How to split and concatenate a string
I have a filename in a string. I want to split the given string into 2 (1 is filename without extension, 2 is only extension) strings. Then add _dev to the end of first string and concatenate with 2nd one.

ex:

```<code>Dim name as string="abc.txt"
Dim finalName as string
</code>```

The finalName should be like this "abc_dev.txt"

Any suggestions please?

答:
If they're really filenames:</p>

```<code> ' unested, likely to contain spelling errors
 name = Path.GetFileNameWithoutExtension(oldName)
 ext = Path.GetExtension(oldName)
 newName = odlName & "_dev"
 newName = Path.ChangeExtension(newName, ext)
</code>```

Title: How to split and concatenate a string

Body:
I have a filename in a string. I want to split the given string into 2 (1 is filename without extension, 2 is only extension) strings. Then add _dev to the end of first string and concatenate with 2nd one.

ex:

Dim name as string="abc.txt"
Dim finalName as string

The finalName should be like this "abc_dev.txt"

Any suggestions please?

Body:
If they're really filenames:

 ' unested, likely to contain spelling errors
 name = Path.GetFileNameWithoutExtension(oldName)
 ext = Path.GetExtension(oldName)
 newName = odlName & "_dev"
 newName = Path.ChangeExtension(newName, ext)


问:
Can't push old elements up one place in an array
I am trying to create a method where I enter a number and it replaces the first array element. However after that I want the older array values to be pushed to the next size.
Like old values {1,2,3,4}
New values after inputting 10 in this method: {10,1,2,3}.
I do not understand where I am going wrong.
Here list is the name of the array.  </p>

```<code> public void insertFirst(int newElement)
    {
        int temp = 0;
        list[0]= newElement;

        for(int y= 1; y<list.length-1;y++){
            list[y+1] = list[y];
        }

    }
</code>```

答:
You are iterating from 1 which will give you 2 with list[y] so you need to iterate from the end and copy the elements accordingly.

```<code>    // move the elements from end
    for(int y = list.length-1; y> 0; y--){
        list[y] = list[y-1];
    }
</code>```

In the end, put the new element at the first position.

```<code>    // put the new element at the beginning
    list[0] = newElement;
</code>```

Live Demo

Body:
I am trying to create a method where I enter a number and it replaces the first array element. However after that I want the older array values to be pushed to the next size.
Like old values {1,2,3,4}
New values after inputting 10 in this method: {10,1,2,3}.
I do not understand where I am going wrong.
Here list is the name of the array.

 public void insertFirst(int newElement)
    {
        int temp = 0;
        list[0]= newElement;

        for(int y= 1; y<list.length-1;y++){
            list[y+1] = list[y];
        }

    }

Body:
You are iterating from 1 which will give you 2 with list[y] so you need to iterate from the end and copy the elements accordingly.

    // move the elements from end
    for(int y = list.length-1; y> 0; y--){
        list[y] = list[y-1];
    }

In the end, put the new element at the first position.

    // put the new element at the beginning
    list[0] = newElement;

Live Demo


问:
TypeChecker API: How do I find inferred type arguments to a function?
Is there any way to, given a CallExpression with inferred type arguments, find what those type arguments are?

Example code:

```<code>class SomeClass {
    public someMethod<T>(arg: T): void { }
}

// What is the inferred type of T in this call?
someClass.someMethod(7);
</code>```

It's easy enough to find type arguments that were explicitly assigned in the code, but I can't figure out how to find what was inferred.

```<code>function inferTypeArguments(node: ts.CallExpression, typeChecker: ts.TypeChecker) {
    node.typeArguments; // is empty
    const signature = typeChecker.getResolvedSignature(node);
    signature['typeArguments']; // is also empty

    // This returns "<number>(arg: number): void"
    // so I know that the typeChecker has the right information,
    // but I would really like a ts.Type[]
    typeChecker.signatureToString(signature, node, ts.TypeFormatFlags.WriteTypeArgumentsOfSignature)
}
</code>```

答:
I'd been using Simon's code for a while in my transpiler... then 3.9 came along and broke it. I've done a preliminary attempt to get it working again. Unfortunately, the mapper is an "internal" concern for typescript, so this will likely change again in the future</p>

```<code>/* @internal - from typescript 3.9 codebase*/
const enum TypeMapKind {
  Simple,
  Array,
  Function,
  Composite,
  Merged,
}

/* @internal - from typescript 3.9 codebase*/
type TypeMapper =
  | { kind: TypeMapKind.Simple, source: ts.Type, target: ts.Type }
  | { kind: TypeMapKind.Array, sources: readonly ts.Type[], targets: readonly ts.Type[] | undefined }
  | { kind: TypeMapKind.Function, func: (t: ts.Type) => ts.Type }
  | { kind: TypeMapKind.Composite | TypeMapKind.Merged, mapper1: TypeMapper, mapper2: TypeMapper };

/* basic application of the mapper - recursive for composite.*/
function typeMapper(mapper:TypeMapper, source: ts.Type): ts.Type {
  switch(mapper.kind){
    case TypeMapKind.Simple:
      return mapper.target;
    case TypeMapKind.Array:
      throw Error("not implemented");
    case TypeMapKind.Function:
      return mapper.func(source);
    case TypeMapKind.Composite:
    case TypeMapKind.Merged:
      return typeMapper(mapper.mapper2, source);
  }
}

function inferTypeArguments(node: ts.CallExpression, typeChecker: ts.TypeChecker): ts.Type[] {
  const signature:ts.Signature = typeChecker.getResolvedSignature(node);
  const targetParams: ts.TypeParameter[] = signature['target'] && signature['target'].typeParameters;

  if (!targetParams) {
    return [];
  }

  if(signature['mapper'] == undefined)
    return targetParams;

  //typescript <= 3.8
  if(typeof signature['mapper'] == "function")
    return targetParams.map(p=>signature['mapper'](p));
  //typescript >= 3.9....
  return targetParams.map(p=> typeMapper(signature['mapper'] as TypeMapper, p));
}
</code>```

Body:
Is there any way to, given a CallExpression with inferred type arguments, find what those type arguments are?

Example code:

class SomeClass {
    public someMethod<T>(arg: T): void { }
}

// What is the inferred type of T in this call?
someClass.someMethod(7);

It's easy enough to find type arguments that were explicitly assigned in the code, but I can't figure out how to find what was inferred.

function inferTypeArguments(node: ts.CallExpression, typeChecker: ts.TypeChecker) {
    node.typeArguments; // is empty
    const signature = typeChecker.getResolvedSignature(node);
    signature['typeArguments']; // is also empty

    // This returns "<number>(arg: number): void"
    // so I know that the typeChecker has the right information,
    // but I would really like a ts.Type[]
    typeChecker.signatureToString(signature, node, ts.TypeFormatFlags.WriteTypeArgumentsOfSignature)
}

Body:
I'd been using Simon's code for a while in my transpiler... then 3.9 came along and broke it. I've done a preliminary attempt to get it working again. Unfortunately, the mapper is an "internal" concern for typescript, so this will likely change again in the future

/* @internal - from typescript 3.9 codebase*/
const enum TypeMapKind {
  Simple,
  Array,
  Function,
  Composite,
  Merged,
}

/* @internal - from typescript 3.9 codebase*/
type TypeMapper =
  | { kind: TypeMapKind.Simple, source: ts.Type, target: ts.Type }
  | { kind: TypeMapKind.Array, sources: readonly ts.Type[], targets: readonly ts.Type[] | undefined }
  | { kind: TypeMapKind.Function, func: (t: ts.Type) => ts.Type }
  | { kind: TypeMapKind.Composite | TypeMapKind.Merged, mapper1: TypeMapper, mapper2: TypeMapper };

/* basic application of the mapper - recursive for composite.*/
function typeMapper(mapper:TypeMapper, source: ts.Type): ts.Type {
  switch(mapper.kind){
    case TypeMapKind.Simple:
      return mapper.target;
    case TypeMapKind.Array:
      throw Error("not implemented");
    case TypeMapKind.Function:
      return mapper.func(source);
    case TypeMapKind.Composite:
    case TypeMapKind.Merged:
      return typeMapper(mapper.mapper2, source);
  }
}

function inferTypeArguments(node: ts.CallExpression, typeChecker: ts.TypeChecker): ts.Type[] {
  const signature:ts.Signature = typeChecker.getResolvedSignature(node);
  const targetParams: ts.TypeParameter[] = signature['target'] && signature['target'].typeParameters;

  if (!targetParams) {
    return [];
  }

  if(signature['mapper'] == undefined)
    return targetParams;

  //typescript <= 3.8
  if(typeof signature['mapper'] == "function")
    return targetParams.map(p=>signature['mapper'](p));
  //typescript >= 3.9....
  return targetParams.map(p=> typeMapper(signature['mapper'] as TypeMapper, p));
}


问:
SMTP ERROR: Failed to connect to server: (0) SMTP connect() failed
I am trying to send an email using Mailer but getting below error

Connection: opening 2017-05-25 08:22:07   SMTP ERROR: Failed to connect
  to server: (0) SMTP connect() failed. Mailer Error: SMTP connect()
  failed.

php_openssl extension & IMAP both are enabled. I tried to find it on google but still no luck.

Code:

```<code>function sendMail($subject='',$to='',$emailcontent='',$attach='')
{
    global $_mailmsg;
    //echo $emailcontent;exit;
    $mail = new PHPMailer;
    $mail->SMTPDebug = 4;
    $mail->isSMTP();
    $mail->Host = 'smtp.gmail.com';
    $mail->Port = '465';
    $mail->SMTPAuth = true;
    $mail->Username = 'xx@gmail.com';
    $mail->Password = 'xxxx';
    $mail->SMTPSecure = 'ssl';
    $mail->From = 'xx@gmail.com';
    $mail->FromName = 'Test';
    $mail->addAddress($to);  // Add a recipient
    if(!empty($cc)){    $mail->addCC($cc); }
    if(!empty($bcc)){   $mail->addBCC($bcc);    }

    $mail->WordWrap = 50;
    if($attach != ''){
        $mail->addAttachment($attach);
    }
    //$mail->addAttachment('/tmp/image.jpg', 'new.jpg');
    $mail->isHTML(true);
    $mail->Subject = $subject;
    $mail->Body    = 'Test';
    try
    {
        if($mail->send()) {
            return 1;
           exit;
        }
        else
        {
            echo 'Mailer Error: ' . $mail->ErrorInfo;
            return 0;
        }
    }
    catch(Exception $e)
    {
        return 0;
    }
}
</code>```

答:
As you are using Gmail, just turn on "Allow less secure apps":

https://myaccount.google.com/u/0/lesssecureapps

And also you'll probably need to allow access to your Google account without unlock captcha:

https://accounts.google.com/DisplayUnlockCaptcha

Body:
I am trying to send an email using Mailer but getting below error

Connection: opening 2017-05-25 08:22:07   SMTP ERROR: Failed to connect
  to server: (0) SMTP connect() failed. Mailer Error: SMTP connect()
  failed.

php_openssl extension & IMAP both are enabled. I tried to find it on google but still no luck.

Code:

function sendMail($subject='',$to='',$emailcontent='',$attach='')
{
    global $_mailmsg;
    //echo $emailcontent;exit;
    $mail = new PHPMailer;
    $mail->SMTPDebug = 4;
    $mail->isSMTP();
    $mail->Host = 'smtp.gmail.com';
    $mail->Port = '465';
    $mail->SMTPAuth = true;
    $mail->Username = 'xx@gmail.com';
    $mail->Password = 'xxxx';
    $mail->SMTPSecure = 'ssl';
    $mail->From = 'xx@gmail.com';
    $mail->FromName = 'Test';
    $mail->addAddress($to);  // Add a recipient
    if(!empty($cc)){    $mail->addCC($cc); }
    if(!empty($bcc)){   $mail->addBCC($bcc);    }

    $mail->WordWrap = 50;
    if($attach != ''){
        $mail->addAttachment($attach);
    }
    //$mail->addAttachment('/tmp/image.jpg', 'new.jpg');
    $mail->isHTML(true);
    $mail->Subject = $subject;
    $mail->Body    = 'Test';
    try
    {
        if($mail->send()) {
            return 1;
           exit;
        }
        else
        {
            echo 'Mailer Error: ' . $mail->ErrorInfo;
            return 0;
        }
    }
    catch(Exception $e)
    {
        return 0;
    }
}


问:
How can I get a particular part of a String enclosed between 2 characters using Excel VBA?
I need to write a macro in excel which can help me get a particular part of a string. My string is as follows :

PAYPAL *VINAYAKAGGRAWAL 4029357733

I need to extract VINAYAKAGGRAWAL from the above string. Any help with vba macro or any excel formula to do this would help.

Thanks in advance.

答:
Something like:</p>

```<code>Sub parser()
    Dim s As String, s2 As String, s3 As String
    s = "PAYPAL *VINAYAKAGGRAWAL 4029357733"
    s2 = Mid(s, InStr(1, s, "*") + 1)
    s3 = Left(s2, InStr(1, s2, " "))
    MsgBox s3
End Sub
</code>```

Body:
Something like:

Sub parser()
    Dim s As String, s2 As String, s3 As String
    s = "PAYPAL *VINAYAKAGGRAWAL 4029357733"
    s2 = Mid(s, InStr(1, s, "*") + 1)
    s3 = Left(s2, InStr(1, s2, " "))
    MsgBox s3
End Sub


答:
How about </p>

```<code>finalName = Path.GetFileNameWithoutExtension(name) & "_dev" & Path.GetExtension(name)
</code>```

Title: How to split and concatenate a string

Body:
How about

finalName = Path.GetFileNameWithoutExtension(name) & "_dev" & Path.GetExtension(name)


问:
ng2-tel-input: Country flag do not change automatically when manually change input
I use ng2-tel-input with reactive form method (Angular).

Issue:

When i open flag dropdown and choose a value, it is working fine.
Value is displayed into input correctly but country flag do not change and the default flag appear.

When I change value manually in input then flag changes automatically, otherwise default country flag displaying.

Example:

Value format: +917878747474

Selected country: India

Default country: us

when i press on set value. phone no set on input but flag remain same

html

```<code> <form [formGroup]="form">
        <small class="phone-text">{{ placeHolder }}</small>
        <md-input-container class="full-width pt-0">
            <input type="text"
                   mdInput
                   formControlName="phone"
                   ng2TelInput
                   [ng2TelInputOptions]="{initialCountry: initialCountry}"
                   (hasError)="hasError($event)"
                   (ng2TelOutput)="hasOutPut($event)"
                   #phoneInput
                   maxlength="45"/>
        </md-input-container>
       <button type="button" (click)="setValue()">Set Value</button>
    </form>
</code>```

Component

```<code>import {Attribute, Component, forwardRef, Input} from '@angular/core';
import {FormBuilder, FormGroup} from '@angular/forms';

@Component({
    selector: 'app-phone',
    templateUrl: './phone.component.html',
    styleUrls: ['./phone.component.scss']
})
export class PhoneComponent implements ControlValueAccessor, Validator {
    placeHolder = 'Default Value';
    initialCountry = 'us';
    form: FormGroup;

    constructor(private _fb: FormBuilder) {
        this._initForm();
    }

    setValue(): void {
        const phone = '+917878747416'
        this.form.setValue({phone: phone});
    }

    private _initForm(): void {
        this.form = this._fb.group({
            'phone': ['']
        });
    }

    hasError(event: any): void {
        if (!event && this.form.value.phone !== '') {
            this.form.get('phone').setErrors(['invalid_cell_phone', true]);
        }
    }

    hasOutPut(event: any): void {
        this.form.patchValue({phone: event});
    }
}
</code>```

Any help would be appreciated.

答:
This is crazy hack but worked:

So, if you just want to change the flag based on the input value, the component itself already detects keyup events and sets the flag based on the dialCode (e.g. if you start typing "+49", it would set the German flag).

Based on that, if you set the input field programmatically, it will not detect this keyup event, so I decided to hack it.

This answer helped me how to do that:
Trigger keyup event in Angular 5 TypeScript

Bind your input with ViewChild:

```<code>@ViewChild('phoneInput')
phoneInput: ElementRef;
</code>```

Trigger a fake keyup event:

```<code>setValue(): void {
  const phone = '+917878747416'
  this.form.setValue({phone: phone});
  this.phoneInput.nativeElement.dispatchEvent(
    new KeyboardEvent('keyup', { bubbles: true })
  );
}
</code>```

Worked out pretty smoothly for me.

Body:
I use ng2-tel-input with reactive form method (Angular).

Issue:

When i open flag dropdown and choose a value, it is working fine.
Value is displayed into input correctly but country flag do not change and the default flag appear.

When I change value manually in input then flag changes automatically, otherwise default country flag displaying.

Example:

Value format: +917878747474

Selected country: India

Default country: us

when i press on set value. phone no set on input but flag remain same

html

 <form [formGroup]="form">
        {{ placeHolder }}
        <md-input-container class="full-width pt-0">
            <input type="text"
                   mdInput
                   formControlName="phone"
                   ng2TelInput
                   [ng2TelInputOptions]="{initialCountry: initialCountry}"
                   (hasError)="hasError($event)"
                   (ng2TelOutput)="hasOutPut($event)"
                   #phoneInput
                   maxlength="45"/>
        </md-input-container>
       <button type="button" (click)="setValue()">Set Value</button>
    </form>

Component

import {Attribute, Component, forwardRef, Input} from '@angular/core';
import {FormBuilder, FormGroup} from '@angular/forms';

@Component({
    selector: 'app-phone',
    templateUrl: './phone.component.html',
    styleUrls: ['./phone.component.scss']
})
export class PhoneComponent implements ControlValueAccessor, Validator {
    placeHolder = 'Default Value';
    initialCountry = 'us';
    form: FormGroup;

    constructor(private _fb: FormBuilder) {
        this._initForm();
    }

    setValue(): void {
        const phone = '+917878747416'
        this.form.setValue({phone: phone});
    }

    private _initForm(): void {
        this.form = this._fb.group({
            'phone': ['']
        });
    }

    hasError(event: any): void {
        if (!event && this.form.value.phone !== '') {
            this.form.get('phone').setErrors(['invalid_cell_phone', true]);
        }
    }

    hasOutPut(event: any): void {
        this.form.patchValue({phone: event});
    }
}

Any help would be appreciated.

Body:
This is crazy hack but worked:

So, if you just want to change the flag based on the input value, the component itself already detects keyup events and sets the flag based on the dialCode (e.g. if you start typing "+49", it would set the German flag).

Based on that, if you set the input field programmatically, it will not detect this keyup event, so I decided to hack it.

This answer helped me how to do that:
Trigger keyup event in Angular 5 TypeScript

Bind your input with ViewChild:

@ViewChild('phoneInput')
phoneInput: ElementRef;

Trigger a fake keyup event:

setValue(): void {
  const phone = '+917878747416'
  this.form.setValue({phone: phone});
  this.phoneInput.nativeElement.dispatchEvent(
    new KeyboardEvent('keyup', { bubbles: true })
  );
}

Worked out pretty smoothly for me.


问:
Keras - accuracy for multi-output model is not working
An important concern in the case of multi-output models is that the training of such a model requires the ability to specify different metrics for different heads (outputs) of the network.

As mentioned in the official documentation:

To specify different metrics for different outputs of a multi-output model, you could also pass a dictionary, such as metrics={'output_a': 'accuracy'}

For my model, I am doing something similar with the following :

```<code>metrics ={'output_a': 'crossentropy',
          'output_b': 'mse',
          'output_c': 'mse',
          'output_d': 'mse',
          'output_e': 'categorical_accuracy'}
</code>```

But when I start training the model, the overall accuracy is nowhere to be seen at the logs, while the loss and the val_loss are visible.

So my questions are:

Do val and val_loss imply the overall loss and overall validation loss of the model respectively?

Is it possible to have the acc of the model printed as well?

答:
I will answer the 2nd part as 1st is already answered.

Yes, we can print the validation accuracy by creating a custom callback and overriding the on_epoch_end function. In the on_epoch_end we can access the logs which is the dictionary of metric_name: values.

For example -

I have a 13 output model.

```<code>    class CustomCallbacks(tf.keras.callbacks.Callback):
      def on_epoch_end(self, epoch, logs={}):
        val_acc = 0
        for i in range(13):
          val_acc += (logs.get('val_digit_{}_accuracy'.format(i)))/13 # take mean acc value
        print("mean val acc -  ",val_acc)

</code>```

Body:
An important concern in the case of multi-output models is that the training of such a model requires the ability to specify different metrics for different heads (outputs) of the network.

As mentioned in the official documentation:

To specify different metrics for different outputs of a multi-output model, you could also pass a dictionary, such as metrics={'output_a': 'accuracy'}

For my model, I am doing something similar with the following :

metrics ={'output_a': 'crossentropy',
          'output_b': 'mse',
          'output_c': 'mse',
          'output_d': 'mse',
          'output_e': 'categorical_accuracy'}

But when I start training the model, the overall accuracy is nowhere to be seen at the logs, while the loss and the val_loss are visible.

So my questions are:

Do val and val_loss imply the overall loss and overall validation loss of the model respectively?

Is it possible to have the acc of the model printed as well?

Body:
I will answer the 2nd part as 1st is already answered.

Yes, we can print the validation accuracy by creating a custom callback and overriding the on_epoch_end function. In the on_epoch_end we can access the logs which is the dictionary of metric_name: values.

For example -

I have a 13 output model.

    class CustomCallbacks(tf.keras.callbacks.Callback):
      def on_epoch_end(self, epoch, logs={}):
        val_acc = 0
        for i in range(13):
          val_acc += (logs.get('val_digit_{}_accuracy'.format(i)))/13 # take mean acc value
        print("mean val acc -  ",val_acc)