问:
Why/how some packages define their functions in nameless environment?
In my code, I needed to check which package the function is defined from (in my case it was exprs(): I needed it from Biobase but it turned out to be overriden by rlang).

From this SO question, I thought I could use simply environmentName(environment(functionname)). But for exprs from Biobase that expression returned empty string:

```<code>environmentName(environment(exprs))
# [1] ""
</code>```

After checking the structure of environment(exprs) I noticed that it has .Generic member which contains package name as an attribute:

```<code>environment(exprs)$.Generic
# [1] "exprs"
# attr(,"package")
# [1] "Biobase"
</code>```

So, for now I made this helper function:

```<code>pkgparent <- function(functionObj) {
  functionEnv <- environment(functionObj)
  envName <- environmentName(functionEnv)
  if (envName!="")
    return(envName) else
      return(attr(functionEnv$.Generic,'package'))
}
</code>```

It does the job and correctly returns package name for the function if it is loaded, for example:

```<code>pkgparent(exprs)
# Error in environment(functionObj) : object 'exprs' not found

library(Biobase)

pkgparent(exprs)
# [1] "Biobase"

library(rlang)
# The following object is masked from ‘package:Biobase’:
#   exprs

pkgparent(exprs)
# [1] "rlang"
</code>```

But I still would like to learn how does it happen that for some packages their functions are defined in "unnamed" environment while others will look like <environment: namespace:packagename>.

答:
What you’re seeing here is part of how S4 method dispatch works. In fact, .Generic is part of the R method dispatch mechanism.

The rlang package is a red herring, by the way: the issue presents itself purely due to Biobase’s use of S4.

But more generally your resolution strategy might fail in other situations, because there are other reasons (albeit rarely) why packages might define functions inside a separate environment. The reason for this is generally to define a closure over some variable.

For example, it’s generally impossible to modify variables defined inside a package at the namespace level, because the namespace gets locked when loaded. There are multiple ways to work around this. A simple way, if a package needs a stateful function, is to define this function inside an environment. For example, you could define a counter function that increases its count on each invocation as follows:

```<code>counter = local({
    current = 0L

    function () {
        current <<- current + 1L
        current
    }
})
</code>```

local defines an environment in which the function is wrapped.

To cope with this kind of situation, what you should do instead is to iterate over parent environments until you find a namespace environment. But there’s a simpler solution, because R already provides a function to find a namespace environment for a given environment (by performing said iteration):

```<code>pkgparent = function (fun) {
    nsenv = topenv(environment(fun))
    environmentName(nsenv)
}
</code>```

Body:
In my code, I needed to check which package the function is defined from (in my case it was exprs(): I needed it from Biobase but it turned out to be overriden by rlang).

From this SO question, I thought I could use simply environmentName(environment(functionname)). But for exprs from Biobase that expression returned empty string:

environmentName(environment(exprs))
# [1] ""

After checking the structure of environment(exprs) I noticed that it has .Generic member which contains package name as an attribute:

environment(exprs)$.Generic
# [1] "exprs"
# attr(,"package")
# [1] "Biobase"

So, for now I made this helper function:

pkgparent <- function(functionObj) {
  functionEnv <- environment(functionObj)
  envName <- environmentName(functionEnv)
  if (envName!="")
    return(envName) else
      return(attr(functionEnv$.Generic,'package'))
}

It does the job and correctly returns package name for the function if it is loaded, for example:

pkgparent(exprs)
# Error in environment(functionObj) : object 'exprs' not found

library(Biobase)

pkgparent(exprs)
# [1] "Biobase"

library(rlang)
# The following object is masked from ‘package:Biobase’:
#   exprs

pkgparent(exprs)
# [1] "rlang"

But I still would like to learn how does it happen that for some packages their functions are defined in "unnamed" environment while others will look like <environment: namespace:packagename>.

Body:
What you’re seeing here is part of how S4 method dispatch works. In fact, .Generic is part of the R method dispatch mechanism.

The rlang package is a red herring, by the way: the issue presents itself purely due to Biobase’s use of S4.

But more generally your resolution strategy might fail in other situations, because there are other reasons (albeit rarely) why packages might define functions inside a separate environment. The reason for this is generally to define a closure over some variable.

For example, it’s generally impossible to modify variables defined inside a package at the namespace level, because the namespace gets locked when loaded. There are multiple ways to work around this. A simple way, if a package needs a stateful function, is to define this function inside an environment. For example, you could define a counter function that increases its count on each invocation as follows:

counter = local({
    current = 0L

    function () {
        current <<- current + 1L
        current
    }
})

local defines an environment in which the function is wrapped.

To cope with this kind of situation, what you should do instead is to iterate over parent environments until you find a namespace environment. But there’s a simpler solution, because R already provides a function to find a namespace environment for a given environment (by performing said iteration):

pkgparent = function (fun) {
    nsenv = topenv(environment(fun))
    environmentName(nsenv)
}


来源: stackexchange

问:
WPF custom window
I want to get custom Window like

My code

```<code>     Height="800" Width="450" WindowStyle="None" ResizeMode="NoResize" Background="Transparent" AllowsTransparency="True">
<Grid>
    <Border Background="#FFFFFF" BorderBrush="LightGray" BorderThickness="3" CornerRadius="30 30 30 30">
    </Border>
</Grid>
</code>```

But I don't understand how to change geometry to get that arrow on the top. Can you help me with reference(geometry changing)?

答:
Here is an idea maybe it helps you get the right direction:

```<code><Window x:Class="Test.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="450" Width="800"
        WindowStyle="None" ResizeMode="NoResize" WindowStartupLocation="CenterScreen"
        Background="Transparent" AllowsTransparency="True" SnapsToDevicePixels="True">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <Canvas Grid.Row="0" Panel.ZIndex="5" HorizontalAlignment="Center" Height="12.5">
            <Polygon Points="15,15 20,15 10,0 0,15" Height="14" Width="20" Fill="White" Stroke="LightGray" StrokeThickness="1"/>
        </Canvas>
        <Border Grid.Row="1" BorderThickness="1" Background="White" BorderBrush="LightGray" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
        </Border>
    </Grid>
</Window>
</code>```

ContentLicense: CC BY-SA 4.0

Title: WPF custom window

Body:
I want to get custom Window like

My code

     Height="800" Width="450" WindowStyle="None" ResizeMode="NoResize" Background="Transparent" AllowsTransparency="True">
<Grid>
    <Border Background="#FFFFFF" BorderBrush="LightGray" BorderThickness="3" CornerRadius="30 30 30 30">
    </Border>
</Grid>

But I don't understand how to change geometry to get that arrow on the top. Can you help me with reference(geometry changing)?

Body:
Here is an idea maybe it helps you get the right direction:

<Window x:Class="Test.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="450" Width="800"
        WindowStyle="None" ResizeMode="NoResize" WindowStartupLocation="CenterScreen"
        Background="Transparent" AllowsTransparency="True" SnapsToDevicePixels="True">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <Canvas Grid.Row="0" Panel.ZIndex="5" HorizontalAlignment="Center" Height="12.5">
            <Polygon Points="15,15 20,15 10,0 0,15" Height="14" Width="20" Fill="White" Stroke="LightGray" StrokeThickness="1"/>
        </Canvas>
        <Border Grid.Row="1" BorderThickness="1" Background="White" BorderBrush="LightGray" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
        </Border>
    </Grid>
</Window>


问:
SQL Getting the party with highest votes
I am trying to make a voting system through a SQL server, and I can't get it right. What I am trying to do is get the party with the highest amount of votes.

```<code>SELECT COUNT(*)
FROM Vote
    INNER JOIN Members ON Vote.Voted = Members.PartyName
WHERE (PartyName is the biggest one)
</code>```

I expect something like [DEMS][8], or at the very least, the party name of the party with the highest votes.

答: SELECT PartijNaam FROM leden INNER JOIN stem ON leden.LidNummer = stem.Gestemt GROUP BY PartijNaam ORDER BY COUNT(gestemt) DESC LIMIT 1;</p>

Body:
I am trying to make a voting system through a SQL server, and I can't get it right. What I am trying to do is get the party with the highest amount of votes.

SELECT COUNT(*)
FROM Vote
    INNER JOIN Members ON Vote.Voted = Members.PartyName
WHERE (PartyName is the biggest one)

I expect something like [DEMS][8], or at the very least, the party name of the party with the highest votes.


问:
C# Switch If condition to expand the switch cases
I have some data which need to converted, for that I need a switch condition with more than 50 cases, I need the same cases 3 times but in the third time I need the 50 cases and some more and I don't want to write the same code twice. Maybe there is a possibility to do something like this.</p>

```<code>switch (example)
{
    case "1":
        //do something
    case "2":
        //do something
    case "50":
        //do something
    //now maybe something like this
    if (condition == true)
    {
        case "1":
            //do something else than above at case "1", and so on
            //now its i little bit illogical, but i neet to do the first 50 cases and then
            //use the cases 1 to 50 again but with other actions
    }
}
</code>```

答:
I presume you are looking for a way not to repeat if (condition == true).  Aside from the new when clause in C#7, you could also take a different approach with two switch statements:

```<code>if (!condition)
{
    switch (example)
    {
        case "1":
            //do something
        case "2":
            //do something
        case "50":
            //do something
    }
} else {
    switch (example)
    {
        case "51:
            //do something, and so on
    }
}
</code>```

Body:
I have some data which need to converted, for that I need a switch condition with more than 50 cases, I need the same cases 3 times but in the third time I need the 50 cases and some more and I don't want to write the same code twice. Maybe there is a possibility to do something like this.

switch (example)
{
    case "1":
        //do something
    case "2":
        //do something
    case "50":
        //do something
    //now maybe something like this
    if (condition == true)
    {
        case "1":
            //do something else than above at case "1", and so on
            //now its i little bit illogical, but i neet to do the first 50 cases and then
            //use the cases 1 to 50 again but with other actions
    }
}

Body:
I presume you are looking for a way not to repeat if (condition == true).  Aside from the new when clause in C#7, you could also take a different approach with two switch statements:

if (!condition)
{
    switch (example)
    {
        case "1":
            //do something
        case "2":
            //do something
        case "50":
            //do something
    }
} else {
    switch (example)
    {
        case "51:
            //do something, and so on
    }
}


问:
Decode image from HTTP POST request in python
I am sending an image from my HTML-JS frontend to my Python backend. Below is my JS code:

```<code>var formData = new FormData();
formData.append("a", file);

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

xhr.addEventListener("readystatechange", function() {
    if(this.readyState === 4) {
        log(this.responseText);
    }
});

xhr.open("POST", "http://localhost:8088");

xhr.send(formData);
</code>```

In my backend I am using BaseHTTPServer to receive this image

```<code>self.send_response(200)
self.send_header('Access-Control-Allow-Origin', 'http://localhost:8887')
self.send_header("Access-Control-Allow-Credentials", "true")
self.end_headers()
form = cgi.FieldStorage(
        fp=self.rfile,
        headers=self.headers,
        environ={"REQUEST_METHOD": "POST",
                 "CONTENT_TYPE": self.headers['Content-Type']})
image = form.getvalue("a")
bytes_array = []
for i in range(90000):
    try:
        bytes_array.append(image[i])
    except:
        print(i)
        break
print(bytes_array)
</code>```

