问:
Haskell function that checks if a word contains in binary tree
I have to write a function is Haskell that checks if a word contains in binary tree. The only requirement is that the last symbol of the word, should be a leaf of the tree.

Here is the tree I got:

```<code>t1 :: BTree Char
t1 = Node 'a'   (Node 'c'   (Node 'f' Empty Empty)
                            (Node 'd' Empty Empty))
                (Node 'b' Empty
                            (Node 'e' Empty Empty))
</code>```

And here is what I wrote, but its only for Tree with one element:

```<code>containsWord :: BTree Char -> String -> Bool
containsWord Empty _ = False
containsWord (Node v Empty Empty) ch
|v == ch    = True
|otherwise  = False
</code>```

I don't know how to continue.
Here are two examples:

```<code>containsWord t1 "acd" → True
containsWord t1 "ac" → False
</code>```

答:
The first problem here is that the statement v == ch will not compile because v is a Char and ch is a String. The second guard should therefore be (note also that your guards are not necessary, since v == ch is already the value you need):

```<code>containsWord (Node v Empty Empty) [ch] = v == ch
</code>```

Given this fix, what patters are now not matched? You need to match on non-leaf nodes and strings longer than one character. So you should think about what definitions fit with these three patterns:

```<code>containsWord _            []
containsWord (Node v l r) (ch : s)
</code>```

The first one is the case of matching any node against an empty string. Given your problem statement above, this should never be true, thus:

```<code>containsWord _ [] = False
</code>```

The second one is the primary recursive case of your function. Check if the current node's value matches the first character, then check if either subtree matches the rest of the string.

```<code>containsWord (Node v l r) s@(ch : rs) =
    | ch == v   = containsWord l rs || containsWord r rs
    | otherwise = containsWord l  s || containsWord r  s
</code>```

Now I would suggest that containsWord Empty "" should be True. If that's the case, you need to add another pattern to the beginning:

```<code>containsWord Empty [] = True
</code>```

In this case, the first pattern we discussed (containsWord (Node v Empty Empty) [ch]) is actually unnecessary.

Body:
I have to write a function is Haskell that checks if a word contains in binary tree. The only requirement is that the last symbol of the word, should be a leaf of the tree.

Here is the tree I got:

t1 :: BTree Char
t1 = Node 'a'   (Node 'c'   (Node 'f' Empty Empty)
                            (Node 'd' Empty Empty))
                (Node 'b' Empty
                            (Node 'e' Empty Empty))

And here is what I wrote, but its only for Tree with one element:

containsWord :: BTree Char -> String -> Bool
containsWord Empty _ = False
containsWord (Node v Empty Empty) ch
|v == ch    = True
|otherwise  = False

I don't know how to continue.
Here are two examples:

containsWord t1 "acd" → True
containsWord t1 "ac" → False

Body:
The first problem here is that the statement v == ch will not compile because v is a Char and ch is a String. The second guard should therefore be (note also that your guards are not necessary, since v == ch is already the value you need):

containsWord (Node v Empty Empty) [ch] = v == ch

Given this fix, what patters are now not matched? You need to match on non-leaf nodes and strings longer than one character. So you should think about what definitions fit with these three patterns:

containsWord _            []
containsWord (Node v l r) (ch : s)

The first one is the case of matching any node against an empty string. Given your problem statement above, this should never be true, thus:

containsWord _ [] = False

The second one is the primary recursive case of your function. Check if the current node's value matches the first character, then check if either subtree matches the rest of the string.

containsWord (Node v l r) s@(ch : rs) =
    | ch == v   = containsWord l rs || containsWord r rs
    | otherwise = containsWord l  s || containsWord r  s

Now I would suggest that containsWord Empty "" should be True. If that's the case, you need to add another pattern to the beginning:

containsWord Empty [] = True

In this case, the first pattern we discussed (containsWord (Node v Empty Empty) [ch]) is actually unnecessary.


来源: stackexchange

问:
Magic Link Authentication in react SPA
For a small app catering to a very small set of users, we are planning to implement magic link authentication. The user would come to the application, enter their email address, get a magic link on the email address, after the user clicks on the link, they are logged in to the app.

I am not able to find enough resources to figure out how to do it in a SPA. Here are some helpful links:

Magic Link with Node

https://medium.com/@aleksandrasays/sending-magic-links-with-nodejs-765a8686996

https://medium.com/one-more-thing-studio/how-to-make-magic-links-with-node-1d164c036e29

Magic Link with Auth0

https://auth0.com/passwordless

This is the SPA workflow that I have in mind:

User comes to the SPA

The SPA takes the user to the login page where they can provide their email address.

The SPA sends the email address to the backend api

The api decides whether or not the user is registered, and sends them an email with a short lived jwt.

Clicking on this link takes user to a SPA route with the jwt in query params.

The Frontend forwards this jwt to the api backend, and the api backend verifies the jwt and sets a cookie

This cookie can then be used to maintain the user session.

I want to verify this workflow, but I am not able to find enough resources.
Specifically, I want to clarify whether the magic link should send the user to the SPA and the SPA should be responsible for extracting the jwt and sending it to the API backend, or is there another way to do it?

Is this how this should be implemented? What are the security implications?

I am using react and react-router.

答:
Checkout this Reack Hook use-magic-link to integration Magic Link very quickly into a React app.

Read this article for more info: Simple Auth Setup for Your React App

ContentLicense: CC BY-SA 4.0

Title: Magic Link Authentication in react SPA


问:
Using Powershell called from a bat file, Need to get owner/user of a windows process, but owner isn't showing up
I need to get the path and owner of certain processes on a remote computer and use a batch file to get it.  So far, I've come up with something that gives me the path, but not the owner:

```<code>powershell -command "Get-WmiObject -Class win32_process -ComputerName myserver.mydomain.local -Filter 'name like """"%%myprocess%%""""' | select path,GetOwner"
</code>```

For that, GetOwner is blank.

How can I get this to work or accomplish the same objective with another PS query or batch command?

答:
GetOwner() is a method.  User is a property returned by getowner() that is probably what you want.

```<code>set myprocess=powershell
powershell "Get-WmiObject win32_process -computername myserver.mydomain.local | where name -match %myprocess% | select path,@{n='Owner';e={$_.getowner().user}}"

Path                                                      Owner
----                                                      -----
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe admin
</code>```

Or you can use get-process.  EDIT:  Hmm looks like -computername and -includeusername can't go together.  I can test it with "%computername%" but not "localhost".

```<code>powershell "get-process -computername %computername% -includeusername *%myprocess%* | select path,username"

Get-Process : Parameter set cannot be resolved using the specified named parameters.
At line:1 char:1
+ get-process -computername DESKTOP-JQ7B7TZ -includeusername *powershel ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Get-Process], ParameterBindingException
    + FullyQualifiedErrorId : AmbiguousParameterSet,Microsoft.PowerShell.Commands.GetProcessCommand
</code>```

If remote powershell were working:

```<code>powershell "invoke-command myserver.mydomain.local { get-process -includeusername *%myprocess%* | select path,username }"

Path           : C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
UserName       : DESKTOP-JQ7B7TZ\admin
PSComputerName : myserver.mydomain.local
RunspaceId     : b1bc87a7-1c21-4f91-a238-bbb68978ea6c
</code>```

Body:
I need to get the path and owner of certain processes on a remote computer and use a batch file to get it.  So far, I've come up with something that gives me the path, but not the owner:

powershell -command "Get-WmiObject -Class win32_process -ComputerName myserver.mydomain.local -Filter 'name like """"%%myprocess%%""""' | select path,GetOwner"

For that, GetOwner is blank.

How can I get this to work or accomplish the same objective with another PS query or batch command?

Body:
GetOwner() is a method.  User is a property returned by getowner() that is probably what you want.

set myprocess=powershell
powershell "Get-WmiObject win32_process -computername myserver.mydomain.local | where name -match %myprocess% | select path,@{n='Owner';e={$_.getowner().user}}"

Path                                                      Owner
----                                                      -----
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe admin

Or you can use get-process.  EDIT:  Hmm looks like -computername and -includeusername can't go together.  I can test it with "%computername%" but not "localhost".

powershell "get-process -computername %computername% -includeusername *%myprocess%* | select path,username"

Get-Process : Parameter set cannot be resolved using the specified named parameters.
At line:1 char:1
+ get-process -computername DESKTOP-JQ7B7TZ -includeusername *powershel ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Get-Process], ParameterBindingException
    + FullyQualifiedErrorId : AmbiguousParameterSet,Microsoft.PowerShell.Commands.GetProcessCommand

If remote powershell were working:

powershell "invoke-command myserver.mydomain.local { get-process -includeusername *%myprocess%* | select path,username }"

Path           : C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
UserName       : DESKTOP-JQ7B7TZ\admin
PSComputerName : myserver.mydomain.local
RunspaceId     : b1bc87a7-1c21-4f91-a238-bbb68978ea6c


问:
Use ionic 4 plugin in Cordova Typescript project
i'm trying to use  cordova-plugin-googleplus
to my Cordova typescript project, but i can't find how can i use javascript plugin in typescript project.
Maybe it'll be easier to use ionic plugin in cordova Angular + Typescript project? (BTW. it is the same plugin).
Any advice?</p>

答: You can use this plugin (based on cordova-plugin-googlePlus), but with types.</p>


问:
My visual report throws error, can't determine the relationship between two or more fields
I have a model where cqm_detail is connected with detaildistinct table with 1 to many relationship on cqm_detail[issuenumber] and detaildistinct[issuenumber].

Also I have a table detailhierarchy joined to detaildistinct table with 1 to many relationship on detaildistinct[issuenumber] and detailhierarchy[parentkey].

But when I try to create a visual report, taking issueid from cqm_detail and parentkey from detailhierarchy, it throws an error:

Can’t display the data because powerbi can't determine the relationship between two or more fields.

Can anyone help me fetch parentkey for the issueid?

答:
If your relationships are set up like this

```<code>cpm_detail[issuenumber]    : * <--- 1 : detaildistinct[issuenumber]
detailhierarchy[parentkey] : * <--- 1 : detaildistinct[issuenumber]
</code>```