The issue I am facing is that parts of my image variable looks like:

```<code><?xpacket begin=\'\xef\xbb\xbf\' id=\'W5M0MpCehiHzreSzNTczkc9d\'?>\r\n<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="uuid:faf5bdd5-ba3d-11da-ad31-d33d75182f1b" xmlns:dc="http://purl.org/dc/elements/1.1/"/><rdf:Description rdf:about="uuid:faf5bdd5-ba3d-11da-ad31-d33d75182f1b" xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:creator><rdf:Seq xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:li>Bankar, Pranit</rdf:li></rdf:Seq>\r\n\t\t\t</dc:creator></rdf:Description></rdf:RDF></x:xmpmeta>\r\n
</code>```

and

```<code><?xpacket end=\'w\'?>
</code>```

This creates garbage values in my bytes_array.

What would be a proper way to send an image file so that I can extract the pixel values?

答:
I modified my JS file in the below manner:

```<code>let b64_data;

function handleFileSelectTest(event){
  //Change event for image file upload

    img = document.getElementById('img');
    file = event.target.files[0];
    img.src = URL.createObjectURL(file);
    img.onload = function(){
        var canvas = document.createElement('canvas'),
        ctx = canvas.getContext('2d');
        canvas.height = img.naturalHeight;
        canvas.width = img.naturalWidth;
        ctx.drawImage(img, 0, 0);

        var uri = canvas.toDataURL('image/png'),
        b64_data1 = uri.replace(/^data:image.+;base64,/, '');
        b64_data = b64_data1;
    }
}
</code>```

and

```<code>var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

xhr.addEventListener("readystatechange", function() {
    if(this.readyState === 4) {
        log(this.responseText);
    }
});
xhr.open("POST", "http://localhost:8088");
//console.log(b64_data);
xhr.send(b64_data);
</code>```

I also modified my python code as:

```<code>self.send_response(200)
self.send_header('Access-Control-Allow-Origin', 'http://localhost:8887')
self.send_header("Access-Control-Allow-Credentials", "true")
self.end_headers()
content_len = int(self.headers.get('Content-Length'))
post_body = self.rfile.read(content_len)

print(post_body)
data = base64.b64decode(post_body)
with open("imageToSave1.png", "wb") as fh:
    fh.write(base64.decodebytes(post_body))
ans="a b c"
self.wfile.write(ans.encode())
</code>```

Body:
I am sending an image from my HTML-JS frontend to my Python backend. Below is my JS code:

var formData = new FormData();
formData.append("a", file);

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

xhr.addEventListener("readystatechange", function() {
    if(this.readyState === 4) {
        log(this.responseText);
    }
});

xhr.open("POST", "http://localhost:8088");

xhr.send(formData);

In my backend I am using BaseHTTPServer to receive this image

self.send_response(200)
self.send_header('Access-Control-Allow-Origin', 'http://localhost:8887')
self.send_header("Access-Control-Allow-Credentials", "true")
self.end_headers()
form = cgi.FieldStorage(
        fp=self.rfile,
        headers=self.headers,
        environ={"REQUEST_METHOD": "POST",
                 "CONTENT_TYPE": self.headers['Content-Type']})
image = form.getvalue("a")
bytes_array = []
for i in range(90000):
    try:
        bytes_array.append(image[i])
    except:
        print(i)
        break
print(bytes_array)

The issue I am facing is that parts of my image variable looks like:

<?xpacket begin=\'\xef\xbb\xbf\' id=\'W5M0MpCehiHzreSzNTczkc9d\'?>\r\n<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="uuid:faf5bdd5-ba3d-11da-ad31-d33d75182f1b" xmlns:dc="http://purl.org/dc/elements/1.1/"/><rdf:Description rdf:about="uuid:faf5bdd5-ba3d-11da-ad31-d33d75182f1b" xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:creator><rdf:Seq xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:li>Bankar, Pranit</rdf:li></rdf:Seq>\r\n\t\t\t</dc:creator></rdf:Description></rdf:RDF></x:xmpmeta>\r\n

and

<?xpacket end=\'w\'?>

This creates garbage values in my bytes_array.

What would be a proper way to send an image file so that I can extract the pixel values?

Body:
I modified my JS file in the below manner:

let b64_data;

function handleFileSelectTest(event){
  //Change event for image file upload

    img = document.getElementById('img');
    file = event.target.files[0];
    img.src = URL.createObjectURL(file);
    img.onload = function(){
        var canvas = document.createElement('canvas'),
        ctx = canvas.getContext('2d');
        canvas.height = img.naturalHeight;
        canvas.width = img.naturalWidth;
        ctx.drawImage(img, 0, 0);

        var uri = canvas.toDataURL('image/png'),
        b64_data1 = uri.replace(/^data:image.+;base64,/, '');
        b64_data = b64_data1;
    }
}

and

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

xhr.addEventListener("readystatechange", function() {
    if(this.readyState === 4) {
        log(this.responseText);
    }
});
xhr.open("POST", "http://localhost:8088");
//console.log(b64_data);
xhr.send(b64_data);

I also modified my python code as:

self.send_response(200)
self.send_header('Access-Control-Allow-Origin', 'http://localhost:8887')
self.send_header("Access-Control-Allow-Credentials", "true")
self.end_headers()
content_len = int(self.headers.get('Content-Length'))
post_body = self.rfile.read(content_len)

print(post_body)
data = base64.b64decode(post_body)
with open("imageToSave1.png", "wb") as fh:
    fh.write(base64.decodebytes(post_body))
ans="a b c"
self.wfile.write(ans.encode())


问:
How do I manually initialize a Spring Boot repository without using beans or annotations? (Kotlin)
I want to initialize a repository object in Spring Boot without having to make it a bean or an Autowired property.

I just want to do feedRepository = FeedRepository() in Kotlin. Why won't Spring Boot allow me to do this? Why does it have to be autowired or a bean?

here's my code:

```<code>@Component
class UriParser() {
    @Autowired
    lateinit var uriRepository: UriRepository

    @Autowired
    lateinit var hostRepository: HostRepository

    @Autowired
    lateinit var feedRepository: FeedRepository

    fun parseUri(uri: String) : Feed {
        val urlRepository = UriRepository()
        val uri = URI(uri)

        val uriRecord = uriRepository.save(Uri(scheme = uri.scheme, host = uri.host, port = uri.port))
        hostRepository.save(Host(host = uri.host))

        return feedRepository.save(Feed(uriId = uriRecord.id))
    }
}
</code>```

Edit: ok so here's better context as to why I can't autowire things. Basically I'm doing this within a static function so I have absolutely no access to beans or autowired properties:

```<code>@SpringBootApplication
class Application

fun main(args: Array<String>) {
    runApplication<Application>(*args)
     KafkaScheduler().init()
}
</code>```

The Kafka scheduler basically executes several threads which all listen to kafka topics:

```<code>class KafkaScheduler() {
    // this doesn't work....
    @Autowired
    lateinit var feedRepository: FeedRepository

    fun init() {
        val threads = arrayOf(
            {
                QueueListener().init()
            },
            {
                PrefetchListener().init()
            },
            {
                FetchListener().init()
            }
        )

        val service = Executors.newFixedThreadPool(threads.size)

        for (thread in threads) {
            service.submit(thread)
        }
    }
}
</code>```

however, I can't autowire the KafkaScheduler class as a bean within a static method so I can't really make that a component or autowire any repositories, as far as I know.

答:
Noone stops you from initializing objects by yourself inside the spring managed component.

However, these objects:

won't be managed by spring (e.g. if they also have dependencies you'll have to resolve them by yourself)

It doesn't make sense to use @Autowired in this case because it works only between spring beans.

For example, this is wrong because class A is not managed by spring:

```<code>
// not managed by spring
class A {
}

@Component
class B {
  @Autowired
  A a;
}
</code>```

So I believe you aim for something like this:

```<code>@Component
class UriParser() {

    // no autowired here, you manage everything by youself
    // also possible from constructor
    lateinit var uriRepository = UriRepository()
    ...
}
</code>```

Side note, I haven't learnt Kotlin, so the syntax might be wrong.

Body:
I want to initialize a repository object in Spring Boot without having to make it a bean or an Autowired property.

I just want to do feedRepository = FeedRepository() in Kotlin. Why won't Spring Boot allow me to do this? Why does it have to be autowired or a bean?

here's my code:

@Component
class UriParser() {
    @Autowired
    lateinit var uriRepository: UriRepository

    @Autowired
    lateinit var hostRepository: HostRepository

    @Autowired
    lateinit var feedRepository: FeedRepository

    fun parseUri(uri: String) : Feed {
        val urlRepository = UriRepository()
        val uri = URI(uri)

        val uriRecord = uriRepository.save(Uri(scheme = uri.scheme, host = uri.host, port = uri.port))
        hostRepository.save(Host(host = uri.host))

        return feedRepository.save(Feed(uriId = uriRecord.id))
    }
}

Edit: ok so here's better context as to why I can't autowire things. Basically I'm doing this within a static function so I have absolutely no access to beans or autowired properties:

@SpringBootApplication
class Application

fun main(args: Array<String>) {
    runApplication<Application>(*args)
     KafkaScheduler().init()
}

The Kafka scheduler basically executes several threads which all listen to kafka topics:

class KafkaScheduler() {
    // this doesn't work....
    @Autowired
    lateinit var feedRepository: FeedRepository

    fun init() {
        val threads = arrayOf(
            {
                QueueListener().init()
            },
            {
                PrefetchListener().init()
            },
            {
                FetchListener().init()
            }
        )

        val service = Executors.newFixedThreadPool(threads.size)

        for (thread in threads) {
            service.submit(thread)
        }
    }
}

however, I can't autowire the KafkaScheduler class as a bean within a static method so I can't really make that a component or autowire any repositories, as far as I know.

Body:
Noone stops you from initializing objects by yourself inside the spring managed component.

However, these objects:

won't be managed by spring (e.g. if they also have dependencies you'll have to resolve them by yourself)

It doesn't make sense to use @Autowired in this case because it works only between spring beans.

For example, this is wrong because class A is not managed by spring:

// not managed by spring
class A {
}

@Component
class B {
  @Autowired
  A a;
}

So I believe you aim for something like this:

@Component
class UriParser() {

    // no autowired here, you manage everything by youself
    // also possible from constructor
    lateinit var uriRepository = UriRepository()
    ...
}

Side note, I haven't learnt Kotlin, so the syntax might be wrong.


问:
Adding native swift code to NativeScript application
I'm trying to add native swift code to my NativeScript app. According to these instructions in the documentation I can just add a swift source file to App_Resources/iOS/src/ and then use any publicly exposed classes directly in my TypeScript code.
Unfortunately this just doesn't work. I'll just get Cannot find name 'TestClass' and that's it.

Steps to reproduce:

Get a fresh NS project with ios tns create my-app-name --template tns-template-blank-ts