then detailhierarchy cannot filter cpm_detail since the relationship only activates in the 1-to-many direction.

To get it to work like you expect, you'll either need to make that second one bidirectional or else use the CROSSFILTER function in the relevant measure(s).

You could also use detaildistinct[issuenumber] in your visual instead of detailhierarchy[parentkey] but that's basically ignoring detailhierarchy entirely.

Body:
If your relationships are set up like this

cpm_detail[issuenumber]    : * <--- 1 : detaildistinct[issuenumber]
detailhierarchy[parentkey] : * <--- 1 : detaildistinct[issuenumber]

then detailhierarchy cannot filter cpm_detail since the relationship only activates in the 1-to-many direction.

To get it to work like you expect, you'll either need to make that second one bidirectional or else use the CROSSFILTER function in the relevant measure(s).

You could also use detaildistinct[issuenumber] in your visual instead of detailhierarchy[parentkey] but that's basically ignoring detailhierarchy entirely.


问:
Java to HTML Parser / State Machine
I wish to create a app that translates input java code into HTML formatted java code,

For example:

```<code>public class ReadWithScanner
</code>```

Would become

```<code><span class="public">public</span> <span class="class">class</span> ReadWithScanner
</code>```

However it gets quite complicated when it comes to parameters and regular expressions. Now I have a bit of time on my hands, and I wish to write my own code parser.

How would I start this? and is there any tutorials or online content to not only help me write this, but understand it.

Thanks

答: What you need to do is use ANTLR, it already has Java grammars for parsing Java, then you just need to supply your own templates to output whatever you want from the Abstract Syntax Tree you generate with ANTLR.</p>

ContentLicense: CC BY-SA 3.0

Title: Java to HTML Parser / State Machine

Body:
I wish to create a app that translates input java code into HTML formatted java code,

For example:

public class ReadWithScanner

Would become

public class ReadWithScanner

However it gets quite complicated when it comes to parameters and regular expressions. Now I have a bit of time on my hands, and I wish to write my own code parser.

How would I start this? and is there any tutorials or online content to not only help me write this, but understand it.

Thanks


问:
Error no exported member 'HTTP_PARAMS_FACTORY'
I'm following Backbase Frontend Essentials course on https://bbacademy.learnupon.com/ - and the task was to generate a data module with RAML (the RAML was provided).  I downloaded the provided RAML, followed the tutorial, but when I went to view in the browser my terminal shows the following error:

```<code>ERROR in libs/exchange-rate-data/src/exchange-rate-data.service.ts(5,33): error TS2305: Module '"../../../node_modules/@backbase/foundation-ang/data-http/backbase-foundation-ang-data-http"' has no exported member 'HTTP_PARAMS_FACTORY'.
    libs/exchange-rate-data/src/exchange-rate-data.service.ts(5,54): error TS2305: Module '"../../../node_modules/@backbase/foundation-ang/data-http/backbase-foundation-ang-data-http"' has no exported member 'HttpParamsFactory'.
</code>```

I haven't touched this file.  Here is what I have tried:

Checked my Node Version - I'm on v10.18.1 (thought maybe an older version was the culprit) and my angular version is 8.

Ran npm install and npm update to update /node modules

I checked ../../../node_modules/@backbase/foundation-ang/data-http/backbase-foundation-ang-data-http and sure enough did not find HTTP_PARAMS_FACTORY nor HttpParamsFactory

Checked Backbase documentation for HTTP_PARAMS_FACTORY and HttpParamsFactory and its part of foundation-ang/data-http API.

I am new to backbase and think this error is coming from the code I was given in the tutorial but I am not sure. Any help would be appreciated.

答:
I have solved the issue, but not 100% certain if all of the below fixed it or not.  This is what I did:
Tutorial says to install @backbase/foundation-ang at version 4.25 but that version didn't have the HttpParamsFactory type alias nor the HTTP_PARAMS_FACTORY const which were both referenced in the downloaded Raml spec given in the tutorial.  I switched to @backbase/foundation-ang version 4.33.0.  I also modified the module file from the provided RAML by importing the HttpClientModule (which the instructor had but I did not by default)and then I modified the provider's array. So my final exchange-rate-data.module.ts file now looks like this:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { InjectionToken, ModuleWithProviders, Optional } from "@angular/core";
import { HttpClientModule } from "@angular/common/http";
import { createServiceDataHttpConfig, DATA_HTTP_CONFIG, DataHttpModule, ServiceDataHttpConfig } from "@backbase/foundation-ang/data-http";
import { EXCHANGE_RATE_DATA_CONFIG, ExchangeRateDataService } from "./exchange-rate-data.service";
export const CONFIG_VALUE = new InjectionToken("ExchangeRateData Data Service :: Custom Http Config");
// export function createExchangeRateDataServiceDataHttpConfig(globalConfig: ServiceDataHttpConfig, serviceConfig?: Partial<ServiceDataHttpConfig>) {
//     return createServiceDataHttpConfig(globalConfig, serviceConfig ? serviceConfig : { "servicePath": "" });
// }
@NgModule({
    declarations: [],
    imports: [
        CommonModule,
        DataHttpModule,
        HttpClientModule
    ],
    providers: [ExchangeRateDataService, {provide: CONFIG_VALUE, useValue: {
        servicePath: '',
    }}, {
        provide: EXCHANGE_RATE_DATA_CONFIG,
        useFactory: createServiceDataHttpConfig,
        deps: [DATA_HTTP_CONFIG, CONFIG_VALUE],
        }]
})```

Body:
I'm following Backbase Frontend Essentials course on https://bbacademy.learnupon.com/ - and the task was to generate a data module with RAML (the RAML was provided).  I downloaded the provided RAML, followed the tutorial, but when I went to view in the browser my terminal shows the following error:

ERROR in libs/exchange-rate-data/src/exchange-rate-data.service.ts(5,33): error TS2305: Module '"../../../node_modules/@backbase/foundation-ang/data-http/backbase-foundation-ang-data-http"' has no exported member 'HTTP_PARAMS_FACTORY'.
    libs/exchange-rate-data/src/exchange-rate-data.service.ts(5,54): error TS2305: Module '"../../../node_modules/@backbase/foundation-ang/data-http/backbase-foundation-ang-data-http"' has no exported member 'HttpParamsFactory'.

I haven't touched this file.  Here is what I have tried:

Checked my Node Version - I'm on v10.18.1 (thought maybe an older version was the culprit) and my angular version is 8.

Ran npm install and npm update to update /node modules

I checked ../../../node_modules/@backbase/foundation-ang/data-http/backbase-foundation-ang-data-http and sure enough did not find HTTP_PARAMS_FACTORY nor HttpParamsFactory

Checked Backbase documentation for HTTP_PARAMS_FACTORY and HttpParamsFactory and its part of foundation-ang/data-http API.

I am new to backbase and think this error is coming from the code I was given in the tutorial but I am not sure. Any help would be appreciated.


问:
Unregistering BroadcastReceiver registered in Activity context results in IllegalArgumentException crash
The crash is pretty strange one.

In onStart, BroadcastReceiver that is stored in the Activity field is registered. In onStop, this BroadcastReceiver is unregistered. When BroadcastReceiver was successfully registered, I also set isRegistered field to true, and before I unregister the receiver, I check this field to see if we need

However, in Crashlytics I see that sometimes this fails, and the whole app crashes with IllegalArgumentException with Receiver not registered message, which originates from android.app.LoadedApk#forgetReceiverDispatcher. Which is pretty strange, considering that I check the flag, right?

After I looked into ContextImpl and LoadedApk classes which handle registration/unregistration and added some reflection-based diagnostics, it got even more mysterious. In short, on every crash like that I will extract the map of existing Context to BroadcastReceiver (see ContextImpl.java:1590 and LoadedApk.java:1361).

When it unregisters normally, without a crash I can see a map like this:

```<code>com.mypackage.myapp.MyAppContext instance -> list of instances that are registered app wide
com.mypackage.myapp.MyActivity1 instance -> list of instances that are registered for Activity1
com.mypackage.myapp.MyActivity2 instance -> list of instances that are registered for Activity2
...
</code>```

However, in the event of the crash this map looks like this:

```<code>com.mypackage.myapp.MyAppContext instance -> list of instances that are registered app wide
</code>```

i.e. there are no activities in which my BroadcastReceiver is registered, even though I never called unregisterReceiver!

It only happens in one specific activity, so my first guess was that this activity is leaked somehow, onDestroy lifecycle gets called, Activity entry get removed from receivers map, and then obviously the receiver won't be there when we try to unregister it. However, if that's the case, why is onStop being called after onDestroy then? And why then the receivers list is completely empty?

And if it's not the leak, then what can lead to such puzzling behaviour? I truly hope that somebody else has experienced such a strange occurrence, and may be able to help me, because right now I'm all out of ideas.

答:
I have done the implementation in this way:

Releasing the receiver in the onDestroy event

```<code>@Override
public void onDestroy() {

    // ...releasing more objects

    LocalBroadcastManager.getInstance(this).unregisterReceiver(testReceiver);
    super.onDestroy();
}
</code>```

```<code>@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // ... more initializations

    initializeBroadcastReceivers();
}

private void initializeBroadcastReceivers()
{
    LocalBroadcastManager.getInstance(this)
      .registerReceiver(testReceiver,
        new IntentFilter("testReceiver"));
}