Update: I actually created the App with vue init nativescript-vue/vue-cli-template testapp. That seems to have caused the problems.

Add a TestClass.swift to App_Resources/iOS/src/

import Foundation

public class TestClass: NSObject {
    @objc public func echo(param: String) -> String {
        return param
    }
}
```

Instantiate it in any TypeScript source file let instance = new TestClass()

Do tns debug ios

Compilation will fail with Cannot find name 'TestClass'

I have also tried generating TypeScript typings with TNS_TYPESCRIPT_DECLARATIONS_PATH="$(pwd)/typings" tns build ios or or just delcaring it as any with declare let KeyCommander: any; to eliminate the possibility that this is a TS related problem. The first approach doesn't generate any typings for my custom class so the TypeScript code will still not compile. The second approach let's the TS code compile but crashes on execution with JS ERROR ReferenceError: Can't find variable: TestClass.

I have also verified that the swift file is indeed getting compiled by inserting a syntax error which will crash the build process.

My NativeScript version is 6.4.0.

What am I missing?

Update: I just realized I actually created the App with vue init nativescript-vue/vue-cli-template testapp. I verified that as mentioned Tyler Blake's answer in an app created with the tns cli the described process actually works. In an app I just freshly created with vue init it doesn't, the objc!nsswiftsupport.d.ts is not being generated.

The question now is: What's causing the difference?

答:
I was able to solve the problem by inspecting the differences between the templates created with tns-cli and vue init. The difference is that the vue init template ships with an outdated version of the nativescript platform. You can just simply change

```<code>"tns-ios": {
  "version": "6.0.1"
}
</code>```

to version 6.4.0 (which the version the tns-cli template comes with) and then the process will work as described in the documentation.

Body:
I'm trying to add native swift code to my NativeScript app. According to these instructions in the documentation I can just add a swift source file to App_Resources/iOS/src/ and then use any publicly exposed classes directly in my TypeScript code.
Unfortunately this just doesn't work. I'll just get Cannot find name 'TestClass' and that's it.

Steps to reproduce:

Get a fresh NS project with ios tns create my-app-name --template tns-template-blank-ts

Update: I actually created the App with vue init nativescript-vue/vue-cli-template testapp. That seems to have caused the problems.

Add a TestClass.swift to App_Resources/iOS/src/

import Foundation

public class TestClass: NSObject {
    @objc public func echo(param: String) -> String {
        return param
    }
}

Instantiate it in any TypeScript source file let instance = new TestClass()

Do tns debug ios

Compilation will fail with Cannot find name 'TestClass'

I have also tried generating TypeScript typings with TNS_TYPESCRIPT_DECLARATIONS_PATH="$(pwd)/typings" tns build ios or or just delcaring it as any with declare let KeyCommander: any; to eliminate the possibility that this is a TS related problem. The first approach doesn't generate any typings for my custom class so the TypeScript code will still not compile. The second approach let's the TS code compile but crashes on execution with JS ERROR ReferenceError: Can't find variable: TestClass.

I have also verified that the swift file is indeed getting compiled by inserting a syntax error which will crash the build process.

My NativeScript version is 6.4.0.

What am I missing?

Update: I just realized I actually created the App with vue init nativescript-vue/vue-cli-template testapp. I verified that as mentioned Tyler Blake's answer in an app created with the tns cli the described process actually works. In an app I just freshly created with vue init it doesn't, the objc!nsswiftsupport.d.ts is not being generated.

The question now is: What's causing the difference?

Body:
I was able to solve the problem by inspecting the differences between the templates created with tns-cli and vue init. The difference is that the vue init template ships with an outdated version of the nativescript platform. You can just simply change

"tns-ios": {
  "version": "6.0.1"
}

to version 6.4.0 (which the version the tns-cli template comes with) and then the process will work as described in the documentation.


问:
undefined and null
```<code>undefined === null => false
undefined == null => true
</code>```

I have thought about the reason of undefined == null and found out only one case:

```<code>if(document.getElementById() == null) ....
</code>```

Is there any other reason to make (undefined === null) == false ?

Is there any other examples of use === - operation in javascript?

答:
null and undefined are two different concepts. undefined is the lack of value (if you define a variable with var without initializing it, it doesn't contain null, but undefined), while with null the variable exists and is initialized with the value null, which is a special type of value.

JavaScript equality operator is broken though, Crockford found out that it lacks transitivity and for this reason suggests to use always the strict equality (===). Consider this table published in Javascript the good parts:

```<code>'' == '0'          // false
0 == ''            // true
0 == '0'           // true

false == 'false'   // false
false == '0'       // true

false == undefined // false
false == null      // false
null == undefined  // true
</code>```

ContentLicense: CC BY-SA 3.0

Title: undefined and null

Body:
undefined === null => false
undefined == null => true

I have thought about the reason of undefined == null and found out only one case:

if(document.getElementById() == null) ....

Is there any other reason to make (undefined === null) == false ?

Is there any other examples of use === - operation in javascript?

Body:
null and undefined are two different concepts. undefined is the lack of value (if you define a variable with var without initializing it, it doesn't contain null, but undefined), while with null the variable exists and is initialized with the value null, which is a special type of value.

JavaScript equality operator is broken though, Crockford found out that it lacks transitivity and for this reason suggests to use always the strict equality (===). Consider this table published in Javascript the good parts:

'' == '0'          // false
0 == ''            // true
0 == '0'           // true

false == 'false'   // false
false == '0'       // true

false == undefined // false
false == null      // false
null == undefined  // true


问:
Move console and logcat view to bottom
My eclipse's（ADT bundle Mac OSX） console view and logcat view are located at the right side of the screen. When activated, they will cover my code editor. （When I maximize them they will automatically move to the bottom, but when minimized they fly back to the right side again.）

status 1:normal ,them cover the editor,

status 2:  when I max them, look like good, but

status 3:when minimize them, backto status 1

答:
Since Eclipse Neon (4.6, June 2016), you don't need to drag each tab individually. You can just drag the empty space after the tabs to move the whole stack of views.

You can do this both when the stack is minimized/maximized and when it's not.

Title: Move console and logcat view to bottom


答:
try this:</p>

```<code>  SELECT  PartijNaam, COUNT(*)as vote
    FROM stem
        INNER JOIN leden ON stem.Gestemt = Leden.lidnummer
    GROUP BY PartijNaam
    ORDER BY DESC
</code>```

Title: SQL Getting the party with highest votes

Body:
try this:

  SELECT  PartijNaam, COUNT(*)as vote
    FROM stem
        INNER JOIN leden ON stem.Gestemt = Leden.lidnummer
    GROUP BY PartijNaam
    ORDER BY DESC


问:
Remove "Using default security password" on Spring Boot
I added one custom Security Config in my application on Spring Boot, but the message about "Using default security password" is still there in LOG file.

Is there any to remove it? I do not need this default password. It seems Spring Boot is not recognizing my security policy.

```<code>@Configuration
@EnableWebSecurity
public class CustomSecurityConfig extends WebSecurityConfigurerAdapter {

    private final String uri = "/custom/*";

    @Override
    public void configure(final HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.headers().httpStrictTransportSecurity().disable();
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        // Authorize sub-folders permissions
        http.antMatcher(uri).authorizeRequests().anyRequest().permitAll();
    }
}
</code>```

答:
To remove the default user you need to configure authentication manager with no users for example:

```<code>@configuration
class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication();
    }
}
</code>```

this will remove default password message and default user because in that case you are configuring InMemoryAuthentication and you will not specify any user in next steps

Body:
I added one custom Security Config in my application on Spring Boot, but the message about "Using default security password" is still there in LOG file.

Is there any to remove it? I do not need this default password. It seems Spring Boot is not recognizing my security policy.

@Configuration
@EnableWebSecurity
public class CustomSecurityConfig extends WebSecurityConfigurerAdapter {

    private final String uri = "/custom/*";

    @Override
    public void configure(final HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.headers().httpStrictTransportSecurity().disable();
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        // Authorize sub-folders permissions
        http.antMatcher(uri).authorizeRequests().anyRequest().permitAll();
    }
}

Body:
To remove the default user you need to configure authentication manager with no users for example:

@configuration
class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication();
    }
}

this will remove default password message and default user because in that case you are configuring InMemoryAuthentication and you will not specify any user in next steps


问:
Using Axios in Nativescript App for User Authentication
I am building an app using Nativescript-Vue that requires authentication of users in order to use the app.  I have a RESTful backend that functions appropriately as tested with Postman.

JWT Tokens are implemented with a perpetual life but require refreshing every 5 minutes (refresh functionality - in a vaccuum -- working appropriately).

Using Axios.js for web calls.

I am stuck on how to implement basic logic for determining if the user is logged in. All Axios calls return a Promise. I have read the extended "Promise" responses a bunch, but it's not sinking into my head how to do what I want. In a nutshell, I need to pause code execution until the API can authenticate the user and this is not computing for me.

Code as follows:

app.js

```<code>// Import VUE library
import Vue from "nativescript-vue";

// This is my user handler
import {UserServices} from "./assets/js/UserServices.js"

// imported Components
import Login from "./components/Login";
import Home from "./components/Home.vue"

let user = new UserServices();
let loggedIn =  user.checkAuthStatus();

new Vue({
    render: h =>  h('Frame', [
        h(
            loggedIn ? Home : Login
        )
    ])
}).$start();