private BroadcastReceiver testReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        // some code
    }
};
</code>```

Body:
The crash is pretty strange one.

In onStart, BroadcastReceiver that is stored in the Activity field is registered. In onStop, this BroadcastReceiver is unregistered. When BroadcastReceiver was successfully registered, I also set isRegistered field to true, and before I unregister the receiver, I check this field to see if we need

However, in Crashlytics I see that sometimes this fails, and the whole app crashes with IllegalArgumentException with Receiver not registered message, which originates from android.app.LoadedApk#forgetReceiverDispatcher. Which is pretty strange, considering that I check the flag, right?

After I looked into ContextImpl and LoadedApk classes which handle registration/unregistration and added some reflection-based diagnostics, it got even more mysterious. In short, on every crash like that I will extract the map of existing Context to BroadcastReceiver (see ContextImpl.java:1590 and LoadedApk.java:1361).

When it unregisters normally, without a crash I can see a map like this:

com.mypackage.myapp.MyAppContext instance -> list of instances that are registered app wide
com.mypackage.myapp.MyActivity1 instance -> list of instances that are registered for Activity1
com.mypackage.myapp.MyActivity2 instance -> list of instances that are registered for Activity2
...

However, in the event of the crash this map looks like this:

com.mypackage.myapp.MyAppContext instance -> list of instances that are registered app wide

i.e. there are no activities in which my BroadcastReceiver is registered, even though I never called unregisterReceiver!

It only happens in one specific activity, so my first guess was that this activity is leaked somehow, onDestroy lifecycle gets called, Activity entry get removed from receivers map, and then obviously the receiver won't be there when we try to unregister it. However, if that's the case, why is onStop being called after onDestroy then? And why then the receivers list is completely empty?

And if it's not the leak, then what can lead to such puzzling behaviour? I truly hope that somebody else has experienced such a strange occurrence, and may be able to help me, because right now I'm all out of ideas.

Body:
I have done the implementation in this way:

Releasing the receiver in the onDestroy event

@Override
public void onDestroy() {

    // ...releasing more objects

    LocalBroadcastManager.getInstance(this).unregisterReceiver(testReceiver);
    super.onDestroy();
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // ... more initializations

    initializeBroadcastReceivers();
}

private void initializeBroadcastReceivers()
{
    LocalBroadcastManager.getInstance(this)
      .registerReceiver(testReceiver,
        new IntentFilter("testReceiver"));
}

private BroadcastReceiver testReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        // some code
    }
};


问:
java.nio.file.AccessDeniedException of Jenkins when Jenkins container accessing the local folder on my system
I have run the Jenkins Docker Container. When Jenkins is up, I have created a new item by name Ant_Build. Under Ant_Build configurations, for General tab and when clicked on Advanced, I have checked the 'Use Custom Workspace' and have provided the value as D:\BuildSourceCode\CRONUS\RM_OFFICE\RMRest

Under Build configurations, I have provided Build File location as: D:\BuildSourceCode\CRONUS\RM_OFFICE\RMRest\Sources\BuildFiles\build.xml

I have provided Properties location as D:\BuildSourceCode\CRONUS\RM_OFFICE\RMRest\Sources\build.properties

When I clicked on Build Now for Ant_Build, I am getting the following error.

```<code>Console Output:

    Started by user admin
    Running as SYSTEM
    Building in workspace D:\BuildSourceCode\CRONUS\RM_OFFICE\RMRest
    java.nio.file.AccessDeniedException: /D:\BuildSourceCode\CRONUS\RM_OFFICE\RMRest
        at sun.nio.fs.UnixException.translateToIOException(UnixException.java:84)
        at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:102)
        at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:107)
        at sun.nio.fs.UnixFileSystemProvider.createDirectory(UnixFileSystemProvider.java:384)
        at java.nio.file.Files.createDirectory(Files.java:674)
        at java.nio.file.Files.createAndCheckIsDirectory(Files.java:781)
        at java.nio.file.Files.createDirectories(Files.java:767)
        at hudson.FilePath.mkdirs(FilePath.java:3260)
        at hudson.FilePath.access$1300(FilePath.java:211)
        at hudson.FilePath$Mkdirs.invoke(FilePath.java:1251)
        at hudson.FilePath$Mkdirs.invoke(FilePath.java:1247)
        at hudson.FilePath.act(FilePath.java:1075)
        at hudson.FilePath.act(FilePath.java:1058)
        at hudson.FilePath.mkdirs(FilePath.java:1243)
        at hudson.model.AbstractProject.checkout(AbstractProject.java:1200)
        at hudson.model.AbstractBuild$AbstractBuildExecution.defaultCheckout(AbstractBuild.java:574)
        at jenkins.scm.SCMCheckoutStrategy.checkout(SCMCheckoutStrategy.java:86)
        at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:499)
        at hudson.model.Run.execute(Run.java:1880)
        at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
        at hudson.model.ResourceController.execute(ResourceController.java:97)
        at hudson.model.Executor.run(Executor.java:428)
    Finished: FAILURE
</code>```

Can anyone help me execute the Ant_Build job correctly on Jenkins Docker Container ?

答:
Please follow the below link, it's provided by Jenkins

https://github.com/jenkinsci/docker/blob/master/README.md

I used the below command :

docker run -d -p 8080:8080 -v jenkins_home:/var/jenkins_home -u root jenkins/jenkins

Body:
I have run the Jenkins Docker Container. When Jenkins is up, I have created a new item by name Ant_Build. Under Ant_Build configurations, for General tab and when clicked on Advanced, I have checked the 'Use Custom Workspace' and have provided the value as D:\BuildSourceCode\CRONUS\RM_OFFICE\RMRest

Under Build configurations, I have provided Build File location as: D:\BuildSourceCode\CRONUS\RM_OFFICE\RMRest\Sources\BuildFiles\build.xml

I have provided Properties location as D:\BuildSourceCode\CRONUS\RM_OFFICE\RMRest\Sources\build.properties

When I clicked on Build Now for Ant_Build, I am getting the following error.

Console Output:

    Started by user admin
    Running as SYSTEM
    Building in workspace D:\BuildSourceCode\CRONUS\RM_OFFICE\RMRest
    java.nio.file.AccessDeniedException: /D:\BuildSourceCode\CRONUS\RM_OFFICE\RMRest
        at sun.nio.fs.UnixException.translateToIOException(UnixException.java:84)
        at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:102)
        at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:107)
        at sun.nio.fs.UnixFileSystemProvider.createDirectory(UnixFileSystemProvider.java:384)
        at java.nio.file.Files.createDirectory(Files.java:674)
        at java.nio.file.Files.createAndCheckIsDirectory(Files.java:781)
        at java.nio.file.Files.createDirectories(Files.java:767)
        at hudson.FilePath.mkdirs(FilePath.java:3260)
        at hudson.FilePath.access$1300(FilePath.java:211)
        at hudson.FilePath$Mkdirs.invoke(FilePath.java:1251)
        at hudson.FilePath$Mkdirs.invoke(FilePath.java:1247)
        at hudson.FilePath.act(FilePath.java:1075)
        at hudson.FilePath.act(FilePath.java:1058)
        at hudson.FilePath.mkdirs(FilePath.java:1243)
        at hudson.model.AbstractProject.checkout(AbstractProject.java:1200)
        at hudson.model.AbstractBuild$AbstractBuildExecution.defaultCheckout(AbstractBuild.java:574)
        at jenkins.scm.SCMCheckoutStrategy.checkout(SCMCheckoutStrategy.java:86)
        at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:499)
        at hudson.model.Run.execute(Run.java:1880)
        at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
        at hudson.model.ResourceController.execute(ResourceController.java:97)
        at hudson.model.Executor.run(Executor.java:428)
    Finished: FAILURE

Can anyone help me execute the Ant_Build job correctly on Jenkins Docker Container ?


问:
Running difference month over month
I have a sample data, i want to get the Difference in month over month data 'Lag' column for only row B

答:
If there always is just one row per month and id, then just use lag(). You can wrap this in a case expression so it only applies to id 'B'.

```<code>select
    id,
    date,
    data,
    case when id = 'B'
        then data - lag(data) over(partition by id order by date)
    end lag_diff
from mytable
</code>```

Title: Running difference month over month

Body:
If there always is just one row per month and id, then just use lag(). You can wrap this in a case expression so it only applies to id 'B'.

select
    id,
    date,
    data,
    case when id = 'B'
        then data - lag(data) over(partition by id order by date)
    end lag_diff
from mytable


问:
How to calculate x1, y1, x2, y2, x3, y3, x4, y4 for rectangle
I need to find the position of a rectangle on the image. Rectangle points positions are fallowing [X1, Y1, X2, Y2] [7608,1638,7663,1680] also I know Image Height: 4096 and Width: 8192 on which I need to plot the rectangle. The rectangle will be hosted in GeoServer as a WFS layer. However, to visualize the shape I need to calculate x1, y1, x2, y2, x3, y3, x4, y4, x5, y5 somethink like this [[7047,2451],[7021,2266],[6749,2231],[6777,2392],[7047,2451]] from above-given values. How can I do that? I know that x5 ,y5 will be the same as x1, y1 as it is a closing one.

I believe for many of you this is a very basic question but for me it is complicated.

答:
If you have the points minX, maxX, minY, maxY, and if we're talking about a right-angled, level rectangle, then the four points would typically be:

```<code>(minX, minY)-► ■ ═════════════════ ■ ◄-(maxX, minY)
               ║                   ║
               ║                   ║
               ║                   ║  Height = maxY - minY
               ║                   ║
               ║                   ║
(minX, maxY)-► ■ ═════════════════ ■ ◄-(maxX, maxY)

                Width = maxX - minX
</code>```

This assumes that we're dealing with rectangles where (0, 0) is the top-left corner, which is typical in windowed applications. Adjust accordingly if GeoServer rectangles are laid out differently.

Body:
If you have the points minX, maxX, minY, maxY, and if we're talking about a right-angled, level rectangle, then the four points would typically be:

(minX, minY)-► ■ ═════════════════ ■ ◄-(maxX, minY)
               ║                   ║
               ║                   ║
               ║                   ║  Height = maxY - minY
               ║                   ║
               ║                   ║
(minX, maxY)-► ■ ═════════════════ ■ ◄-(maxX, maxY)

                Width = maxX - minX

This assumes that we're dealing with rectangles where (0, 0) is the top-left corner, which is typical in windowed applications. Adjust accordingly if GeoServer rectangles are laid out differently.


问:
How to solve error: no match between expected input batch size and target batch size in PyTorch?
I attempting to create a logistic model on CIFAR10 dataset by PyTorch. However I am getting an error:

ValueError: Expected input batch_size (900) to match target batch_size (300).

What I think is happening is that 3*100 is 300. So may be the 3 axis of the RGB image is doing that but I cant figure how to solve.

These are my hyperparameters.

```<code>batch_size = 100
learning_rate = 0.001