</code>```

This isn't working because user.checkAuthStatus() is an async function that returns a promise and thus I cannot get a boolean value returned.  I know this is the problem, but I left that in the code so that the intended result can be understood.  What I don't understand is how to rewrite the code so that the designed flow is feasible using Promises.

Core logic is designed to be:

Check the user's logged-in status via user.checkAuthStatus().  This routine checks for a valid token (valid meaning it exists and is not expired).  If it is expired, the token is refreshed via a call to this.refresh() from the UserServices controller.

If a value of "true" is returned from user.checkAuthStatus() the Vue app should load the Home component (aka user is logged in), else the user should be required to login.

I can only imagine that this is a simple situation thousands of people have successfully overcome, but my brain isn't working thru it.  I get why JS needs to continue running so as not to stop the progress of the code (and that's the point of a Promise, I think?), but sometimes the code just needs to stop and wait it seems, like in a user authentication scenario.

Any help drilling down on the specifics on how to address my challenge?  Please and thank you.

答:
I would do like this:

Check if a locally stored token exists, valid and not expired, if yes go to homepage else redirect to login.

Body:
I am building an app using Nativescript-Vue that requires authentication of users in order to use the app.  I have a RESTful backend that functions appropriately as tested with Postman.

JWT Tokens are implemented with a perpetual life but require refreshing every 5 minutes (refresh functionality - in a vaccuum -- working appropriately).

Using Axios.js for web calls.

I am stuck on how to implement basic logic for determining if the user is logged in. All Axios calls return a Promise. I have read the extended "Promise" responses a bunch, but it's not sinking into my head how to do what I want. In a nutshell, I need to pause code execution until the API can authenticate the user and this is not computing for me.

Code as follows:

app.js

// Import VUE library
import Vue from "nativescript-vue";

// This is my user handler
import {UserServices} from "./assets/js/UserServices.js"

// imported Components
import Login from "./components/Login";
import Home from "./components/Home.vue"

let user = new UserServices();
let loggedIn =  user.checkAuthStatus();

new Vue({
    render: h =>  h('Frame', [
        h(
            loggedIn ? Home : Login
        )
    ])
}).$start();

This isn't working because user.checkAuthStatus() is an async function that returns a promise and thus I cannot get a boolean value returned.  I know this is the problem, but I left that in the code so that the intended result can be understood.  What I don't understand is how to rewrite the code so that the designed flow is feasible using Promises.

Core logic is designed to be:

Check the user's logged-in status via user.checkAuthStatus().  This routine checks for a valid token (valid meaning it exists and is not expired).  If it is expired, the token is refreshed via a call to this.refresh() from the UserServices controller.

If a value of "true" is returned from user.checkAuthStatus() the Vue app should load the Home component (aka user is logged in), else the user should be required to login.

I can only imagine that this is a simple situation thousands of people have successfully overcome, but my brain isn't working thru it.  I get why JS needs to continue running so as not to stop the progress of the code (and that's the point of a Promise, I think?), but sometimes the code just needs to stop and wait it seems, like in a user authentication scenario.

Any help drilling down on the specifics on how to address my challenge?  Please and thank you.


问:
How to serialize a string holding nothing but "\r\n" to XML correctly?
We're using DataContractSerializer to serialize our data to XML. Recently we found a bug with how the string "\r\n" gets saved and read back - it was turned into just "\n". Apparently, what causes this is using an XmlWriter with Indent = true set:

```<code>// public class Test { public string Line; }

var serializer = new DataContractSerializer(typeof(Test));

using (var fs = File.Open("C:/test.xml", FileMode.Create))
using (var wr = XmlWriter.Create(fs, new XmlWriterSettings() { Indent = true }))
    serializer.WriteObject(wr, new Test() { Line = "\r\n" });

Test test;
using (var fs = File.Open("C:/test.xml", FileMode.Open))
    test = (Test) serializer.ReadObject(fs);
</code>```

The obvious fix is to stop indenting XML, and indeed removing the "XmlWriter.Create" line makes the Line value roundtrip correctly, whether it's "\n", "\r\n" or anything else.

However, the way DataContractSerializer writes it still doesn't seem to be entirely safe or perhaps even correct - for example, just reading the resulting file with XML Notepad and saving it again destroys both "\n" and "\r\n" values completely.

What is the correct approach here? Is using XML as a format for serializing binary data a flawed concept? Are we wrong to expect that tools like XML Notepad won't break our data? Do we need to augment each and every string field that could contain such text with some special attribute, perhaps something to force CDATA?

答:
You can try using:

XmlWriterSettings.NewLineHandling = NewLineHandling.Entitize;
```

ContentLicense: CC BY-SA 2.5

Body:
We're using DataContractSerializer to serialize our data to XML. Recently we found a bug with how the string "\r\n" gets saved and read back - it was turned into just "\n". Apparently, what causes this is using an XmlWriter with Indent = true set:

// public class Test { public string Line; }

var serializer = new DataContractSerializer(typeof(Test));

using (var fs = File.Open("C:/test.xml", FileMode.Create))
using (var wr = XmlWriter.Create(fs, new XmlWriterSettings() { Indent = true }))
    serializer.WriteObject(wr, new Test() { Line = "\r\n" });

Test test;
using (var fs = File.Open("C:/test.xml", FileMode.Open))
    test = (Test) serializer.ReadObject(fs);

The obvious fix is to stop indenting XML, and indeed removing the "XmlWriter.Create" line makes the Line value roundtrip correctly, whether it's "\n", "\r\n" or anything else.

However, the way DataContractSerializer writes it still doesn't seem to be entirely safe or perhaps even correct - for example, just reading the resulting file with XML Notepad and saving it again destroys both "\n" and "\r\n" values completely.

What is the correct approach here? Is using XML as a format for serializing binary data a flawed concept? Are we wrong to expect that tools like XML Notepad won't break our data? Do we need to augment each and every string field that could contain such text with some special attribute, perhaps something to force CDATA?


问:
Optimizer and scheduler for BERT fine-tuning
I'm trying to fine-tune a model with BERT (using transformers library), and I'm a bit unsure about the optimizer and scheduler.

First, I understand that I should use transformers.AdamW instead of Pytorch's version of it. Also, we should use a warmup scheduler as suggested in the paper, so the scheduler is created using get_linear_scheduler_with_warmup function from transformers package.

The main questions I have are:

get_linear_scheduler_with_warmup should be called with the warm up. Is it ok to use 2 for warmup out of 10 epochs?

When should I call scheduler.step()? If I do after train, the learning rate is zero for the first epoch. Should I call it for each batch?

Am I doing something wrong with this?

from transformers import AdamW
from transformers.optimization import get_linear_scheduler_with_warmup

N_EPOCHS = 10

model = BertGRUModel(finetune_bert=True,...)
num_training_steps = N_EPOCHS+1
num_warmup_steps = 2
warmup_proportion = float(num_warmup_steps) / float(num_training_steps)  # 0.1

optimizer = AdamW(model.parameters())
criterion = nn.BCEWithLogitsLoss(pos_weight=torch.Tensor([class_weights[1]]))

scheduler = get_linear_schedule_with_warmup(
    optimizer, num_warmup_steps=num_warmup_steps,
    num_training_steps=num_training_steps
)

for epoch in range(N_EPOCHS):
    scheduler.step() #If I do after train, LR = 0 for the first epoch
    print(optimizer.param_groups[0]["lr"])

    train(...) # here we call optimizer.step()
    evaluate(...)
```

<p>My model and train routine(quite similar to this notebook)</p>

<pre class="lang-py prettyprint-override"><code>class BERTGRUSentiment(nn.Module):
    def __init__(self,
                 bert,
                 hidden_dim,
                 output_dim,
                 n_layers=1,
                 bidirectional=False,
                 finetune_bert=False,
                 dropout=0.2):

        super().__init__()

        self.bert = bert

        embedding_dim = bert.config.to_dict()['hidden_size']

        self.finetune_bert = finetune_bert

        self.rnn = nn.GRU(embedding_dim,
                          hidden_dim,
                          num_layers = n_layers,
                          bidirectional = bidirectional,
                          batch_first = True,
                          dropout = 0 if n_layers < 2 else dropout)

        self.out = nn.Linear(hidden_dim * 2 if bidirectional else hidden_dim, output_dim)
        self.dropout = nn.Dropout(dropout)

    def forward(self, text):
        #text = [batch size, sent len]

        if not self.finetune_bert:
            with torch.no_grad():
                embedded = self.bert(text)[0]
        else:
            embedded = self.bert(text)[0]
        #embedded = [batch size, sent len, emb dim]
        _, hidden = self.rnn(embedded)

        #hidden = [n layers * n directions, batch size, emb dim]

        if self.rnn.bidirectional:
            hidden = self.dropout(torch.cat((hidden[-2,:,:], hidden[-1,:,:]), dim = 1))
        else:
            hidden = self.dropout(hidden[-1,:,:])

        #hidden = [batch size, hid dim]

        output = self.out(hidden)

        #output = [batch size, out dim]

        return output

import torch
from sklearn.metrics import accuracy_score, f1_score

def train(model, iterator, optimizer, criterion, max_grad_norm=None):
    """
    Trains the model for one full epoch
    """
    epoch_loss = 0
    epoch_acc = 0

    model.train()

    for i, batch in enumerate(iterator):
        optimizer.zero_grad()
        text, lens = batch.text

        predictions = model(text)

        target = batch.target

        loss = criterion(predictions.squeeze(1), target)

        prob_predictions = torch.sigmoid(predictions)

        preds = torch.round(prob_predictions).detach().cpu()
        acc = accuracy_score(preds, target.cpu())

        loss.backward()
        # Gradient clipping
        if max_grad_norm:
            torch.nn.utils.clip_grad_norm_(model.parameters(), max_grad_norm)

        optimizer.step()

        epoch_loss += loss.item()
        epoch_acc += acc.item()

    return epoch_loss / len(iterator), epoch_acc / len(iterator)

</code>```

答:
I think it is hardly possible to give a 100% perfect answer, but you can certainly get inspiration from the way other scripts are doing it. The best place to start is the examples/ directory of the huggingface repository itself, where you can for example find this excerpt:

if (step + 1) % args.gradient_accumulation_steps == 0:
    if args.fp16:
        torch.nn.utils.clip_grad_norm_(amp.master_params(optimizer), args.max_grad_norm)
    else:
        torch.nn.utils.clip_grad_norm_(model.parameters(), args.max_grad_norm)

    optimizer.step()
    scheduler.step()  # Update learning rate schedule
    model.zero_grad()
    global_step += 1