# Other constants
input_size = 32*32
num_classes = 10
</code>```

Here I divide my data into train, validation and test data.

```<code>
transform_train = transforms.Compose([transforms.Resize((32,32)),
                                      transforms.RandomHorizontalFlip(),
                                      transforms.RandomRotation(10),
                                      transforms.RandomAffine(0, shear=10, scale=(0.8,1.2)),
                                      transforms.ColorJitter(brightness=0.2, contrast=0.2, saturation=0.2),
                                      transforms.ToTensor(),
                                      transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
                               ])

transform = transforms.Compose([transforms.Resize((32,32)),
                               transforms.ToTensor(),
                               transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
                               ])
training_dataset = CIFAR10(root='D:\PyTorch\cifar-10-python', train=True, download=True, transform=transform_train)
train_ds, val_ds = random_split(training_dataset, [40000, 10000])
test_ds = CIFAR10(root='D:\PyTorch\cifar-10-python', train=False, download=True, transform=transform)

train_loader = DataLoader(train_ds, batch_size=100, shuffle=True)
val_loader = DataLoader(val_ds, batch_size = 100, shuffle = False)
test_loader = DataLoader(test_ds, batch_size = 100, shuffle=False)
</code>```

This is the model.

```<code>class CifarModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.linear = nn.Linear(input_size,  num_classes)
    def forward(self, xb):
        xb = xb.view(-1, 32*32)
        #xb = xb.reshape(-1, 784)
        print(xb.shape)
        out = self.linear(xb)
        return out

    def training_step(self, batch):
        images, labels = batch
        out = self(images)                  # Generate predictions
        loss = F.cross_entropy(out, labels) # Calculate loss
        return loss

    def validation_step(self, batch):
        images, labels = batch
        out = self(images)                    # Generate predictions
        loss = F.cross_entropy(out, labels)   # Calculate loss
        acc = accuracy(out, labels)           # Calculate accuracy
        return {'val_loss': loss.detach(), 'val_acc': acc.detach()}

    def validation_epoch_end(self, outputs):
        batch_losses = [x['val_loss'] for x in outputs]
        epoch_loss = torch.stack(batch_losses).mean()   # Combine losses
        batch_accs = [x['val_acc'] for x in outputs]
        epoch_acc = torch.stack(batch_accs).mean()      # Combine accuracies
        return {'val_loss': epoch_loss.item(), 'val_acc': epoch_acc.item()}

    def epoch_end(self, epoch, result):
        print("Epoch [{}], val_loss: {:.4f}, val_acc: {:.4f}".format(epoch, result['val_loss'], result['val_acc']))

model = CifarModel()
</code>```

```<code>def accuracy(outputs, labels):
    _, preds = torch.max(outputs, dim=1)
    return torch.tensor(torch.sum(preds == labels).item() / len(preds))
def evaluate(model, val_loader):
    outputs = [model.validation_step(batch) for batch in val_loader]
    return model.validation_epoch_end(outputs)

def fit(epochs, lr, model, train_loader, val_loader, opt_func=torch.optim.SGD):
    history = []
    optimizer = opt_func(model.parameters(), lr)
    for epoch in range(epochs):
        # Training Phase
        for batch in train_loader:
            loss = model.training_step(batch)
            loss.backward()
            optimizer.step()
            optimizer.zero_grad()
        # Validation phase
        result = evaluate(model, val_loader)
        model.epoch_end(epoch, result)
        history.append(result)
    return history
evaluate(model, val_loader)
</code>```

Here's the error I encounter when I run evaluate function:

```<code>torch.Size([900, 1024])

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-23-3621eab8de1a> in <module>
     21         history.append(result)
     22     return history
---> 23 evaluate(model, val_loader)

<ipython-input-23-3621eab8de1a> in evaluate(model, val_loader)
      3     return torch.tensor(torch.sum(preds == labels).item() / len(preds))
      4 def evaluate(model, val_loader):
----> 5     outputs = [model.validation_step(batch) for batch in val_loader]
      6     return model.validation_epoch_end(outputs)
      7

<ipython-input-23-3621eab8de1a> in <listcomp>(.0)
      3     return torch.tensor(torch.sum(preds == labels).item() / len(preds))
      4 def evaluate(model, val_loader):
----> 5     outputs = [model.validation_step(batch) for batch in val_loader]
      6     return model.validation_epoch_end(outputs)
      7

<ipython-input-22-c9e17d21eaff> in validation_step(self, batch)
     19         images, labels = batch
     20         out = self(images)                    # Generate predictions
---> 21         loss = F.cross_entropy(out, labels)   # Calculate loss
     22         acc = accuracy(out, labels)           # Calculate accuracy
     23         return {'val_loss': loss.detach(), 'val_acc': acc.detach()}

~\Anaconda3\lib\site-packages\torch\nn\functional.py in cross_entropy(input, target, weight, size_average, ignore_index, reduce, reduction)
   2019     if size_average is not None or reduce is not None:
   2020         reduction = _Reduction.legacy_get_string(size_average, reduce)
-> 2021     return nll_loss(log_softmax(input, 1), target, weight, None, ignore_index, None, reduction)
   2022
   2023

~\Anaconda3\lib\site-packages\torch\nn\functional.py in nll_loss(input, target, weight, size_average, ignore_index, reduce, reduction)
   1834     if input.size(0) != target.size(0):
   1835         raise ValueError('Expected input batch_size ({}) to match target batch_size ({}).'
-> 1836                          .format(input.size(0), target.size(0)))
   1837     if dim == 2:
   1838         ret = torch._C._nn.nll_loss(input, target, weight, _Reduction.get_enum(reduction), ignore_index)

ValueError: Expected input batch_size (900) to match target batch_size (300).
</code>```

答:
One problem that I am seeing is this line:

```<code>xb = xb.view(-1, 32*32)
</code>```

Here you are saying that the input image has only one channels. In other words, grayscale. Change it to reflect the number of channels (RGB):

```<code>xb = xb.view(-1, 32*32*3)
</code>```

Body:
I attempting to create a logistic model on CIFAR10 dataset by PyTorch. However I am getting an error:

ValueError: Expected input batch_size (900) to match target batch_size (300).

What I think is happening is that 3*100 is 300. So may be the 3 axis of the RGB image is doing that but I cant figure how to solve.

These are my hyperparameters.

batch_size = 100
learning_rate = 0.001

# Other constants
input_size = 32*32
num_classes = 10

Here I divide my data into train, validation and test data.

transform_train = transforms.Compose([transforms.Resize((32,32)),
                                      transforms.RandomHorizontalFlip(),
                                      transforms.RandomRotation(10),
                                      transforms.RandomAffine(0, shear=10, scale=(0.8,1.2)),
                                      transforms.ColorJitter(brightness=0.2, contrast=0.2, saturation=0.2),
                                      transforms.ToTensor(),
                                      transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
                               ])

transform = transforms.Compose([transforms.Resize((32,32)),
                               transforms.ToTensor(),
                               transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
                               ])
training_dataset = CIFAR10(root='D:\PyTorch\cifar-10-python', train=True, download=True, transform=transform_train)
train_ds, val_ds = random_split(training_dataset, [40000, 10000])
test_ds = CIFAR10(root='D:\PyTorch\cifar-10-python', train=False, download=True, transform=transform)

train_loader = DataLoader(train_ds, batch_size=100, shuffle=True)
val_loader = DataLoader(val_ds, batch_size = 100, shuffle = False)
test_loader = DataLoader(test_ds, batch_size = 100, shuffle=False)

This is the model.

class CifarModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.linear = nn.Linear(input_size,  num_classes)
    def forward(self, xb):
        xb = xb.view(-1, 32*32)
        #xb = xb.reshape(-1, 784)
        print(xb.shape)
        out = self.linear(xb)
        return out

    def training_step(self, batch):
        images, labels = batch
        out = self(images)                  # Generate predictions
        loss = F.cross_entropy(out, labels) # Calculate loss
        return loss

    def validation_step(self, batch):
        images, labels = batch
        out = self(images)                    # Generate predictions
        loss = F.cross_entropy(out, labels)   # Calculate loss
        acc = accuracy(out, labels)           # Calculate accuracy
        return {'val_loss': loss.detach(), 'val_acc': acc.detach()}

    def validation_epoch_end(self, outputs):
        batch_losses = [x['val_loss'] for x in outputs]
        epoch_loss = torch.stack(batch_losses).mean()   # Combine losses
        batch_accs = [x['val_acc'] for x in outputs]
        epoch_acc = torch.stack(batch_accs).mean()      # Combine accuracies
        return {'val_loss': epoch_loss.item(), 'val_acc': epoch_acc.item()}

    def epoch_end(self, epoch, result):
        print("Epoch [{}], val_loss: {:.4f}, val_acc: {:.4f}".format(epoch, result['val_loss'], result['val_acc']))

model = CifarModel()

def accuracy(outputs, labels):
    _, preds = torch.max(outputs, dim=1)
    return torch.tensor(torch.sum(preds == labels).item() / len(preds))
def evaluate(model, val_loader):
    outputs = [model.validation_step(batch) for batch in val_loader]
    return model.validation_epoch_end(outputs)

def fit(epochs, lr, model, train_loader, val_loader, opt_func=torch.optim.SGD):
    history = []
    optimizer = opt_func(model.parameters(), lr)
    for epoch in range(epochs):
        # Training Phase
        for batch in train_loader:
            loss = model.training_step(batch)
            loss.backward()
            optimizer.step()
            optimizer.zero_grad()
        # Validation phase
        result = evaluate(model, val_loader)
        model.epoch_end(epoch, result)
        history.append(result)
    return history
evaluate(model, val_loader)

Here's the error I encounter when I run evaluate function:

torch.Size([900, 1024])

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-23-3621eab8de1a> in <module>
     21         history.append(result)
     22     return history
---> 23 evaluate(model, val_loader)

<ipython-input-23-3621eab8de1a> in evaluate(model, val_loader)
      3     return torch.tensor(torch.sum(preds == labels).item() / len(preds))
      4 def evaluate(model, val_loader):
----> 5     outputs = [model.validation_step(batch) for batch in val_loader]
      6     return model.validation_epoch_end(outputs)
      7

<ipython-input-23-3621eab8de1a> in <listcomp>(.0)
      3     return torch.tensor(torch.sum(preds == labels).item() / len(preds))
      4 def evaluate(model, val_loader):
----> 5     outputs = [model.validation_step(batch) for batch in val_loader]
      6     return model.validation_epoch_end(outputs)
      7

<ipython-input-22-c9e17d21eaff> in validation_step(self, batch)
     19         images, labels = batch
     20         out = self(images)                    # Generate predictions
---> 21         loss = F.cross_entropy(out, labels)   # Calculate loss
     22         acc = accuracy(out, labels)           # Calculate accuracy
     23         return {'val_loss': loss.detach(), 'val_acc': acc.detach()}

~\Anaconda3\lib\site-packages\torch\nn\functional.py in cross_entropy(input, target, weight, size_average, ignore_index, reduce, reduction)
   2019     if size_average is not None or reduce is not None:
   2020         reduction = _Reduction.legacy_get_string(size_average, reduce)
-> 2021     return nll_loss(log_softmax(input, 1), target, weight, None, ignore_index, None, reduction)
   2022
   2023

~\Anaconda3\lib\site-packages\torch\nn\functional.py in nll_loss(input, target, weight, size_average, ignore_index, reduce, reduction)
   1834     if input.size(0) != target.size(0):
   1835         raise ValueError('Expected input batch_size ({}) to match target batch_size ({}).'
-> 1836                          .format(input.size(0), target.size(0)))
   1837     if dim == 2:
   1838         ret = torch._C._nn.nll_loss(input, target, weight, _Reduction.get_enum(reduction), ignore_index)

ValueError: Expected input batch_size (900) to match target batch_size (300).

Body:
One problem that I am seeing is this line:

xb = xb.view(-1, 32*32)

Here you are saying that the input image has only one channels. In other words, grayscale. Change it to reflect the number of channels (RGB):

xb = xb.view(-1, 32*32*3)


问:
Mocking a post request using Mockito raises javax.ws.rs.ProcessingException: RESTEASY004655: Unable to invoke request
I'm totally new to Mockito and I need to mock a post request so that I can test a client alone. However, no matter what I do I get the RESTEASY004655: Unable to invoke request exception. This is the simplified version of what I have so far. I have the class TestClassA which sends a post request to an api as follows:

```<code>import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;

import org.jboss.resteasy.client.jaxrs.ResteasyClient;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;

import com.fasterxml.jackson.databind.ObjectMapper;

public class TestClassA {

    public int moveActual(String path) throws IOException {

        Response resp = null;
        String newHome = "0" ;
        ResteasyClient client = new ResteasyClientBuilder().build();
        ResteasyWebTarget callTarget = client.target(path) ;

        Map<String, Object> request = new HashMap<>();
        request.put("operation", "dislocation");
        request.put("direction", "right");
        request.put("amount", "2");
        request.put("unit", "metric");
        String payload = new ObjectMapper().writeValueAsString(request);

        resp = callTarget.request().post(Entity.entity(payload, "application/json"));
        String outcome = resp.readEntity(String.class);
        ObjectMapper outcomeMapper = new ObjectMapper();
        @SuppressWarnings("unchecked")
        Map<String, Object> finalResponse = (Map<String, Object>) outcomeMapper.readValue(outcome, Map.class);

        if (finalResponse != null) {
            newHome = (String) finalResponse.get("coordinate");
        }
        return Integer.parseInt(newHome) ;
    }
}
</code>```

I try to mock the post request using the mockito test bellow:

```<code>import static org.junit.Assert.assertEquals;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Answers;
import org.mockito.ArgumentMatchers;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import static org.mockito.BDDMockito.given;

import java.util.HashMap;
import java.util.Map;

import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;

import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import externalTests.TestClassA;

@RunWith(MockitoJUnitRunner.class)
public class DispositionMockTest {

    @Mock(answer = Answers.RETURNS_DEEP_STUBS)
    ResteasyWebTarget targetMock;

    @InjectMocks
    TestClassA classA;

    @Test
    public void dispositionTest() throws Exception {
        // Given
        Map<String, Integer> outcomeMap = new HashMap<String, Integer>() ;
        outcomeMap.put("coordinate", 4) ;
        Response resp = Response.status(Status.OK).type(MediaType.APPLICATION_JSON).entity(outcomeMap).build() ;

        //  Builder req = DispositionMockTest.fakeRequest() ;
        //  given(req.post(ArgumentMatchers.any(Entity.class))).willReturn(fakeRequest()) ;

        given(targetMock.request().post(ArgumentMatchers.any(Entity.class))).willReturn(resp) ;

        // When
        int result = classA.moveActual("url to what has to run") ;

        // Then
        assertEquals(4, result);
    }
}
</code>```

I also tried to mock the request method using the two commented out lines in the test and have it return more or less fake Builder from the method bellow.

```<code>public static Builder fakeRequest() {
    ResteasyClient httpClient = new ResteasyClientBuilder().build();
    ResteasyWebTarget target = httpClient.target("");
    Builder req = target.request() ;
    return req ;
}
</code>```

But I keep getting this exception.

```<code>javax.ws.rs.ProcessingException: RESTEASY004655: Unable to invoke request: org.apache.http.client.ClientProtocolException
    at org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine.invoke(ApacheHttpClient4Engine.java:325)
    at org.jboss.resteasy.client.jaxrs.internal.ClientInvocation.invoke(ClientInvocation.java:443)
    at org.jboss.resteasy.client.jaxrs.internal.ClientInvocation.invoke(ClientInvocation.java:62)
    at org.jboss.resteasy.client.jaxrs.internal.ClientInvocationBuilder.post(ClientInvocationBuilder.java:219)
    at externalTests.TestClassA.moveActual(TestClassA.java:33)
    at externalTests.DispositionMockTest.dispositionTest(DispositionMockTest.java:60)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.mockito.internal.runners.DefaultInternalRunner$1$1.evaluate(DefaultInternalRunner.java:46)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.mockito.internal.runners.DefaultInternalRunner$1.run(DefaultInternalRunner.java:77)
    at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:83)
    at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:39)
    at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:89)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:542)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:770)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:464)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)
Caused by: org.apache.http.client.ClientProtocolException
    at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:187)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:56)
    at org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine.invoke(ApacheHttpClient4Engine.java:320)
    ... 33 more
Caused by: org.apache.http.ProtocolException: Target host is not specified
    at org.apache.http.impl.conn.DefaultRoutePlanner.determineRoute(DefaultRoutePlanner.java:71)
    at org.apache.http.impl.client.InternalHttpClient.determineRoute(InternalHttpClient.java:125)
    at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184)
    ... 36 more
</code>```

I tried many possible solutions I found online but I can't get anything to work. If anyone knows how I can mock a post request I would be truly thankful to learn from them.

答:
Because you mocked ResteasyWebTarget and didn't define what should be the return of request() method, you got that exception.

You should first mock request and return it to the request() method and define the behavior to post() method from mockedRequest

```<code>@Mock
private Invocation.Builder mockedRequest;