```

If we look at the surrounding parts, this is basically updating the LR schedule every time you do a backwards pass. In the same example, you can also look at the default value for warmup_steps, which is 0. From my understanding, the warmup is not necessarily required when fine-tuning, but I am less certain about this aspect and would check with other scripts as well.

Body:
I'm trying to fine-tune a model with BERT (using transformers library), and I'm a bit unsure about the optimizer and scheduler.

First, I understand that I should use transformers.AdamW instead of Pytorch's version of it. Also, we should use a warmup scheduler as suggested in the paper, so the scheduler is created using get_linear_scheduler_with_warmup function from transformers package.

The main questions I have are:

get_linear_scheduler_with_warmup should be called with the warm up. Is it ok to use 2 for warmup out of 10 epochs?

When should I call scheduler.step()? If I do after train, the learning rate is zero for the first epoch. Should I call it for each batch?

Am I doing something wrong with this?

from transformers import AdamW
from transformers.optimization import get_linear_scheduler_with_warmup

N_EPOCHS = 10

model = BertGRUModel(finetune_bert=True,...)
num_training_steps = N_EPOCHS+1
num_warmup_steps = 2
warmup_proportion = float(num_warmup_steps) / float(num_training_steps)  # 0.1

optimizer = AdamW(model.parameters())
criterion = nn.BCEWithLogitsLoss(pos_weight=torch.Tensor([class_weights[1]]))

scheduler = get_linear_schedule_with_warmup(
    optimizer, num_warmup_steps=num_warmup_steps,
    num_training_steps=num_training_steps
)

for epoch in range(N_EPOCHS):
    scheduler.step() #If I do after train, LR = 0 for the first epoch
    print(optimizer.param_groups[0]["lr"])

    train(...) # here we call optimizer.step()
    evaluate(...)

My model and train routine(quite similar to this notebook)

class BERTGRUSentiment(nn.Module):
    def __init__(self,
                 bert,
                 hidden_dim,
                 output_dim,
                 n_layers=1,
                 bidirectional=False,
                 finetune_bert=False,
                 dropout=0.2):

        super().__init__()

        self.bert = bert

        embedding_dim = bert.config.to_dict()['hidden_size']

        self.finetune_bert = finetune_bert

        self.rnn = nn.GRU(embedding_dim,
                          hidden_dim,
                          num_layers = n_layers,
                          bidirectional = bidirectional,
                          batch_first = True,
                          dropout = 0 if n_layers < 2 else dropout)

        self.out = nn.Linear(hidden_dim * 2 if bidirectional else hidden_dim, output_dim)
        self.dropout = nn.Dropout(dropout)

    def forward(self, text):
        #text = [batch size, sent len]

        if not self.finetune_bert:
            with torch.no_grad():
                embedded = self.bert(text)[0]
        else:
            embedded = self.bert(text)[0]
        #embedded = [batch size, sent len, emb dim]
        _, hidden = self.rnn(embedded)

        #hidden = [n layers * n directions, batch size, emb dim]

        if self.rnn.bidirectional:
            hidden = self.dropout(torch.cat((hidden[-2,:,:], hidden[-1,:,:]), dim = 1))
        else:
            hidden = self.dropout(hidden[-1,:,:])

        #hidden = [batch size, hid dim]

        output = self.out(hidden)

        #output = [batch size, out dim]

        return output

import torch
from sklearn.metrics import accuracy_score, f1_score

def train(model, iterator, optimizer, criterion, max_grad_norm=None):
    """
    Trains the model for one full epoch
    """
    epoch_loss = 0
    epoch_acc = 0

    model.train()

    for i, batch in enumerate(iterator):
        optimizer.zero_grad()
        text, lens = batch.text

        predictions = model(text)

        target = batch.target

        loss = criterion(predictions.squeeze(1), target)

        prob_predictions = torch.sigmoid(predictions)

        preds = torch.round(prob_predictions).detach().cpu()
        acc = accuracy_score(preds, target.cpu())

        loss.backward()
        # Gradient clipping
        if max_grad_norm:
            torch.nn.utils.clip_grad_norm_(model.parameters(), max_grad_norm)

        optimizer.step()

        epoch_loss += loss.item()
        epoch_acc += acc.item()

    return epoch_loss / len(iterator), epoch_acc / len(iterator)

Body:
I think it is hardly possible to give a 100% perfect answer, but you can certainly get inspiration from the way other scripts are doing it. The best place to start is the examples/ directory of the huggingface repository itself, where you can for example find this excerpt:

if (step + 1) % args.gradient_accumulation_steps == 0:
    if args.fp16:
        torch.nn.utils.clip_grad_norm_(amp.master_params(optimizer), args.max_grad_norm)
    else:
        torch.nn.utils.clip_grad_norm_(model.parameters(), args.max_grad_norm)

    optimizer.step()
    scheduler.step()  # Update learning rate schedule
    model.zero_grad()
    global_step += 1

If we look at the surrounding parts, this is basically updating the LR schedule every time you do a backwards pass. In the same example, you can also look at the default value for warmup_steps, which is 0. From my understanding, the warmup is not necessarily required when fine-tuning, but I am less certain about this aspect and would check with other scripts as well.


问:
Passing an image in axios request in react-native
I am trying to pass an image along with this request, other parameters get sent, but not the image. What way would be better. appApi is an axios instance which I imported.

```<code>const update = dispatch => async ({ name, email, phone, photo, Age, Blood, Gender, Height, Weight, id }) => {
      //make api request to update with that info

      // const picture = new FormData()
      // picture.append("picture", {
      //   type: 'image/jpg',
      //   uri: photo,
      //   name: 'profilepic.jpg'
      // });

      // const picture = {
      //   type: 'image/jpg',
      //   uri: photo,
      //   name: 'profilepic.jpg'
      // }
      // console.log(picture)
      const picture = {
        type: 'image/jpg',
        uri: photo,
        name: 'profilepic.jpg'
      }

      const response = await appApi.put(`/userregister/${id}`, { name, email, phone, picture, Age, Blood, Gender, Height, Weight })
      if (response) {
        console.log(response.data)
        navigate("AccountScrn");

      } else {
        dispatch({
          type: "ADD_ERROR",
          payload: 'Unable to update profile, please try again later'
        })
      }
    };
</code>```

答:
Using fetch method i had done you can easily cahnge to axios

```<code>fetch("/url", {
      method: "POST",
      body: JSON.stringify({ serial_no: "xyz" }),
      headers: {
        "Content-Type": "application/json"
      }
    })
      .then(response => response.blob())
      .then(file => {
        var outside = URL.createObjectURL(file);
        console.log(outside)
      });
</code>```

You can use the image as in img tag or you can also download the image

Body:
I am trying to pass an image along with this request, other parameters get sent, but not the image. What way would be better. appApi is an axios instance which I imported.

const update = dispatch => async ({ name, email, phone, photo, Age, Blood, Gender, Height, Weight, id }) => {
      //make api request to update with that info

      // const picture = new FormData()
      // picture.append("picture", {
      //   type: 'image/jpg',
      //   uri: photo,
      //   name: 'profilepic.jpg'
      // });

      // const picture = {
      //   type: 'image/jpg',
      //   uri: photo,
      //   name: 'profilepic.jpg'
      // }
      // console.log(picture)
      const picture = {
        type: 'image/jpg',
        uri: photo,
        name: 'profilepic.jpg'
      }

      const response = await appApi.put(`/userregister/${id}`, { name, email, phone, picture, Age, Blood, Gender, Height, Weight })
      if (response) {
        console.log(response.data)
        navigate("AccountScrn");

      } else {
        dispatch({
          type: "ADD_ERROR",
          payload: 'Unable to update profile, please try again later'
        })
      }
    };

Body:
Using fetch method i had done you can easily cahnge to axios

fetch("/url", {
      method: "POST",
      body: JSON.stringify({ serial_no: "xyz" }),
      headers: {
        "Content-Type": "application/json"
      }
    })
      .then(response => response.blob())
      .then(file => {
        var outside = URL.createObjectURL(file);
        console.log(outside)
      });

You can use the image as in img tag or you can also download the image


问:
using svyciprop to calculate prevalence with CI
I'm  using R(3.6.1) to calculate prevalence using the package "survey", as i calculated prevalence with weights, my issue is that to calculate confidence interval with proportion. I'm using svyciprop() command but when it shows the confidence intervals for 97.5% it doesn't shows the value after two decimal places

```<code>x=svyciprop(~new_var3,small.w1)
x
</code>```

Returns:

```<code>                  2.5% 97.5%
new_var3 0.0176 0.0140  0.02
</code>```

I don't know how to fix this or there is another package or by some other way you can calculate these estimates, please help me!

答:
what you are seeing is printed onto the console, you can access the values like this:</p>

```<code>library(survey)
data(api)
dclus1<-svydesign(id=~dnum, fpc=~fpc, data=apiclus1)
x = svyciprop(~I(ell==0), dclus1, method="li")
x
                         2.5% 97.5%
I(ell == 0) 0.021858 0.000664  0.11

values = attr(x,"ci")
values
        2.5%        97.5%
0.0006639212 0.1077784084
values[1]
        2.5%
0.0006639212
values[2]
    97.5%
0.1077784
</code>```

Body:
I'm  using R(3.6.1) to calculate prevalence using the package "survey", as i calculated prevalence with weights, my issue is that to calculate confidence interval with proportion. I'm using svyciprop() command but when it shows the confidence intervals for 97.5% it doesn't shows the value after two decimal places

x=svyciprop(~new_var3,small.w1)
x

Returns:

                  2.5% 97.5%
new_var3 0.0176 0.0140  0.02

I don't know how to fix this or there is another package or by some other way you can calculate these estimates, please help me!

Body:
what you are seeing is printed onto the console, you can access the values like this:

library(survey)
data(api)
dclus1<-svydesign(id=~dnum, fpc=~fpc, data=apiclus1)
x = svyciprop(~I(ell==0), dclus1, method="li")
x
                         2.5% 97.5%
I(ell == 0) 0.021858 0.000664  0.11

values = attr(x,"ci")
values
        2.5%        97.5%
0.0006639212 0.1077784084
values[1]
        2.5%
0.0006639212
values[2]
    97.5%
0.1077784


问:
Accessing container resource variables in Azure Devops YAML Pipeline
Using Azure Devops YAML Pipelines and trying to have a pipeline trigger on a container being pushed to an ACR.

According to the documentation in the link below, I should be able to access the tag and other information related to the image using variables like RESOURCES_CONTAINER_IDENTIFIER_TAG that should be available.

https://learn.microsoft.com/en-us/azure/devops/pipelines/process/resources?view=azure-devops&tabs=schema

However, I see no trace of variables from Containers or Repositories. It works fine with Pipelines and I haven't tested Builds. To be clear, the pipeline is triggered fine but inside the pipeline I cannot see which tag triggered it.

So is there something special that needs to be done here or is it released in the documentation but not working yet?

答:
Just as the document states:

resources.container.<Alias>.tag is what you want and it should work because this feature is supported since Sprint 159. (Now it's Sprint 164.)

Sample yaml:

```<code>resources:
  containers:
  - container: ACRResource1
    type: ACR
    azureSubscription: ARM
    resourceGroup: xxx
    registry: xxx
    repository: xxx/docker-acr:v1-tag
  - container: ACRResource2
    type: ACR
    azureSubscription: ARM
    resourceGroup: xxx
    registry: xxx
    repository: xxx/docker-acr
</code>```

Sample output:

```<code>resources.container.ACRResource1.tag = v1-tag
resources.container.ACRResource2.tag = v10-tag  (latest tag value)
</code>```

Make sure you configured the yaml and settings well and created valid service connections.

Body:
Just as the document states:

resources.container.<Alias>.tag is what you want and it should work because this feature is supported since Sprint 159. (Now it's Sprint 164.)

Sample yaml:

resources:
  containers:
  - container: ACRResource1
    type: ACR
    azureSubscription: ARM
    resourceGroup: xxx
    registry: xxx
    repository: xxx/docker-acr:v1-tag
  - container: ACRResource2
    type: ACR
    azureSubscription: ARM
    resourceGroup: xxx
    registry: xxx
    repository: xxx/docker-acr

Sample output:

resources.container.ACRResource1.tag = v1-tag
resources.container.ACRResource2.tag = v10-tag  (latest tag value)

Make sure you configured the yaml and settings well and created valid service connections.


问:
Unable to prompt for search in an array
I am trying to create a search array where user enter the number of items, enter the value of all items and search for an array. However, I am unable to prompt for the search array to display after user enter the values of all the items. Here is an example of the desired output:

```<code>Enter the number of items: 5
Enter the value of all items (separated by space): 6 1 8 2 4
Enter the search key: 8
8 is found with index 2
</code>```

Here is my coding:

```<code>import java.util.Scanner;

public class SearchArray {

public static void main(String[] args) {

    int[] array;
    int items;

    Scanner in = new Scanner(System.in);
    System.out.print("Enter the number of items: ");
    items = in.nextInt();

    array = new int[items];
    print(array);
    System.out.println();

}

public static void print(int[] array) {

    Scanner in = new Scanner(System.in);

    if (array.length > 0) {
        System.out.print("Enter the value of all items (separated by space): ");
        for (int i = 0; i < array.length; ++i) {
            array[i] = in.nextInt();
        }

    }

}

public static int search(int[] array, int key){

    Scanner in = new Scanner(System.in);

  if (array.length > 0) {
      System.out.print("Enter the search key: ");
    for(int i=0; i<array.length; ++i){
        if(array[i] == key){
            key = in.nextInt();
            System.out.println(key + "is present at location " + (i+1) + ".");
        }
    }

  }
  return -1;

 }

public static boolean isEmpty(int[] array) {

    if (array.length == 0)
        return true;
    else
        return false;

}
}
</code>```

It would be good if someone can help me on that. Thanks!

答:
what am seeing is that your not calling the search method in the main method
like search(array)
Also you don't need the second parameter in the search function. instantiate
     a global variable called key and scan the input search(key) before the for
     loop in the search method. I have done below.

```<code>public class SearchArray {
    private static int[] array;
    private static int items;
    private static int key;
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter the number of items: ");
        items = scanner.nextInt();

        array = new int[items];
        print(array);
        search(array);
        System.out.println();

    }

public static void print(int[] array) {
        Scanner scanner = new Scanner(System.in);

        if(array.length > 0) {
            System.out.print("Enter the value of all items (seperated by space):");
            for(int i = 0; i < array.length; i++) {
                array[i] = scanner.nextInt();
            }
        }
    }

public static int search(int[] array) {
        Scanner scanner = new Scanner(System.in);

        if(array.length > 0) {
            System.out.print("Enter the search key: ");
            key = scanner.nextInt();
            for(int i = 0; i < array.length; i++) {
                if(array[i] == key) {
                    System.out.println(key + " is present at location " + (i+1));

                }
            }
        }
        return -1;

    }

public static boolean isEmpty(int[] array) {
        if(array.length == 0)
            return true;
        else
            return false;
    }

}
</code>```

output is

```<code>Enter the number of items: 5
Enter the value of all items (seperated by space):5 7 3 4 6
Enter the search key: 3
3 is present at location 3
</code>```

Title: Unable to prompt for search in an array

Body:
I am trying to create a search array where user enter the number of items, enter the value of all items and search for an array. However, I am unable to prompt for the search array to display after user enter the values of all the items. Here is an example of the desired output:

Enter the number of items: 5
Enter the value of all items (separated by space): 6 1 8 2 4
Enter the search key: 8
8 is found with index 2

Here is my coding:

import java.util.Scanner;

public class SearchArray {

public static void main(String[] args) {

    int[] array;
    int items;

    Scanner in = new Scanner(System.in);
    System.out.print("Enter the number of items: ");
    items = in.nextInt();

    array = new int[items];
    print(array);
    System.out.println();

}

public static void print(int[] array) {

    Scanner in = new Scanner(System.in);

    if (array.length > 0) {
        System.out.print("Enter the value of all items (separated by space): ");
        for (int i = 0; i < array.length; ++i) {
            array[i] = in.nextInt();
        }

    }

}

public static int search(int[] array, int key){

    Scanner in = new Scanner(System.in);

  if (array.length > 0) {
      System.out.print("Enter the search key: ");
    for(int i=0; i<array.length; ++i){
        if(array[i] == key){
            key = in.nextInt();
            System.out.println(key + "is present at location " + (i+1) + ".");
        }
    }

  }
  return -1;

 }

public static boolean isEmpty(int[] array) {

    if (array.length == 0)
        return true;
    else
        return false;

}
}

It would be good if someone can help me on that. Thanks!

Body:
what am seeing is that your not calling the search method in the main method
like search(array)
Also you don't need the second parameter in the search function. instantiate
     a global variable called key and scan the input search(key) before the for
     loop in the search method. I have done below.

public class SearchArray {
    private static int[] array;
    private static int items;
    private static int key;
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter the number of items: ");
        items = scanner.nextInt();

        array = new int[items];
        print(array);
        search(array);
        System.out.println();

    }

public static void print(int[] array) {
        Scanner scanner = new Scanner(System.in);

        if(array.length > 0) {
            System.out.print("Enter the value of all items (seperated by space):");
            for(int i = 0; i < array.length; i++) {
                array[i] = scanner.nextInt();
            }
        }
    }

public static int search(int[] array) {
        Scanner scanner = new Scanner(System.in);

        if(array.length > 0) {
            System.out.print("Enter the search key: ");
            key = scanner.nextInt();
            for(int i = 0; i < array.length; i++) {
                if(array[i] == key) {
                    System.out.println(key + " is present at location " + (i+1));

                }
            }
        }
        return -1;

    }

public static boolean isEmpty(int[] array) {
        if(array.length == 0)
            return true;
        else
            return false;
    }

}

output is

Enter the number of items: 5
Enter the value of all items (seperated by space):5 7 3 4 6
Enter the search key: 3
3 is present at location 3


问:
URL parameter in react Class Component
I'm trying to pass parameter to component using URL.I'm using react component not functionnel component so I can't use hooks? How can I read url parameter in class component ?
I'm trying to pass parameter to a component so it can depending on parameter fetch data from database and update it or just create a new record!
Thanks</p>

答: You can use window.location to read the URL parameters

Title: URL parameter in react Class Component


问:
Google NLP : row unreadable when the sentiment score is equal to 10
I have a problem when I try to add items to a new dataset to do a sentiment analysis.

I have a sentiment score scale from 0 to 10 and everything works perfectly for sentiment score from 0 to 9 but those associated to 10 can't be read despite the fact that I put maximal sentiment scale to 10.

Is there a special modification to do to my csv file so that google could recognise those rows ?

This is the error I got :

```<code>Invalid input found at row 2 of ... "Row parsing resulting in unexpected label name."
</code>```

Thanks for your help !

答:
```<code>gs://tttttt-bucket/table_2jpg,table
gs://tttttt-bucket/table_l.png,table
</code>```

You can test a file like this, just give the uri and label. I tested it works.

Body:
I have a problem when I try to add items to a new dataset to do a sentiment analysis.

I have a sentiment score scale from 0 to 10 and everything works perfectly for sentiment score from 0 to 9 but those associated to 10 can't be read despite the fact that I put maximal sentiment scale to 10.

Is there a special modification to do to my csv file so that google could recognise those rows ?

This is the error I got :

Invalid input found at row 2 of ... "Row parsing resulting in unexpected label name."

Thanks for your help !

Body:
gs://tttttt-bucket/table_2jpg,table
gs://tttttt-bucket/table_l.png,table

You can test a file like this, just give the uri and label. I tested it works.


问:
Unable to convert varchar to date
I am trying to convert a function (varchar) to date, but get the below error message.

Error

Failed to convert date and / or time from string.

Script

```<code>DECLARE @MyDate date

SET @MyDate = CONVERT(date, dbo.GETMINDATE(0123), 103)

SELECT @MyDate
</code>```

The function itself returns a varchar date like so - '01 Apr 2010 08:00:00.000'.

The SQL Server host is in French settings, so perhaps it's a regional setting issue.

答:
Here is an experiment

```<code>--this returns a value
set language english;
select CAST('01 Apr 2010 08:00:00.000' as date);

--this works
set language french;
select CAST('01 Avr 2010 08:00:00.000' as date);

--this errors out
set language french;
select CAST('01 Apr 2010 08:00:00.000' as date);
</code>```

so you can possibly translate the value, according to local settings (which you can vary in the scope of a query).

Title: Unable to convert varchar to date

Body:
I am trying to convert a function (varchar) to date, but get the below error message.

Error

Failed to convert date and / or time from string.

Script

DECLARE @MyDate date

SET @MyDate = CONVERT(date, dbo.GETMINDATE(0123), 103)

SELECT @MyDate

The function itself returns a varchar date like so - '01 Apr 2010 08:00:00.000'.

The SQL Server host is in French settings, so perhaps it's a regional setting issue.

Body:
Here is an experiment

--this returns a value
set language english;
select CAST('01 Apr 2010 08:00:00.000' as date);

--this works
set language french;
select CAST('01 Avr 2010 08:00:00.000' as date);

--this errors out
set language french;
select CAST('01 Apr 2010 08:00:00.000' as date);

so you can possibly translate the value, according to local settings (which you can vary in the scope of a query).


问:
Some services are not able to be constructed using the library : NetCore.AutoRegisterDi
I am developing asp.net core 3.1 GraphQL based APIs. I used the below reference article to setup automatic DI configuration in the API layer and have used the nuget package : NetCore.AutoRegisterDi

https://www.thereformedprogrammer.net/asp-net-core-fast-and-automatic-dependency-injection-setup/

Here goes the code details:

Code:

Startup.cs:

```<code>public virtual void ConfigureServices(IServiceCollection services) => services
                      .AddGraphQLResolvers()
                      .AddProjectRepositories();
</code>```

ProjectServiceCollectionExtensions.cs

```<code>public static class ProjectServiceCollectionExtensions
{
    public static IServiceCollection AddProjectRepositories(this IServiceCollection services) =>
        services.RegisterAssemblyPublicNonGenericClasses(Assembly.GetAssembly(typeof(CommonService)))
                .Where(c => c.Name.EndsWith("Persistence"))
                .AsPublicImplementedInterfaces(ServiceLifetime.Scoped);

    public static IServiceCollection AddGraphQLResolvers(this IServiceCollection services) =>
       services
           .AddScoped<ICountriesResolver, CountriesResolver>()
           .AddScoped<ICountryGroupsResolver, CountryGroupsResolver>()
           .AddScoped<IDisclaimerResolver, DisclaimerResolver>();
}
</code>```

Here in the above CommonService is part of the Service Layer that ends with Persistence.

CountriesResolver.cs

```<code>public class CountriesResolver : Resolver, ICountriesResolver
{
    private readonly ICountryService _countryService;
    private readonly IHttpContextAccessor _accessor;
    private readonly IDataLoaderContextAccessor _dataLoaderContextAccessor;
    public CountriesResolver(ICountryService countryService, IHttpContextAccessor accessor, IDataLoaderContextAccessor dataLoaderContextAccessor)
    {
        _countryService = countryService ?? throw new ArgumentNullException(nameof(countryService));
        _accessor = accessor;
        _dataLoaderContextAccessor = dataLoaderContextAccessor;
    }

    public void Resolve(GraphQLQuery graphQLQuery)
    {
        var language = _accessor.HttpContext.Items["language"] as LanguageDTO;
        graphQLQuery.FieldAsync<ResponseGraphType<CountryResultType>>("countriesresponse", arguments: new QueryArguments(new QueryArgument<IdGraphType>{Name = "pageNo", Description = "page number"}, new QueryArgument<IdGraphType>{Name = "pageSize", Description = "page size"}), resolve: async context =>
        {
            var pageNo = context.GetArgument<int>("pageNo") == 0 ? 1 : context.GetArgument<int>("pageNo");
            var pageSize = context.GetArgument<int>("pageSize") == 0 ? 100 : context.GetArgument<int>("pageSize");
            if (language != null)
            {
                var loader = _dataLoaderContextAccessor.Context.GetOrAddLoader("GetAllCountries", () => _countryService.GetAllCountriesAsync(language, pageNo, pageSize));
                var list = await context.TryAsyncResolve(async c => await loader.LoadAsync());
                return Response(list);
            }

            return null;
        }

        , description: "All Countries data");
    }
}
</code>```

ICommonService.cs

```<code>using Author.Query.Persistence.DTO;
using System.Threading.Tasks;