@Test
public void dispositionTest() throws Exception {
    when(targetMock.request()).thenReturn(mockedRequest);
    when(mockedRequest.post(any(Entity.class))).thenReturn(resp) ;
}
</code>```

WebTarget request() doc

Invocation.Builder doc

Body:
I'm totally new to Mockito and I need to mock a post request so that I can test a client alone. However, no matter what I do I get the RESTEASY004655: Unable to invoke request exception. This is the simplified version of what I have so far. I have the class TestClassA which sends a post request to an api as follows:

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;

import org.jboss.resteasy.client.jaxrs.ResteasyClient;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;

import com.fasterxml.jackson.databind.ObjectMapper;

public class TestClassA {

    public int moveActual(String path) throws IOException {

        Response resp = null;
        String newHome = "0" ;
        ResteasyClient client = new ResteasyClientBuilder().build();
        ResteasyWebTarget callTarget = client.target(path) ;

        Map<String, Object> request = new HashMap<>();
        request.put("operation", "dislocation");
        request.put("direction", "right");
        request.put("amount", "2");
        request.put("unit", "metric");
        String payload = new ObjectMapper().writeValueAsString(request);

        resp = callTarget.request().post(Entity.entity(payload, "application/json"));
        String outcome = resp.readEntity(String.class);
        ObjectMapper outcomeMapper = new ObjectMapper();
        @SuppressWarnings("unchecked")
        Map<String, Object> finalResponse = (Map<String, Object>) outcomeMapper.readValue(outcome, Map.class);

        if (finalResponse != null) {
            newHome = (String) finalResponse.get("coordinate");
        }
        return Integer.parseInt(newHome) ;
    }
}

I try to mock the post request using the mockito test bellow:

import static org.junit.Assert.assertEquals;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Answers;
import org.mockito.ArgumentMatchers;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import static org.mockito.BDDMockito.given;

import java.util.HashMap;
import java.util.Map;

import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;

import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import externalTests.TestClassA;

@RunWith(MockitoJUnitRunner.class)
public class DispositionMockTest {

    @Mock(answer = Answers.RETURNS_DEEP_STUBS)
    ResteasyWebTarget targetMock;

    @InjectMocks
    TestClassA classA;

    @Test
    public void dispositionTest() throws Exception {
        // Given
        Map<String, Integer> outcomeMap = new HashMap<String, Integer>() ;
        outcomeMap.put("coordinate", 4) ;
        Response resp = Response.status(Status.OK).type(MediaType.APPLICATION_JSON).entity(outcomeMap).build() ;

        //  Builder req = DispositionMockTest.fakeRequest() ;
        //  given(req.post(ArgumentMatchers.any(Entity.class))).willReturn(fakeRequest()) ;

        given(targetMock.request().post(ArgumentMatchers.any(Entity.class))).willReturn(resp) ;

        // When
        int result = classA.moveActual("url to what has to run") ;

        // Then
        assertEquals(4, result);
    }
}

I also tried to mock the request method using the two commented out lines in the test and have it return more or less fake Builder from the method bellow.

public static Builder fakeRequest() {
    ResteasyClient httpClient = new ResteasyClientBuilder().build();
    ResteasyWebTarget target = httpClient.target("");
    Builder req = target.request() ;
    return req ;
}

But I keep getting this exception.

javax.ws.rs.ProcessingException: RESTEASY004655: Unable to invoke request: org.apache.http.client.ClientProtocolException
    at org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine.invoke(ApacheHttpClient4Engine.java:325)
    at org.jboss.resteasy.client.jaxrs.internal.ClientInvocation.invoke(ClientInvocation.java:443)
    at org.jboss.resteasy.client.jaxrs.internal.ClientInvocation.invoke(ClientInvocation.java:62)
    at org.jboss.resteasy.client.jaxrs.internal.ClientInvocationBuilder.post(ClientInvocationBuilder.java:219)
    at externalTests.TestClassA.moveActual(TestClassA.java:33)
    at externalTests.DispositionMockTest.dispositionTest(DispositionMockTest.java:60)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.mockito.internal.runners.DefaultInternalRunner$1$1.evaluate(DefaultInternalRunner.java:46)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.mockito.internal.runners.DefaultInternalRunner$1.run(DefaultInternalRunner.java:77)
    at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:83)
    at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:39)
    at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:89)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:542)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:770)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:464)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)
Caused by: org.apache.http.client.ClientProtocolException
    at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:187)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:56)
    at org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine.invoke(ApacheHttpClient4Engine.java:320)
    ... 33 more
Caused by: org.apache.http.ProtocolException: Target host is not specified
    at org.apache.http.impl.conn.DefaultRoutePlanner.determineRoute(DefaultRoutePlanner.java:71)
    at org.apache.http.impl.client.InternalHttpClient.determineRoute(InternalHttpClient.java:125)
    at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184)
    ... 36 more

I tried many possible solutions I found online but I can't get anything to work. If anyone knows how I can mock a post request I would be truly thankful to learn from them.

Body:
Because you mocked ResteasyWebTarget and didn't define what should be the return of request() method, you got that exception.

You should first mock request and return it to the request() method and define the behavior to post() method from mockedRequest

@Mock
private Invocation.Builder mockedRequest;

@Test
public void dispositionTest() throws Exception {
    when(targetMock.request()).thenReturn(mockedRequest);
    when(mockedRequest.post(any(Entity.class))).thenReturn(resp) ;
}

WebTarget request() doc

Invocation.Builder doc


问:
How can i resize bootstraps cards for a website using Django?
I'm trying to add some cards from bootstrap to a website to display images of the products with their prices and the option to add then to the cart but since the image in this card are being retrieved from another website, when I tried to load my page the images are too big and the cards don't resize automatically with the browser window so it shows one on top of another:

答:
you can add these properties to the image of the card. </p>

```<code>.card_name img {
  height: 300px!important;
  background-clip: padding-box;
  object-fit: cover;
</code>```

<p>}</p>

Body:
you can add these properties to the image of the card.

.card_name img {
  height: 300px!important;
  background-clip: padding-box;
  object-fit: cover;

}


问:
Check that arguments of a function are the keys of a correct type in a type parameter
I'm trying to build a nice, Rails-like form builder in React with TypeScript. I'm fascinated by the possible compile compile-time checks, and I'm keen to see if there is a certain one I can implement. I'm not sure how to phrase this question abstractly, but I think a small example will illustrate it better anyway.

Let's say I have a generic Input type that is an object with some properties. I'd like to have a function, numericField, that takes an input object and key K where Input[K] is of type number. If I pass a mistyped key or a key of type string, I'd like to get a compiler error.

For example:

interface Person {
  name: string
  age: number
}
```

<p>I'd like to get the following:</p>

<pre class="lang-js prettyprint-override"><code>decimalField<Person>({input: person, key: 'age'})  // works
decimalField<Person>({input: person, key: 'agge'}) // compiler error
decimalField<Person>({input: person, key: 'name'}) // compiler error
</code>```

I've managed to do so with the following type:

export type PropertiesOfSubtype<T, P> = {
  [K in keyof T]-?: Exclude<T[K], undefined | null> extends P ? K : never
}[keyof T]
```

<p>If I define <code>decimalField</code> as:</p>

<pre class="lang-js prettyprint-override"><code>function decimalField<Input>(props: {input: Input, key: PropertiesOfType<Input, number>})
</code>```

..it kinda works. But there is an issue.

I'd like typescript to know that input[key] returns a number. Currently it doesn't. I think there might be a way to rewrite it where it can typecheck as TS knows it will return a string.

I guess my question is: is there a better way to do this?

P.P.: Here's a playground with the example, with what my next step is – an optional/required argument depending if there's a predefined label or on for the field.

答:
When you say you want input[key] to be understood to be a number, you mean inside the implementation of decimalField(), right?   Inside the implementation, Input is an unspecifed generic type parameter.  When types depend on unspecified generic type parameters, the compiler will have a better time understanding that input[key] is of type number if input's type is explicitly constrained to Record<typeof key, number>.  Theoretically the compiler could figure that out itself, but in practice it doesn't perform such higher order analysis with unspecified generics.

You could possibly write it this way:

```<code>type PropertyHaver<T, P> = { [K in PropertiesOfSubtype<T, P>]: P };
</code>```

And then decimalField's generic type parameter can be constrained like this:

```<code>function decimalField<Input extends PropertyHaver<Input, number>>(
    props: { input: Input, key: PropertiesOfSubtype<Input, number> }) {
    const value: number = props.input[props.key]
    return "whatever"
}
</code>```

The implementation understand that input[key] is a number now.  (Note, it's really props.input[props.number].)

Okay, hope that helps; good luck!

Playground link to code

Body:
I'm trying to build a nice, Rails-like form builder in React with TypeScript. I'm fascinated by the possible compile compile-time checks, and I'm keen to see if there is a certain one I can implement. I'm not sure how to phrase this question abstractly, but I think a small example will illustrate it better anyway.

Let's say I have a generic Input type that is an object with some properties. I'd like to have a function, numericField, that takes an input object and key K where Input[K] is of type number. If I pass a mistyped key or a key of type string, I'd like to get a compiler error.

For example:

interface Person {
  name: string
  age: number
}

I'd like to get the following:

decimalField<Person>({input: person, key: 'age'})  // works
decimalField<Person>({input: person, key: 'agge'}) // compiler error
decimalField<Person>({input: person, key: 'name'}) // compiler error

I've managed to do so with the following type:

export type PropertiesOfSubtype<T, P> = {
  [K in keyof T]-?: Exclude<T[K], undefined | null> extends P ? K : never
}[keyof T]

If I define decimalField as:

function decimalField<Input>(props: {input: Input, key: PropertiesOfType<Input, number>})

..it kinda works. But there is an issue.

I'd like typescript to know that input[key] returns a number. Currently it doesn't. I think there might be a way to rewrite it where it can typecheck as TS knows it will return a string.

I guess my question is: is there a better way to do this?

P.P.: Here's a <a href="https://www.typescriptlang.org/play/?ssl=39&ssc=1&pln=39&pc=158#code/JYOwLgpgTgZghgYwgAgArQM4HsTIN4BQyxyIcAthAFzIZhSgDmRJcj1pAruQEbQvF4ANywNIAOW58oNEFP4BfAgQgAPAA6iwyMAE91KVFCwGoYYBAwB5GAGVOPPQYA8AFQA0aAHzIAvPhYAbQBpZFBkAGsIXSwYZFcAXQBaAH4aAFFVBAAbTgATCDcQhM9OEAKYUAg85AAfLmzsnzVIcow0ZBTkUNkIIUVAqJi4xOUYMoRzHGQChGByOGyAMQtsvOcASRB1TjAvAAp1Y3UMGjww7d2aLZ2wTyGaIxNoc0sbe0d9QpvdzzleaA+BQASgCJGQCBwdGQQkWnBQ-lAt0G0QSAmQUAgYE4UFwACIAO4ACzgkH6UDxBCUBEhIGhpmwuH8eDIlBoAHIAFJYIm4AAiWAg7M8bA4AGYxZ5hKJgBJ5DJkABGAAM1Nm80WKwga325yRV2QDJw92iHNF7OQIII6oWy1WeV1F1uNCNIBNujNjHYFqtNs19sd+rALswxsipuQ7NZQstwOUtOh2TgfGy7WZ6OjHPEFCF7nRoo5AEFvVSxhMprg-XbtXkAEybS53ZAAGWT2owByOJlO+CdBp+TaTKZ7reH7sexxeFmsdgcTm+jb+8p8ADJw8MW23UyCaHAQLoCOMQJNgNMq1q1vWB55R+3O8ce3rG9dF8gh+2aLfU+O0JOzNP3jnL4G1uJcASgLxPHfbIaDoBgQEYHdkD3A8jxPM8IDmW0LzrEDfk3Yd727M4+2DZBrzfLcRyon8nlMV4Zw+ec8Kbf5pEgyiUzSWh6CYWNd33MESATbRYVyBFSJRXQ0XBETOO1Px5OyOp6mgjApJkkhMWxXFkEJEkyWgSlqWtTCNWrS9A2fQ1QzdJSMB-dlzVjcFXLc9yPI8gB6Lz4iJaAUGAdo4CU5AYFEHQiSC0ysP9Gtays50bKgRkoJo9dPVzJSi3YABCH1QU8oqSB85ArHJBg8j4sB-JmCB4E4bJtGgmLzJwhKnyS100rHDLI2lMQIEkcDhWyyMljgERBq4EaXNK8QsDqhqmqUzxsGQHAUAQPdkD4WgDDmSpqla7D7Q60iQxSsM1McgbZSG+UCuK57wVKgBhLByHUYBshQcxKGQaBjCgMI4hqgKwnaEBFoqOBGu0Pcamh-azKOmpoKAA" rel="nofollow noreferrer">playground with the example, with what my next step is – an optional/required argument depending if there's a predefined label or on for the field.

Body:
When you say you want input[key] to be understood to be a number, you mean inside the implementation of decimalField(), right?   Inside the implementation, Input is an unspecifed generic type parameter.  When types depend on unspecified generic type parameters, the compiler will have a better time understanding that input[key] is of type number if input's type is explicitly constrained to Record<typeof key, number>.  Theoretically the compiler could figure that out itself, but in practice it doesn't perform such higher order analysis with unspecified generics.

You could possibly write it this way:

type PropertyHaver<T, P> = { [K in PropertiesOfSubtype<T, P>]: P };

And then decimalField's generic type parameter can be constrained like this:

function decimalField<Input extends PropertyHaver<Input, number>>(
    props: { input: Input, key: PropertiesOfSubtype<Input, number> }) {
    const value: number = props.input[props.key]
    return "whatever"
}

The implementation understand that input[key] is a number now.  (Note, it's really props.input[props.number].)

Okay, hope that helps; good luck!

<a href="https://www.typescriptlang.org/play/#code/JYOwLgpgTgZghgYwgAgArQM4HsTIN4BQyxyIcAthAFzIZhSgDmRJcj1pAruQEbQvF4ANywNIAOW58oNEFP4BfAgQgAPAA6iwyMAE91KVFCwGoYYBAwB5GAGVOPPQYA8AFQA0aAHzIAvPgFkAG0AaWRQZABrCF0sGGRXAF0AWgB+GgBRVQQAG04AEwg3UMTPThBCmFAIfOQAHy4cnJ81SAqMNGRU5DDZCCFFIOjY+KTlJ0NjUz0ACTgBqDdPVB9-PGCwiKMTaHNLG3tHfSKPb0SaVGQFAG5lGHKEcxxkQoRgcjgcgDELHPznACSIHUnG0rQg7TQU12ujmC0BwNBnjkvGgXi8AApAuophgaOtQCCwDQgUTPMMLtCzBZrHYHBMEWSuKioD4FABKAIkZAIHB0ZBCT6cDgo6R+ZA4kwYAB0hNBQUl6hlw0SgSgEDAnCguAARAB3AAWcEgCx1BCUBF5IH5pmwuDWpAoHAA5AApLAG3AAESwEGdnjYHAAzEHPMJRMAJPIZMgAIwABiuyle70+PwgfwxBMRxIlmBw5JiNGdgedV3ZBBTH2+v3yWfCOZotoLUSLyBLjHYZY5lYgb2r6cz2aJTfzIELumLZEo3YrBCAA" rel="nofollow noreferrer">Playground link to code


问:
Check if a method type matches a function type
Given the following example, how to check if a method matches a function signature?

```<code>package main

import (
    "fmt"
    "context"
    "reflect"
)

// signature to check
type Fn func(context.Context)

type testStruct struct {}

func (*testStruct) DoSomething(context.Context){}
func (*testStruct) DoSomethingElse([]byte){}

func main() {
    structType := reflect.TypeOf(&testStruct{})
    for i := 0; i < structType.NumMethod(); i++ {
        fmt.Println("======================")
        method := structType.Method(i)
        fmt.Println(method.Name)
        fmt.Println(method.Type.String())

        // compare method and Fn signature
    }
}

</code>```

https://play.golang.org/p/rIDfp0E14ge

答:
1. Using reflect.Value.Type().ConvertibleTo

Note the reflect.ValueOf insted of reflect.TypeOf

```<code>package main

import (
    "context"
    "fmt"
    "reflect"
)

type Fn func(context.Context)

type testStruct struct{}

func (*testStruct) DoSomething(context.Context)           {}
func (*testStruct) DoSomethingElse([]byte)                {}
func (*testStruct) DoSomethingElse2(context.Context) error { return nil }

func main() {
    structType := reflect.ValueOf(&testStruct{})
    for i := 0; i < structType.NumMethod(); i++ {
        fmt.Println("======================")
        method := structType.Method(i)

        // compare method and Fn
        if method.Type().ConvertibleTo(reflect.TypeOf((Fn)(nil))) {
            fmt.Println("function of correct type")
        }
    }
}

</code>```

https://play.golang.org/p/A9_bpURinad

2. Checking inputs and outputs individually

```<code>package main

import (
    "context"
    "fmt"
    "reflect"
)

type Fn func(context.Context)

type testStruct struct{}

func (*testStruct) DoSomething(context.Context) {}
func (*testStruct) DoSomethingElse([]byte)      {}

func main() {
    structType := reflect.TypeOf(&testStruct{})
    rctx := reflect.TypeOf(new(context.Context)).Elem()
    for i := 0; i < structType.NumMethod(); i++ {
        fmt.Println("======================")
        method := structType.Method(i)
        fmt.Println(method.Name)
        fmt.Println(method.Type.String())

        if method.Type.NumIn() != 2 {
            fmt.Println("wrong number of inputs, expected 1")
            continue
        }

        if method.Type.In(1) != rctx {
            fmt.Println("input of wrong type, expected context.Context")
            continue
        }

        if method.Type.NumOut() != 0 {
            fmt.Println("wrong number of outputs, expected 0")
            continue
        }

        fmt.Printf("%v is a function of correct type\n", method.Name)
    }
}
</code>```

https://play.golang.org/p/YDsJ9MSiumF

Body:
Given the following example, how to check if a method matches a function signature?

package main

import (
    "fmt"
    "context"
    "reflect"
)

// signature to check
type Fn func(context.Context)

type testStruct struct {}

func (*testStruct) DoSomething(context.Context){}
func (*testStruct) DoSomethingElse([]byte){}

func main() {
    structType := reflect.TypeOf(&testStruct{})
    for i := 0; i < structType.NumMethod(); i++ {
        fmt.Println("======================")
        method := structType.Method(i)
        fmt.Println(method.Name)
        fmt.Println(method.Type.String())

        // compare method and Fn signature
    }
}

https://play.golang.org/p/rIDfp0E14ge

Body:
1. Using reflect.Value.Type().ConvertibleTo

Note the reflect.ValueOf insted of reflect.TypeOf

package main

import (
    "context"
    "fmt"
    "reflect"
)

type Fn func(context.Context)

type testStruct struct{}

func (*testStruct) DoSomething(context.Context)           {}
func (*testStruct) DoSomethingElse([]byte)                {}
func (*testStruct) DoSomethingElse2(context.Context) error { return nil }

func main() {
    structType := reflect.ValueOf(&testStruct{})
    for i := 0; i < structType.NumMethod(); i++ {
        fmt.Println("======================")
        method := structType.Method(i)

        // compare method and Fn
        if method.Type().ConvertibleTo(reflect.TypeOf((Fn)(nil))) {
            fmt.Println("function of correct type")
        }
    }
}

https://play.golang.org/p/A9_bpURinad

2. Checking inputs and outputs individually

package main

import (
    "context"
    "fmt"
    "reflect"
)

type Fn func(context.Context)

type testStruct struct{}

func (*testStruct) DoSomething(context.Context) {}
func (*testStruct) DoSomethingElse([]byte)      {}

func main() {
    structType := reflect.TypeOf(&testStruct{})
    rctx := reflect.TypeOf(new(context.Context)).Elem()
    for i := 0; i < structType.NumMethod(); i++ {
        fmt.Println("======================")
        method := structType.Method(i)
        fmt.Println(method.Name)
        fmt.Println(method.Type.String())

        if method.Type.NumIn() != 2 {
            fmt.Println("wrong number of inputs, expected 1")
            continue
        }

        if method.Type.In(1) != rctx {
            fmt.Println("input of wrong type, expected context.Context")
            continue
        }

        if method.Type.NumOut() != 0 {
            fmt.Println("wrong number of outputs, expected 0")
            continue
        }

        fmt.Printf("%v is a function of correct type\n", method.Name)
    }
}

https://play.golang.org/p/YDsJ9MSiumF


问:
c++ how to correctly implement parallel ifstream reading
First of, what I am trying to do. I have a class that can deal with a particular type of large files on storage. By dealing with it, I mean basically the following:

```<code>class Large {
  std::ifstream file;
  Large(const char* fname) : file(fname) {
    // read file header, create an index of stuff that's inside, that sort of stuff
    ...
  }

  void read_a_part(int which_part) const {
    // read from ifstream, which unfortunately modifies its state
    fstream.read(...)
  }

  ...
}
</code>```

Now, this is all pseudo code, since I am interested in best practice and not a single particular solution. Function read_a_state will not compile, since it modifies the object state but is declared const.

In what I am trying to achieve, I am not modifying my File (I only read from it), nor am I modifying the instance of Large. Therefore all functions should be declared const and should also be reentrant for parallel work. It seems this cannot be done with a single ifstream as a member of Large. The solutions of not marking the file accessing member functions of Large as const or making the member file mutable are no good. Such solutions are not reentrant. Since ifstream also cannot be copied, it seems it has to be created anew for each call to read_a_part. Therefore, the only working solution that I see is moving file from being a member to being an internal variable of read_a_part (and most other member functions of this class). But is this a good solution performance-wise? Will thousands of calls to ifstream ctor not cause problem with the operating system? Is there not a better way?

答:
It's slightly strange logic to make all const but not const.

For example, compiler can miss repeat calls of read operation (it will think the result will not change).

But:

you can store into class the pointer to file variable and initialize it at constructor (const pointer);

you can store handle on file (result of fopen function). And initialize through constructor.

H-h-hm. Good luck.

Body:
First of, what I am trying to do. I have a class that can deal with a particular type of large files on storage. By dealing with it, I mean basically the following:

class Large {
  std::ifstream file;
  Large(const char* fname) : file(fname) {
    // read file header, create an index of stuff that's inside, that sort of stuff
    ...
  }

  void read_a_part(int which_part) const {
    // read from ifstream, which unfortunately modifies its state
    fstream.read(...)
  }

  ...
}

Now, this is all pseudo code, since I am interested in best practice and not a single particular solution. Function read_a_state will not compile, since it modifies the object state but is declared const.

In what I am trying to achieve, I am not modifying my File (I only read from it), nor am I modifying the instance of Large. Therefore all functions should be declared const and should also be reentrant for parallel work. It seems this cannot be done with a single ifstream as a member of Large. The solutions of not marking the file accessing member functions of Large as const or making the member file mutable are no good. Such solutions are not reentrant. Since ifstream also cannot be copied, it seems it has to be created anew for each call to read_a_part. Therefore, the only working solution that I see is moving file from being a member to being an internal variable of read_a_part (and most other member functions of this class). But is this a good solution performance-wise? Will thousands of calls to ifstream ctor not cause problem with the operating system? Is there not a better way?


问:
How to set soap header in Spring Integration?
I want to send a soap message with Spring Integration. I use Java Config.
I've tried the flolowing interceptor, but the spring integration converts the angle brackets (<>) into html escape characters.

```<code>import org.springframework.ws.client.WebServiceClientException;
import org.springframework.ws.client.support.interceptor.ClientInterceptor;
import org.springframework.ws.context.MessageContext;
import org.springframework.ws.soap.SoapHeader;
import org.springframework.ws.soap.SoapHeaderElement;
import org.springframework.ws.soap.SoapMessage;

public class MyAuthInterceptor implements ClientInterceptor {
    @Override
    public boolean handleRequest(MessageContext messageContext) throws WebServiceClientException {
        SoapMessage soapMessage = (SoapMessage) messageContext.getRequest();
        SoapHeader sh = soapMessage.getSoapHeader();
        QName name = new QName("http://...", "myAuth", "aut");
        sh.addHeaderElement(name).setText("<username>TestUser</username>" + "<password>TestPass</password>");
        return true;
    }
</code>```

Here is the generated soap header:

```<code><SOAP-ENV:Header>
    <aut:myAuth xmlns:aut="http://.../"><username>TestUser</username><password>TestPass</password></aut:myAuth>
</SOAP-ENV:Header>
</code>```

Here is my configuration:

```<code>@Configuration
@EnableIntegration
public class SpringIntegrationConfiguration {

    @Bean
    public PublishSubscribeChannel inputChannel() {
        return new PublishSubscribeChannel();
    }

    @Bean
    public ClientInterceptor myAuthInterceptor() {
        return new MyAuthInterceptor();
    }

    @Bean
    @ServiceActivator(inputChannel = "inputChannel")
    public SimpleWebServiceOutboundGateway myOutput(ClientInterceptor mekAuthInterceptor) {
        SimpleWebServiceOutboundGateway simpleWebServiceOutboundGateway = new SimpleWebServiceOutboundGateway("http://...");
        simpleWebServiceOutboundGateway.setInterceptors(myAuthInterceptor);
        return simpleWebServiceOutboundGateway;
    }
}
</code>```

How can I set the soap header without escaping the angle brackets?

答:
@gary-russell - Your answer made sense from a logical point of view, but there are no "addChildElement" method in org.springframework.ws.soap.. I found them in javax.xml.soap..

So my result looks like the following:

```<code>import javax.xml.XMLConstants;
import javax.xml.namespace.QName;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPHeaderElement;
import javax.xml.soap.SOAPMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ws.client.WebServiceClientException;
import org.springframework.ws.client.support.interceptor.ClientInterceptor;
import org.springframework.ws.context.MessageContext;
import org.springframework.ws.soap.SoapMessage;
import org.springframework.ws.soap.saaj.SaajSoapMessage;

public class MySecurityInterceptor implements ClientInterceptor
{
    private static final Logger log = LoggerFactory.getLogger(MySecurityInterceptor.class);

    @Override
    public boolean handleRequest(MessageContext messageContext) throws WebServiceClientException
    {
        SoapMessage soapMessage = (SoapMessage) messageContext.getRequest();

        QName securityName = new QName(
            "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd",
            "Security",
            XMLConstants.DEFAULT_NS_PREFIX);

        QName usernameToken = new QName(null, "UsernameToken", XMLConstants.DEFAULT_NS_PREFIX);

        QName username = new QName(null, "Username", XMLConstants.DEFAULT_NS_PREFIX);

        QName password = new QName(null, "Password", XMLConstants.DEFAULT_NS_PREFIX);

        try
        {
            SOAPMessage mySoapMessage = ((SaajSoapMessage) soapMessage).getSaajMessage();

            SOAPHeader header = mySoapMessage.getSOAPHeader();

            SOAPHeaderElement securityElement = header.addHeaderElement(securityName);

            SOAPElement usernameTokenElement = securityElement.addChildElement(usernameToken);

            SOAPElement usernameElement = usernameTokenElement.addChildElement(username);

            SOAPElement passwordElement = usernameTokenElement.addChildElement(password);

            usernameElement.setTextContent("jxep-Zenmonics-1-i101@jxtest.local");
            passwordElement.setTextContent("3Sg%T~1q4z!QnH6#+5pD");
        }
        catch (SOAPException e)
        {
            log.error("Error!", e);
        }

        return true;
    }

    @Override
    public boolean handleResponse(MessageContext messageContext) throws WebServiceClientException
    {
        // Auto-generated method stub
        return false;
    }

    @Override
    public boolean handleFault(MessageContext messageContext) throws WebServiceClientException
    {
        // Auto-generated method stub
        return false;
    }

    @Override
    public void afterCompletion(MessageContext messageContext, Exception ex) throws WebServiceClientException
    {
        // Auto-generated method stub
    }
}

</code>```

Body:
I want to send a soap message with Spring Integration. I use Java Config.
I've tried the flolowing interceptor, but the spring integration converts the angle brackets (<>) into html escape characters.

import org.springframework.ws.client.WebServiceClientException;
import org.springframework.ws.client.support.interceptor.ClientInterceptor;
import org.springframework.ws.context.MessageContext;
import org.springframework.ws.soap.SoapHeader;
import org.springframework.ws.soap.SoapHeaderElement;
import org.springframework.ws.soap.SoapMessage;

public class MyAuthInterceptor implements ClientInterceptor {
    @Override
    public boolean handleRequest(MessageContext messageContext) throws WebServiceClientException {
        SoapMessage soapMessage = (SoapMessage) messageContext.getRequest();
        SoapHeader sh = soapMessage.getSoapHeader();
        QName name = new QName("http://...", "myAuth", "aut");
        sh.addHeaderElement(name).setText("<username>TestUser</username>" + "<password>TestPass</password>");
        return true;
    }

Here is the generated soap header:

<SOAP-ENV:Header>
    <aut:myAuth xmlns:aut="http://.../"><username>TestUser</username><password>TestPass</password></aut:myAuth>
</SOAP-ENV:Header>

Here is my configuration:

@Configuration
@EnableIntegration
public class SpringIntegrationConfiguration {

    @Bean
    public PublishSubscribeChannel inputChannel() {
        return new PublishSubscribeChannel();
    }

    @Bean
    public ClientInterceptor myAuthInterceptor() {
        return new MyAuthInterceptor();
    }

    @Bean
    @ServiceActivator(inputChannel = "inputChannel")
    public SimpleWebServiceOutboundGateway myOutput(ClientInterceptor mekAuthInterceptor) {
        SimpleWebServiceOutboundGateway simpleWebServiceOutboundGateway = new SimpleWebServiceOutboundGateway("http://...");
        simpleWebServiceOutboundGateway.setInterceptors(myAuthInterceptor);
        return simpleWebServiceOutboundGateway;
    }
}

How can I set the soap header without escaping the angle brackets?

Body:
@gary-russell - Your answer made sense from a logical point of view, but there are no "addChildElement" method in org.springframework.ws.soap.. I found them in javax.xml.soap..

So my result looks like the following:

import javax.xml.XMLConstants;
import javax.xml.namespace.QName;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPHeaderElement;
import javax.xml.soap.SOAPMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ws.client.WebServiceClientException;
import org.springframework.ws.client.support.interceptor.ClientInterceptor;
import org.springframework.ws.context.MessageContext;
import org.springframework.ws.soap.SoapMessage;
import org.springframework.ws.soap.saaj.SaajSoapMessage;

public class MySecurityInterceptor implements ClientInterceptor
{
    private static final Logger log = LoggerFactory.getLogger(MySecurityInterceptor.class);

    @Override
    public boolean handleRequest(MessageContext messageContext) throws WebServiceClientException
    {
        SoapMessage soapMessage = (SoapMessage) messageContext.getRequest();

        QName securityName = new QName(
            "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd",
            "Security",
            XMLConstants.DEFAULT_NS_PREFIX);

        QName usernameToken = new QName(null, "UsernameToken", XMLConstants.DEFAULT_NS_PREFIX);

        QName username = new QName(null, "Username", XMLConstants.DEFAULT_NS_PREFIX);

        QName password = new QName(null, "Password", XMLConstants.DEFAULT_NS_PREFIX);

        try
        {
            SOAPMessage mySoapMessage = ((SaajSoapMessage) soapMessage).getSaajMessage();

            SOAPHeader header = mySoapMessage.getSOAPHeader();

            SOAPHeaderElement securityElement = header.addHeaderElement(securityName);

            SOAPElement usernameTokenElement = securityElement.addChildElement(usernameToken);

            SOAPElement usernameElement = usernameTokenElement.addChildElement(username);

            SOAPElement passwordElement = usernameTokenElement.addChildElement(password);

            usernameElement.setTextContent("jxep-Zenmonics-1-i101@jxtest.local");
            passwordElement.setTextContent("3Sg%T~1q4z!QnH6#+5pD");
        }
        catch (SOAPException e)
        {
            log.error("Error!", e);
        }

        return true;
    }

    @Override
    public boolean handleResponse(MessageContext messageContext) throws WebServiceClientException
    {
        // Auto-generated method stub
        return false;
    }

    @Override
    public boolean handleFault(MessageContext messageContext) throws WebServiceClientException
    {
        // Auto-generated method stub
        return false;
    }

    @Override
    public void afterCompletion(MessageContext messageContext, Exception ex) throws WebServiceClientException
    {
        // Auto-generated method stub
    }
}