namespace Author.Query.Persistence.Interfaces
{
    public interface ICommonService
    {
        LanguageDTO GetLanguageFromLocale(string locale);
        Task<LanguageDTO> GetLanguageFromLocaleAsync(string locale);
    }
}
</code>```

CommonService.cs

```<code>namespace Author.Query.Persistence
{
    public class CommonService : ICommonService
    {
        private readonly AppDbContext _dbContext;
        private readonly IOptions<AppSettings> _appSettings;
        private readonly IMapper _mapper;
        private readonly ICacheService<Languages, LanguageDTO> _cacheService;
        public CommonService(AppDbContext dbContext, IOptions<AppSettings> appSettings, IMapper mapper, ICacheService<Languages, LanguageDTO> cacheService)
        {
            _dbContext = dbContext ?? throw new ArgumentNullException(nameof(dbContext));
            _appSettings = appSettings;
            _mapper = mapper ?? throw new ArgumentNullException(nameof(mapper));
            _cacheService = cacheService ?? throw new ArgumentNullException(nameof(cacheService));
        }

        //public Languages GetLanguageFromLocale(string locale)
        public LanguageDTO GetLanguageFromLocale(string locale)
        {
            return GetLanguagesByFilter(GetFilterValues(locale, true).ToArray());
        }
    }
}
</code>```

ICountryService.cs

```<code>namespace Author.Query.Persistence.Interfaces
{
    public interface ICountryService
    {
        Task<CountryResult> GetAllCountriesAsync(LanguageDTO language, int pageNo, int pageSize);
        Task<CountryDTO> GetCountryAsync(LanguageDTO language, int countryId);
    }
}
</code>```

CountryService.cs

```<code>namespace Author.Query.Persistence
{
    public class CountryService : ICountryService
    {
        private readonly AppDbContext _dbContext;
        private readonly IOptions<AppSettings> _appSettings;
        private readonly ICacheService<Images, ImageDTO> _cacheService;
        public CountryService(TaxathandDbContext dbContext, IOptions<AppSettings> appSettings, ICacheService<Images, ImageDTO> cacheService)
        {
            _dbContext = dbContext ?? throw new ArgumentNullException(nameof(dbContext));
            _cacheService = cacheService ?? throw new ArgumentNullException(nameof(cacheService));
            _appSettings = appSettings;
        }

        public async Task<CountryResult> GetAllCountriesAsync(LanguageDTO language, int pageNo, int pageSize)
        {
            var localeLangId = language.LanguageId;
            var dftLanguageId = int.Parse(_appSettings.Value.DefaultLanguageId);
            // By default pick the localLanguage value
            var countries = await GetAllCountriesDataAsync(localeLangId, pageNo, pageSize);
            // If localLanguage data is not available then pull the data based on default language
            if (countries.Countries.Count == 0)
            {
                countries = await GetAllCountriesDataAsync(dftLanguageId, pageNo, pageSize);
            }

            return countries;
        }

        public async Task<CountryDTO> GetCountryAsync(LanguageDTO language, int countryId)
        {
            var localeLangId = language.LanguageId;
            var dftLanguageId = int.Parse(_appSettings.Value.DefaultLanguageId);
            //var country = new CountryDTO();
            // By default pick the localLanguage value
            var country = await GetCountryDetailsAsync(countryId, localeLangId);
            // If localLanguage data is not available then pull the data based on default language
            if (country == null)
            {
                country = await GetCountryDetailsAsync(countryId, dftLanguageId);
            }

            return country;
        }

        private async Task<CountryDTO> GetCountryDetailsAsync(int countryId, int languageId)
        {
            var images = await _cacheService.GetAllAsync("imagesCacheKey");
            var country = await _dbContext.Countries.AsNoTracking().FirstOrDefaultAsync(c => c.CountryId.Equals(countryId) && c.IsPublished.Equals(true) && c.LanguageId.Equals(languageId));
            if (country == null)
            {
                return null;
            }

            var countryDTO = new CountryDTO{Uuid = country.CountryId, PNGImagePath = images.FirstOrDefault(im => im.ImageId.Equals(country.PNGImageId)).FilePath, SVGImagePath = images.FirstOrDefault(im => im.ImageId.Equals(country.SVGImageId)).FilePath, DisplayName = country.DisplayName, DisplayNameShort = country.DisplayName, Name = Helper.ReplaceChars(country.DisplayName), Path = Helper.ReplaceChars(country.DisplayName), CompleteResponse = true};
            return countryDTO;
        }

        private async Task<CountryResult> GetAllCountriesDataAsync(int languageId, int pageNo, int pageSize)
        {
            var countryList = new CountryResult();
            var images = await _cacheService.GetAllAsync("imagesCacheKey");
            var countries = await _dbContext.Countries.Where(cc => cc.IsPublished.Equals(true) && cc.LanguageId.Equals(languageId)).Select(c => new
            {
            c.CountryId, c.DisplayName, c.PNGImageId, c.SVGImageId
            }

            ).OrderByDescending(c => c.CountryId).Skip((pageNo - 1) * pageSize).Take(pageSize).AsNoTracking().ToListAsync();
            if (countries.Count == 0)
            {
                return null;
            }

            countryList.Countries.AddRange(countries.Select(co => new CountryDTO{Uuid = co.CountryId, PNGImagePath = images.FirstOrDefault(im => im.ImageId.Equals(co.PNGImageId)).FilePath, SVGImagePath = images.FirstOrDefault(im => im.ImageId.Equals(co.SVGImageId)).FilePath, DisplayName = co.DisplayName, DisplayNameShort = co.DisplayName, Name = Helper.ReplaceChars(co.DisplayName), Path = Helper.ReplaceChars(co.DisplayName), CompleteResponse = true}));
            return countryList;
        }
    }
}
</code>```

Error:

```<code>    System.AggregateException
      HResult=0x80131500
      Message=Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Author.Query.New.API.GraphQL.Resolvers.ICountriesResolver Lifetime: Scoped ImplementationType: Author.Query.New.API.GraphQL.Resolvers.CountriesResolver':
Unable to resolve service for type 'Author.Query.Persistence.Interfaces.ICountryService' while attempting to activate 'Author.Query.New.API.GraphQL.Resolvers.CountriesResolver'.) (Error while validating the service descriptor 'ServiceType:
Author.Query.New.API.GraphQL.Resolvers.ICountryGroupsResolver Lifetime: Scoped ImplementationType: Author.Query.New.API.GraphQL.Resolvers.CountryGroupsResolver': Unable to resolve service for type 'Author.Query.Persistence.Interfaces.ICountryGroupService' while attempting to activate 'Author.Query.New.API.GraphQL.Resolvers.CountryGroupsResolver'.) (Error while validating the service descriptor 'ServiceType: Author.Query.New.API.GraphQL.Resolvers.IDisclaimerResolver Lifetime: Scoped ImplementationType: Author.Query.New.API.GraphQL.Resolvers.DisclaimerResolver': Unable to resolve service for type 'Author.Query.Persistence.Interfaces.IDisclaimerService' while attempting to activate 'Author.Query.New.API.GraphQL.Resolvers.DisclaimerResolver'.)
      Source=Microsoft.Extensions.DependencyInjection
      StackTrace:
       at Microsoft.Extensions.DependencyInjection.ServiceProvider..ctor(IEnumerable`1 serviceDescriptors, ServiceProviderOptions options)
       at Microsoft.Extensions.DependencyInjection.ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(IServiceCollection services, ServiceProviderOptions options)
       at Microsoft.Extensions.DependencyInjection.DefaultServiceProviderFactory.CreateServiceProvider(IServiceCollection containerBuilder)
       at Microsoft.Extensions.Hosting.Internal.ServiceFactoryAdapter`1.CreateServiceProvider(Object containerBuilder)
       at Microsoft.Extensions.Hosting.HostBuilder.CreateServiceProvider()
       at Microsoft.Extensions.Hosting.HostBuilder.Build()
       at Author.Query.New.API.Program.Main(String[] args) in /src/QueryStack/Author.Query.New.API/Program.cs:line 15

    Inner Exception 1:
    InvalidOperationException: Error while validating the service descriptor 'ServiceType: Author.Query.New.API.GraphQL.Resolvers.ICountriesResolver Lifetime: Scoped ImplementationType:
Author.Query.New.API.GraphQL.Resolvers.CountriesResolver':
Unable to resolve service for type 'Author.Query.Persistence.Interfaces.ICountryService' while attempting to activate
'Author.Query.New.API.GraphQL.Resolvers.CountriesResolver'.

    Inner Exception 2:
    InvalidOperationException: Unable to resolve service for type
'Author.Query.Persistence.Interfaces.ICountryService' while attempting to activate
'Author.Query.New.API.GraphQL.Resolvers.CountriesResolver'.
</code>```

Can anyone help me to know how to fix this issue?

答:
Your method AddProjectRepositories() does not register CountryService, because the Where filter in RegisterAssemblyPublicNonGenericClasses() looks at classes (Type), not at namespaces.

So perhaps you can change your filter:

```<code>services.RegisterAssemblyPublicNonGenericClasses(Assembly.GetAssembly(typeof(CommonService)))
                .Where(c => c.Name.EndsWith("Service")) // <-- Change "Persistence" to "Service"
                .AsPublicImplementedInterfaces(ServiceLifetime.Scoped);
</code>```

That should register all classes that end with "Service" in the Assembly that contains CommonService.

Body:
I am developing asp.net core 3.1 GraphQL based APIs. I used the below reference article to setup automatic DI configuration in the API layer and have used the nuget package : NetCore.AutoRegisterDi

https://www.thereformedprogrammer.net/asp-net-core-fast-and-automatic-dependency-injection-setup/

Here goes the code details:

Code:

Startup.cs:

public virtual void ConfigureServices(IServiceCollection services) => services
                      .AddGraphQLResolvers()
                      .AddProjectRepositories();

ProjectServiceCollectionExtensions.cs

public static class ProjectServiceCollectionExtensions
{
    public static IServiceCollection AddProjectRepositories(this IServiceCollection services) =>
        services.RegisterAssemblyPublicNonGenericClasses(Assembly.GetAssembly(typeof(CommonService)))
                .Where(c => c.Name.EndsWith("Persistence"))
                .AsPublicImplementedInterfaces(ServiceLifetime.Scoped);

    public static IServiceCollection AddGraphQLResolvers(this IServiceCollection services) =>
       services
           .AddScoped<ICountriesResolver, CountriesResolver>()
           .AddScoped<ICountryGroupsResolver, CountryGroupsResolver>()
           .AddScoped<IDisclaimerResolver, DisclaimerResolver>();
}

Here in the above CommonService is part of the Service Layer that ends with Persistence.

CountriesResolver.cs

public class CountriesResolver : Resolver, ICountriesResolver
{
    private readonly ICountryService _countryService;
    private readonly IHttpContextAccessor _accessor;
    private readonly IDataLoaderContextAccessor _dataLoaderContextAccessor;
    public CountriesResolver(ICountryService countryService, IHttpContextAccessor accessor, IDataLoaderContextAccessor dataLoaderContextAccessor)
    {
        _countryService = countryService ?? throw new ArgumentNullException(nameof(countryService));
        _accessor = accessor;
        _dataLoaderContextAccessor = dataLoaderContextAccessor;
    }

    public void Resolve(GraphQLQuery graphQLQuery)
    {
        var language = _accessor.HttpContext.Items["language"] as LanguageDTO;
        graphQLQuery.FieldAsync<ResponseGraphType<CountryResultType>>("countriesresponse", arguments: new QueryArguments(new QueryArgument<IdGraphType>{Name = "pageNo", Description = "page number"}, new QueryArgument<IdGraphType>{Name = "pageSize", Description = "page size"}), resolve: async context =>
        {
            var pageNo = context.GetArgument<int>("pageNo") == 0 ? 1 : context.GetArgument<int>("pageNo");
            var pageSize = context.GetArgument<int>("pageSize") == 0 ? 100 : context.GetArgument<int>("pageSize");
            if (language != null)
            {
                var loader = _dataLoaderContextAccessor.Context.GetOrAddLoader("GetAllCountries", () => _countryService.GetAllCountriesAsync(language, pageNo, pageSize));
                var list = await context.TryAsyncResolve(async c => await loader.LoadAsync());
                return Response(list);
            }

            return null;
        }

        , description: "All Countries data");
    }
}

ICommonService.cs

using Author.Query.Persistence.DTO;
using System.Threading.Tasks;

namespace Author.Query.Persistence.Interfaces
{
    public interface ICommonService
    {
        LanguageDTO GetLanguageFromLocale(string locale);
        Task<LanguageDTO> GetLanguageFromLocaleAsync(string locale);
    }
}

CommonService.cs

namespace Author.Query.Persistence
{
    public class CommonService : ICommonService
    {
        private readonly AppDbContext _dbContext;
        private readonly IOptions<AppSettings> _appSettings;
        private readonly IMapper _mapper;
        private readonly ICacheService<Languages, LanguageDTO> _cacheService;
        public CommonService(AppDbContext dbContext, IOptions<AppSettings> appSettings, IMapper mapper, ICacheService<Languages, LanguageDTO> cacheService)
        {
            _dbContext = dbContext ?? throw new ArgumentNullException(nameof(dbContext));
            _appSettings = appSettings;
            _mapper = mapper ?? throw new ArgumentNullException(nameof(mapper));
            _cacheService = cacheService ?? throw new ArgumentNullException(nameof(cacheService));
        }

        //public Languages GetLanguageFromLocale(string locale)
        public LanguageDTO GetLanguageFromLocale(string locale)
        {
            return GetLanguagesByFilter(GetFilterValues(locale, true).ToArray());
        }
    }
}

ICountryService.cs

namespace Author.Query.Persistence.Interfaces
{
    public interface ICountryService
    {
        Task<CountryResult> GetAllCountriesAsync(LanguageDTO language, int pageNo, int pageSize);
        Task<CountryDTO> GetCountryAsync(LanguageDTO language, int countryId);
    }
}

CountryService.cs

namespace Author.Query.Persistence
{
    public class CountryService : ICountryService
    {
        private readonly AppDbContext _dbContext;
        private readonly IOptions<AppSettings> _appSettings;
        private readonly ICacheService<Images, ImageDTO> _cacheService;
        public CountryService(TaxathandDbContext dbContext, IOptions<AppSettings> appSettings, ICacheService<Images, ImageDTO> cacheService)
        {
            _dbContext = dbContext ?? throw new ArgumentNullException(nameof(dbContext));
            _cacheService = cacheService ?? throw new ArgumentNullException(nameof(cacheService));
            _appSettings = appSettings;
        }

        public async Task<CountryResult> GetAllCountriesAsync(LanguageDTO language, int pageNo, int pageSize)
        {
            var localeLangId = language.LanguageId;
            var dftLanguageId = int.Parse(_appSettings.Value.DefaultLanguageId);
            // By default pick the localLanguage value
            var countries = await GetAllCountriesDataAsync(localeLangId, pageNo, pageSize);
            // If localLanguage data is not available then pull the data based on default language
            if (countries.Countries.Count == 0)
            {
                countries = await GetAllCountriesDataAsync(dftLanguageId, pageNo, pageSize);
            }

            return countries;
        }

        public async Task<CountryDTO> GetCountryAsync(LanguageDTO language, int countryId)
        {
            var localeLangId = language.LanguageId;
            var dftLanguageId = int.Parse(_appSettings.Value.DefaultLanguageId);
            //var country = new CountryDTO();
            // By default pick the localLanguage value
            var country = await GetCountryDetailsAsync(countryId, localeLangId);
            // If localLanguage data is not available then pull the data based on default language
            if (country == null)
            {
                country = await GetCountryDetailsAsync(countryId, dftLanguageId);
            }

            return country;
        }

        private async Task<CountryDTO> GetCountryDetailsAsync(int countryId, int languageId)
        {
            var images = await _cacheService.GetAllAsync("imagesCacheKey");
            var country = await _dbContext.Countries.AsNoTracking().FirstOrDefaultAsync(c => c.CountryId.Equals(countryId) && c.IsPublished.Equals(true) && c.LanguageId.Equals(languageId));
            if (country == null)
            {
                return null;
            }

            var countryDTO = new CountryDTO{Uuid = country.CountryId, PNGImagePath = images.FirstOrDefault(im => im.ImageId.Equals(country.PNGImageId)).FilePath, SVGImagePath = images.FirstOrDefault(im => im.ImageId.Equals(country.SVGImageId)).FilePath, DisplayName = country.DisplayName, DisplayNameShort = country.DisplayName, Name = Helper.ReplaceChars(country.DisplayName), Path = Helper.ReplaceChars(country.DisplayName), CompleteResponse = true};
            return countryDTO;
        }

        private async Task<CountryResult> GetAllCountriesDataAsync(int languageId, int pageNo, int pageSize)
        {
            var countryList = new CountryResult();
            var images = await _cacheService.GetAllAsync("imagesCacheKey");
            var countries = await _dbContext.Countries.Where(cc => cc.IsPublished.Equals(true) && cc.LanguageId.Equals(languageId)).Select(c => new
            {
            c.CountryId, c.DisplayName, c.PNGImageId, c.SVGImageId
            }

            ).OrderByDescending(c => c.CountryId).Skip((pageNo - 1) * pageSize).Take(pageSize).AsNoTracking().ToListAsync();
            if (countries.Count == 0)
            {
                return null;
            }

            countryList.Countries.AddRange(countries.Select(co => new CountryDTO{Uuid = co.CountryId, PNGImagePath = images.FirstOrDefault(im => im.ImageId.Equals(co.PNGImageId)).FilePath, SVGImagePath = images.FirstOrDefault(im => im.ImageId.Equals(co.SVGImageId)).FilePath, DisplayName = co.DisplayName, DisplayNameShort = co.DisplayName, Name = Helper.ReplaceChars(co.DisplayName), Path = Helper.ReplaceChars(co.DisplayName), CompleteResponse = true}));
            return countryList;
        }
    }
}

Error:

    System.AggregateException
      HResult=0x80131500
      Message=Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Author.Query.New.API.GraphQL.Resolvers.ICountriesResolver Lifetime: Scoped ImplementationType: Author.Query.New.API.GraphQL.Resolvers.CountriesResolver':
Unable to resolve service for type 'Author.Query.Persistence.Interfaces.ICountryService' while attempting to activate 'Author.Query.New.API.GraphQL.Resolvers.CountriesResolver'.) (Error while validating the service descriptor 'ServiceType:
Author.Query.New.API.GraphQL.Resolvers.ICountryGroupsResolver Lifetime: Scoped ImplementationType: Author.Query.New.API.GraphQL.Resolvers.CountryGroupsResolver': Unable to resolve service for type 'Author.Query.Persistence.Interfaces.ICountryGroupService' while attempting to activate 'Author.Query.New.API.GraphQL.Resolvers.CountryGroupsResolver'.) (Error while validating the service descriptor 'ServiceType: Author.Query.New.API.GraphQL.Resolvers.IDisclaimerResolver Lifetime: Scoped ImplementationType: Author.Query.New.API.GraphQL.Resolvers.DisclaimerResolver': Unable to resolve service for type 'Author.Query.Persistence.Interfaces.IDisclaimerService' while attempting to activate 'Author.Query.New.API.GraphQL.Resolvers.DisclaimerResolver'.)
      Source=Microsoft.Extensions.DependencyInjection
      StackTrace:
       at Microsoft.Extensions.DependencyInjection.ServiceProvider..ctor(IEnumerable`1 serviceDescriptors, ServiceProviderOptions options)
       at Microsoft.Extensions.DependencyInjection.ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(IServiceCollection services, ServiceProviderOptions options)
       at Microsoft.Extensions.DependencyInjection.DefaultServiceProviderFactory.CreateServiceProvider(IServiceCollection containerBuilder)
       at Microsoft.Extensions.Hosting.Internal.ServiceFactoryAdapter`1.CreateServiceProvider(Object containerBuilder)
       at Microsoft.Extensions.Hosting.HostBuilder.CreateServiceProvider()
       at Microsoft.Extensions.Hosting.HostBuilder.Build()
       at Author.Query.New.API.Program.Main(String[] args) in /src/QueryStack/Author.Query.New.API/Program.cs:line 15

    Inner Exception 1:
    InvalidOperationException: Error while validating the service descriptor 'ServiceType: Author.Query.New.API.GraphQL.Resolvers.ICountriesResolver Lifetime: Scoped ImplementationType:
Author.Query.New.API.GraphQL.Resolvers.CountriesResolver':
Unable to resolve service for type 'Author.Query.Persistence.Interfaces.ICountryService' while attempting to activate
'Author.Query.New.API.GraphQL.Resolvers.CountriesResolver'.

    Inner Exception 2:
    InvalidOperationException: Unable to resolve service for type
'Author.Query.Persistence.Interfaces.ICountryService' while attempting to activate
'Author.Query.New.API.GraphQL.Resolvers.CountriesResolver'.

Can anyone help me to know how to fix this issue?

Body:
Your method AddProjectRepositories() does not register CountryService, because the Where filter in RegisterAssemblyPublicNonGenericClasses() looks at classes (Type), not at namespaces.

So perhaps you can change your filter:

services.RegisterAssemblyPublicNonGenericClasses(Assembly.GetAssembly(typeof(CommonService)))
                .Where(c => c.Name.EndsWith("Service")) // <-- Change "Persistence" to "Service"
                .AsPublicImplementedInterfaces(ServiceLifetime.Scoped);

That should register all classes that end with "Service" in the Assembly that contains CommonService.