问:
Axios get request getting cors issue
i'm trying to get some data from some endpoint.

I can't share the url of endpoint here but problem with cors.

when i'm using postman everything is ok.

But when make get request from my react app via axios i'm getting this error:

```<code>Refused to set unsafe header "origin"
Access to XMLHttpRequest at 'http://some.com/products.json' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
</code>```

here is my request:

```<code>const baseUrl = "http://some.com/products.json"
const axiosConfig = {
  withCredentials: true,
  headers: {
    Accept: "application/json",
    "Content-Type": "application/json",
  }
};

      axios
      .get(baseUrl, axiosConfig)
      .then(response => {
        console.log(response);
      })
      .catch(error => {
        console.log(error)
      });
</code>```

i tried many things but i can't figure out with this.

答:
You need to enable CORS in your server, if you have access to your server add the following line to your server.

```<code>'Access-Control-Allow-Origin', '*'
</code>```

for nodejs server

```<code>app.use(function(req, res, next) {
  res.setHeader('Access-Control-Allow-Origin', '*');
}
</code>```

for local development you can bypass cors by disabling chrome security, open chrome using --disable-web-security flag, close all instances of Chrome

```<code># Open chrome and disable security
open -a Google\ Chrome --args --disable-web-security --user-data-dir="/Users/junius/chrome/"

# Open Microsoft Edge
open -a Microsoft\ Edge --args --disable-web-security --user-data-dir="/Users/junius/chrome/"
</code>```

Title: Axios get request getting cors issue

Body:
i'm trying to get some data from some endpoint.

I can't share the url of endpoint here but problem with cors.

when i'm using postman everything is ok.

But when make get request from my react app via axios i'm getting this error:

Refused to set unsafe header "origin"
Access to XMLHttpRequest at 'http://some.com/products.json' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

here is my request:

const baseUrl = "http://some.com/products.json"
const axiosConfig = {
  withCredentials: true,
  headers: {
    Accept: "application/json",
    "Content-Type": "application/json",
  }
};

      axios
      .get(baseUrl, axiosConfig)
      .then(response => {
        console.log(response);
      })
      .catch(error => {
        console.log(error)
      });

i tried many things but i can't figure out with this.

Body:
You need to enable CORS in your server, if you have access to your server add the following line to your server.

'Access-Control-Allow-Origin', '*'

for nodejs server

app.use(function(req, res, next) {
  res.setHeader('Access-Control-Allow-Origin', '*');
}

for local development you can bypass cors by disabling chrome security, open chrome using --disable-web-security flag, close all instances of Chrome

# Open chrome and disable security
open -a Google\ Chrome --args --disable-web-security --user-data-dir="/Users/junius/chrome/"

# Open Microsoft Edge
open -a Microsoft\ Edge --args --disable-web-security --user-data-dir="/Users/junius/chrome/"


来源: stackexchange

问:
Java priority queue
Java's priority queue is a data structure with O(log n) complexity for put (insertion) and O(log n) for poll (retrieval and removal of the min element).

C++ STL's multimap has the same functionality but O(1) complexity for retrieval and removal of the min element (begin and erase). Is there an equivalent in Java ?

答: std:multimap will be a tree structure, which means that add and remove together will be O(log n).

OwnerDisplayName: Helltone

ContentLicense: CC BY-SA 3.0

Title: Java priority queue

OwnerDisplayName: Tom Hawtin - tackline

ContentLicense: CC BY-SA 2.5


问:
if statement, boolean value
This method is taken from Murach's C# 2010 book and is given as an example of an method that checks if a string contains a decimal value:

```<code>        // the new IsDecimal method
    public bool IsDecimal(TextBox textBox, string name)
    {
        //make sure the string only contains numbers and numeric formatting
        string s = textBox.Text;
        int decimalCount = 0;
        bool validDecimal = true;
        foreach (char c in s)
        {
            if (!(
                c == '0' || c == '1' || c == '2' ||   // numeric chars
                c == '3' || c == '4' || c == '5' ||
                c == '6' || c == '7' || c == '8' ||
                c == '9' || c == '.' ||
                c == '$' || c == '%' || c == ',' ||  // formatting chars
                c == ' '
                ))
            {
                validDecimal = false;
                break;
            }
            if (c == '.')
            {
                decimalCount++;
            }
        } // end loop

        if (validDecimal && decimalCount <= 1)
        {
            return true;
        }
        else
        {
            MessageBox.Show(name + " must be a decimal number.",
                "Entry Error");
            textBox.Focus();
            return false;
        }
    }
</code>```

My question is about this if statement and boolean value:

```<code>            if (validDecimal && decimalCount <= 1)
        {
            return true;
        }
</code>```

I understand that it should be checking if both validDecimal returns true from above loop and that there is only one decimal point present. I'm quite confused by this, my understanding of bool is that it can hold two values: 1 = true and 0 = false; in both of those cases that if statement would be satisfied (0 is smaller than 1 and 1 is equal). I'm thinking that correct if statement would look something like that: if (validDecimal == true && decimalCount <= 1) but since I'm beginner I'm not sure and this isn't in the errata for this book.

答:
I think you're reading the statement wrong, if you placed parentheses, so that it's obvious what's going on, it would look like

```<code>(validDecimal) && (decimalCount <= 1)
</code>```

not

```<code>(validDecimal && decimalCount) <= 1
</code>```

In English: check that validDecimal is true and decimalCount is at most 1. The comparison against true is implicit, because it's not necessary.

In C#, variable of type bool can have one of two values, true or false, but they don't act as numbers, so you can't say they are 1 and 0 (although they are usually implemented that way).

Also, in most languages, if you mean “a and b are both at most x”, you can't write it as a && b <= x. That's just not how (most) computer languages work.

Title: if statement, boolean value

Body:
This method is taken from Murach's C# 2010 book and is given as an example of an method that checks if a string contains a decimal value:

        // the new IsDecimal method
    public bool IsDecimal(TextBox textBox, string name)
    {
        //make sure the string only contains numbers and numeric formatting
        string s = textBox.Text;
        int decimalCount = 0;
        bool validDecimal = true;
        foreach (char c in s)
        {
            if (!(
                c == '0' || c == '1' || c == '2' ||   // numeric chars
                c == '3' || c == '4' || c == '5' ||
                c == '6' || c == '7' || c == '8' ||
                c == '9' || c == '.' ||
                c == '$' || c == '%' || c == ',' ||  // formatting chars
                c == ' '
                ))
            {
                validDecimal = false;
                break;
            }
            if (c == '.')
            {
                decimalCount++;
            }
        } // end loop

        if (validDecimal && decimalCount <= 1)
        {
            return true;
        }
        else
        {
            MessageBox.Show(name + " must be a decimal number.",
                "Entry Error");
            textBox.Focus();
            return false;
        }
    }

My question is about this if statement and boolean value:

            if (validDecimal && decimalCount <= 1)
        {
            return true;
        }

I understand that it should be checking if both validDecimal returns true from above loop and that there is only one decimal point present. I'm quite confused by this, my understanding of bool is that it can hold two values: 1 = true and 0 = false; in both of those cases that if statement would be satisfied (0 is smaller than 1 and 1 is equal). I'm thinking that correct if statement would look something like that: if (validDecimal == true && decimalCount <= 1) but since I'm beginner I'm not sure and this isn't in the errata for this book.

Body:
I think you're reading the statement wrong, if you placed parentheses, so that it's obvious what's going on, it would look like

(validDecimal) && (decimalCount <= 1)

not

(validDecimal && decimalCount) <= 1

In English: check that validDecimal is true and decimalCount is at most 1. The comparison against true is implicit, because it's not necessary.

In C#, variable of type bool can have one of two values, true or false, but they don't act as numbers, so you can't say they are 1 and 0 (although they are usually implemented that way).

Also, in most languages, if you mean “a and b are both at most x”, you can't write it as a && b <= x. That's just not how (most) computer languages work.


问:
Data not loading to the UI with redux-saga
With my react-native application when I call the API endpoint it is not loading the payload to the UI but I can see that the data is being loaded through the console. Can anybody please help me to sort the issue? This is killing me. I am listing my sagas and reducers here.

app.js

```<code>/**
 * @format
 * @flow
 */

import React, { Component } from 'react'
import { Provider } from 'react-redux'

import { store } from './store/store'

import Home from './screens/home/home'

class App extends Component {

  render() {
    return (
      <Provider store={store}>
        <Home />
      </Provider>
    )
  }
}

export default App
</code>```

store.js

```<code>import { createStore, applyMiddleware } from 'redux'
import { createLogger } from 'redux-logger'
import createSagaMiddleware from 'redux-saga'

import rootReducer from '../reducers'

import rootSaga from '../sagas'

const sagaMiddleware = createSagaMiddleware()

const store = createStore(
  rootReducer,
  applyMiddleware(
    sagaMiddleware,
    createLogger(),
  ),
)

sagaMiddleware.run(rootSaga)

export {
  store,
}
</code>```

actions.js

```<code>export function getTransatcions() {
    return { type: "TRANSACTIONS_REQUESTED" }
}
</code>```

sagas.js

```<code>import { takeEvery, call, put } from "redux-saga/effects"

export default function* watcherSaga() {
  yield takeEvery("TRANSACTIONS_REQUESTED", workerSaga)
}

function* workerSaga() {
  try {
    const payload = yield call(getTransatcions)
    yield put({ type: "TRANSACTIONS_LOADED", payload })
  } catch (e) {
    yield put({ type: "TRANSACTIONS_ERRORED", payload: e })
  }
}

function getTransatcions() {
    return fetch("https://jsonplaceholder.typicode.com/posts").then(response => {
        return response.json()
    })
}
</code>```

reducers.js

```<code>const initialState = {
    isFetching: false,
    transactions: []
}

export default (state = initialState, action) => {
    switch (action.type) {
        case "TRANSACTIONS_REQUESTED":
            return {
                ...state,
                isFetching: true
            }
        case "TRANSACTIONS_LOADED":
            return {
                ...state,
                isFetching: false,
                transactions: action.payload
            }
        case "TRANSACTIONS_ERRORED":
            return {
                ...state,
                isFetching: false,
                error: action.error
            }
        default:
            return state
    }
}
</code>```

home.js (UI Screen)

```<code>import React, { Component } from 'react'
import { connect } from "react-redux"
import {
    View,
    Text,
    Button,
    StatusBar,
    ScrollView,
    SafeAreaView
} from 'react-native'

import { Header } from 'react-native/Libraries/NewAppScreen'

import { getTransatcions } from '../../actions'

import styles from './styles/home'

class Home extends Component {

    state = {
        transactions: []
    }

    componentWillMount() {
        this.props.getTransatcions()
    }

    render() {
        return (
            <>
                <StatusBar barStyle="dark-content" />
                <SafeAreaView>
                    <ScrollView
                        style={styles.scrollView}
                        contentInsetAdjustmentBehavior="automatic"
                    >
                        <Header />
                        <View style={styles.body}>
                            <Text>{this.props.transactions[0].title}</Text>
                            {this.props.transactions && this.props.transactions.map(each => {
                                <>
                                    <Text>{each.title}</Text>
                                </>
                            })}
                            <Button
                                title="Press me"
                                // onPress={actionCreators.getTransactions}
                            />
                        </View>
                    </ScrollView>
                </SafeAreaView>
            </>
        )
    }
}

function mapStateToProps(state) {
    return {
        transactions: state.transactions
    }
}

export default connect(mapStateToProps, { getTransatcions })(Home)
</code>```

Can somebody please help me to fix this issue. I had to use saga and i am bit new to redux-saga concepts. Data is being viewed in the UI If I put it like this.

```<code>this.props.transactions[0].title
</code>```

But If I use to repeat all content in the UI like this it won't show the data.

```<code>{this.props.transactions && this.props.transactions.map(each => {
<>
    <Text>{each.title}</Text>
</>
})}
</code>```

答:
You missed return inside map

```<code>{this.props.transactions && this.props.transactions.map(each => {
   return (<>
     <Text>{each.title}</Text>
   </>)
})}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
With my react-native application when I call the API endpoint it is not loading the payload to the UI but I can see that the data is being loaded through the console. Can anybody please help me to sort the issue? This is killing me. I am listing my sagas and reducers here.

app.js

/**
 * @format
 * @flow
 */

import React, { Component } from 'react'
import { Provider } from 'react-redux'

import { store } from './store/store'

import Home from './screens/home/home'

class App extends Component {

  render() {
    return (
      <Provider store={store}>
        <Home />
      </Provider>
    )
  }
}

export default App

store.js

import { createStore, applyMiddleware } from 'redux'
import { createLogger } from 'redux-logger'
import createSagaMiddleware from 'redux-saga'

import rootReducer from '../reducers'

import rootSaga from '../sagas'

const sagaMiddleware = createSagaMiddleware()

const store = createStore(
  rootReducer,
  applyMiddleware(
    sagaMiddleware,
    createLogger(),
  ),
)

sagaMiddleware.run(rootSaga)

export {
  store,
}

actions.js

export function getTransatcions() {
    return { type: "TRANSACTIONS_REQUESTED" }
}

sagas.js

import { takeEvery, call, put } from "redux-saga/effects"

export default function* watcherSaga() {
  yield takeEvery("TRANSACTIONS_REQUESTED", workerSaga)
}

function* workerSaga() {
  try {
    const payload = yield call(getTransatcions)
    yield put({ type: "TRANSACTIONS_LOADED", payload })
  } catch (e) {
    yield put({ type: "TRANSACTIONS_ERRORED", payload: e })
  }
}

function getTransatcions() {
    return fetch("https://jsonplaceholder.typicode.com/posts").then(response => {
        return response.json()
    })
}

reducers.js

const initialState = {
    isFetching: false,
    transactions: []
}

export default (state = initialState, action) => {
    switch (action.type) {
        case "TRANSACTIONS_REQUESTED":
            return {
                ...state,
                isFetching: true
            }
        case "TRANSACTIONS_LOADED":
            return {
                ...state,
                isFetching: false,
                transactions: action.payload
            }
        case "TRANSACTIONS_ERRORED":
            return {
                ...state,
                isFetching: false,
                error: action.error
            }
        default:
            return state
    }
}

home.js (UI Screen)

import React, { Component } from 'react'
import { connect } from "react-redux"
import {
    View,
    Text,
    Button,
    StatusBar,
    ScrollView,
    SafeAreaView
} from 'react-native'

import { Header } from 'react-native/Libraries/NewAppScreen'

import { getTransatcions } from '../../actions'

import styles from './styles/home'

class Home extends Component {

    state = {
        transactions: []
    }

    componentWillMount() {
        this.props.getTransatcions()
    }

    render() {
        return (
            <>
                <StatusBar barStyle="dark-content" />
                <SafeAreaView>
                    <ScrollView
                        style={styles.scrollView}
                        contentInsetAdjustmentBehavior="automatic"
                    >

                        <View style={styles.body}>
                            <Text>{this.props.transactions[0].title}</Text>
                            {this.props.transactions && this.props.transactions.map(each => {
                                <>
                                    <Text>{each.title}</Text>
                                </>
                            })}
                            <Button
                                title="Press me"
                                // onPress={actionCreators.getTransactions}
                            />
                        </View>
                    </ScrollView>
                </SafeAreaView>
            </>
        )
    }
}

function mapStateToProps(state) {
    return {
        transactions: state.transactions
    }
}

export default connect(mapStateToProps, { getTransatcions })(Home)

Can somebody please help me to fix this issue. I had to use saga and i am bit new to redux-saga concepts. Data is being viewed in the UI If I put it like this.

this.props.transactions[0].title

But If I use to repeat all content in the UI like this it won't show the data.

{this.props.transactions && this.props.transactions.map(each => {
<>
    <Text>{each.title}</Text>
</>
})}

Body:
You missed return inside map

{this.props.transactions && this.props.transactions.map(each => {
   return (<>
     <Text>{each.title}</Text>
   </>)
})}


问:
Filter specific value from Tshark JSON output
I would like to extract the "tls.handshake.certificate_raw" values, but without success so far. The big JSON is killing me.

Here's my JSON file: Download

Thanks in advance!

答:
My final command:

```<code>jq --stream -c '(.[0]|index("tls.handshake.certificate_raw")) as $ix
            | select($ix) | .[0] |= .[$ix+1:]' Tshark.json |
jq -r -nc 'fromstream(inputs)[0]' | sort -u > Certificates.txt
</code>```

I grab only the first value from the array and remove the double quotes. After a sort uniq I write the SSL certificates line by line into a file.

Thanks a lot for your great assistance!

Body:
My final command:

jq --stream -c '(.[0]|index("tls.handshake.certificate_raw")) as $ix
            | select($ix) | .[0] |= .[$ix+1:]' Tshark.json |
jq -r -nc 'fromstream(inputs)[0]' | sort -u > Certificates.txt

I grab only the first value from the array and remove the double quotes. After a sort uniq I write the SSL certificates line by line into a file.

Thanks a lot for your great assistance!


问:
Align image position of button by CSS
I have a Button with a background-image and a text that is more than the width of the image.
How to place the image in the middle of the text

<!DOCTYPE html>

<button class="button">Button text test</button>

```

Button image

答:
Hope this help you.

.button {
  background: url('https://i.stack.imgur.com/GxHaN.jpg') no-repeat;
  background-size: 100% 100%;
  border: none;
  color: black;
  font-size: 16px;
  width: 60px;
  height: 60px;
  white-space: nowrap;
  background-position: center center;
  display: flex;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button class="button">Button text test</button></code>```

Title: Align image position of button by CSS

Body:
I have a Button with a background-image and a text that is more than the width of the image.
How to place the image in the middle of the text

<!DOCTYPE html>

<button class="button">Button text test</button>

Button image

Body:
Hope this help you.

.button {
  background: url('https://i.stack.imgur.com/GxHaN.jpg') no-repeat;
  background-size: 100% 100%;
  border: none;
  color: black;
  font-size: 16px;
  width: 60px;
  height: 60px;
  white-space: nowrap;
  background-position: center center;
  display: flex;
}

<button class="button">Button text test</button>


问:
How to keep XML in URLs from being interpreted?
I'm trying to get PHP to echo this:

```<code>http://production.shippingapis.com/ShippingAPI.dll?API=TrackV2&XML=<TrackRequest USERID=\"123456\"><TrackID ID=".$trackno."></TrackID></TrackRequest>";
</code>```

However, when I open this page in my browser (FF4), only this shows up:

```<code>http://production.shippingapis.com/ShippingAPI.dll?API=TrackV2&XML=
</code>```

The browser thinks that  onwards is part of a XML document so it does not render it, as shown here:

(parts blanked out for obvious reasons :D)

How do I fix this issue?

Thanks!

答:
It will parse it as HTML. It has nothing to do with XML. Use the Content-Type text/plain header to tell the browser it is plain text.

If this url is not the only output, but it is part of a HTML page, use htmlspecialchars  or htmlentities.

Body:
I'm trying to get PHP to echo this:

http://production.shippingapis.com/ShippingAPI.dll?API=TrackV2&XML=<TrackRequest USERID=\"123456\"><TrackID ID=".$trackno."></TrackID></TrackRequest>";

However, when I open this page in my browser (FF4), only this shows up:

http://production.shippingapis.com/ShippingAPI.dll?API=TrackV2&XML=

The browser thinks that  onwards is part of a XML document so it does not render it, as shown here:

(parts blanked out for obvious reasons :D)

How do I fix this issue?

Thanks!


问:
Dependency Injecting IConfiguration within unit test class
I am using ASP.NET Core 3, I have a helpers class that contains 2 dependencies, IConfiguration and ILogger, when unit testing the concrete implementation seen here:

```<code>public class Helper : IHelpers
{
    private IConfiguration configuration;
    private readonly ILogger<Helper> logger;
    public Helper(IConfiguration _config, ILogger<Helper> _logger)
    {
        configuration = _config;
        logger = _logger;
    }
    public Tuple<string, string> SpotifyClientInformation()
    {
        Tuple<string, string> tuple = null;
        try
        {
            if (configuration != null)
            {
                string clientID = configuration["SpotifySecrets:clientID"];
                //Todo move secretID to more secure location
                string secretID = configuration["SpotifySecrets:secretID"];
                tuple = new Tuple<string, string>(clientID, secretID);
            }
        }
        catch (Exception ex)
        {
            logger.LogCritical("Configuration DI not set up correctly",ex);
        }

        return tuple;
    }
}
</code>```

In my tests, I try to DI  helpers via this code:

```<code>public class HelperTests
{
    private ServiceCollection serviceCollection;
    private IHelpers helper;
    [SetUp]
    public void Setup()
    {
        serviceCollection = new ServiceCollection();
        serviceCollection.AddTransient<IHelpers, Helper>();

        ServiceProvider serviceProvider = serviceCollection.BuildServiceProvider();

        helper = serviceProvider.GetService<IHelpers>();
    }

    [Test]
    public void GetSpotifyConfiguration()
    {
        Tuple<string, string> devData = helper.SpotifyClientInformation();
        Assert.NotNull(devData.Item1);
        Assert.NotNull(devData.Item2);
    }
}
</code>```

but I get the error that reads:

```<code>System.InvalidOperationException : Unable to resolve service for type
'Microsoft.Extensions.Configuration.IConfiguration' while attempting to activate 'Spotify_Angular.Helper'.
</code>```

答:
You're getting an exception as you have not registered the configuration or logger interfaces with the DI container in your set up. You could do that, but may I suggest an alternative.

Rather than creating concrete implementations and registering them/creating a service provider, mock the dependencies. It'll make this process a lot easier and is more canonical in terms of how you should write your unit tests.

Include a reference to Moq then for the success case do something like:

```<code>[Test]
public void SpotifyClientInformation_ReturnsExpectedClientIdAndSecretIdTuple()
{
    var logger = Mock.Of<ILogger<Helper>>();

    var expectedClientId = "My client Id";
    var expectedSecretId = "My secret Id";
    var configurationMock = new Mock<IConfiguration>();
    configurationMock.Setup(m => m["SpotifySecrets:clientID"]).Returns(expectedClientId);
    configurationMock.Setup(m => m["SpotifySecrets:secretID"]).Returns(expectedSecretId);
    var configuration = configurationMock.Object;

    var helper = new Helper(configuration, logger);

    var (actualClientId, actualSecretId) = helper.SpotifyClientInformation();

    Assert.Multiple(() =>
    {
        Assert.That(actualClientId, Is.EqualTo(expectedClientId));
        Assert.That(actualSecretId, Is.EqualTo(expectedSecretId));
    });
}
</code>```

Arrange the dependencies and set up the test state; Act by invoking SpotifyClientInformation; and finally Assert that the resulting tuple has the expected values.

Following on from there you can easily increase your coverage for the null configuration case

```<code>[Test]
public void SpotifyClientInformation_WithNullConfiguration_ReturnsNull()
{
    var logger = Mock.Of<ILogger<Helper>>();
    var helper = new Helper(null, logger);

    var actualResult = helper.SpotifyClientInformation();

    Assert.That(actualResult, Is.Null);
}
</code>```

It is possible to assert the log message with another test but I don't believe it's realistic. All you're doing is reading values from the configuration instance and creating the tuple and I don't think either will produce an exception. Attempting to read a configuration key that doesn't exist returns null.

A better way if you wanted to capture that scenario with a log message would be to do it in the constructor

```<code>public class Helper : IHelpers
{
    private IConfiguration configuration;
    private readonly ILogger<Helper> logger;
    public Helper(IConfiguration _config, ILogger<Helper> _logger)
    {
        configuration = _config;
        logger = _logger;

        if (configuration == null)
        {
            logger.LogCritical("Configuration DI not set up correctly");
        }
    }
    public Tuple<string, string> SpotifyClientInformation()
    {
        if (configuration == null)
        {
            return null;
        }

        string clientID = configuration["SpotifySecrets:clientID"];
        //Todo move secretID to more secure location
        string secretID = configuration["SpotifySecrets:secretID"];
        return new Tuple<string, string>(clientID, secretID);
    }
}
</code>```

Then if you want to assert the log message

```<code>[Test]
public void Initialize_NullConfiguration_GeneratesCriticalLog()
{
    var expectedLogMessage = "Configuration DI not set up correctly";

    var logger = Mock.Of<ILogger<Helper>>();

    var helper = new Helper(null, logger);

    Mock.Get(logger).Verify(m => m.Log(
            LogLevel.Critical,
            It.IsAny<EventId>(),
            It.Is<It.IsAnyType>((o, t) => HasLogMessage(o, expectedLogMessage)),
            It.IsAny<KeyNotFoundException>(),
            (Func<It.IsAnyType, Exception, string>) It.IsAny<object>()),
        Times.Once
    );
}

private static bool HasLogMessage(object state, string expectedMessage)
{
    var loggedValues = (IReadOnlyList<KeyValuePair<string, object>>) state;
    var unformattedMessage = loggedValues[^1].Value.ToString();
    return unformattedMessage.Equals(expectedMessage, StringComparison.CurrentCultureIgnoreCase);
}
</code>```

Personally I don't worry about null guarding DI staples like loggers and configuration. If I had to, I'd raise an ArgumentNullException to really ram it home that this class can't/shouldn't operate without it and I should fix the DI configuration before deploying. Doing that would mean you could do away with the null check in the SpotifyClientInformation method plus any null checking for blocks that consume SpotifyClientInformation.

Body:
I am using ASP.NET Core 3, I have a helpers class that contains 2 dependencies, IConfiguration and ILogger, when unit testing the concrete implementation seen here:

public class Helper : IHelpers
{
    private IConfiguration configuration;
    private readonly ILogger<Helper> logger;
    public Helper(IConfiguration _config, ILogger<Helper> _logger)
    {
        configuration = _config;
        logger = _logger;
    }
    public Tuple<string, string> SpotifyClientInformation()
    {
        Tuple<string, string> tuple = null;
        try
        {
            if (configuration != null)
            {
                string clientID = configuration["SpotifySecrets:clientID"];
                //Todo move secretID to more secure location
                string secretID = configuration["SpotifySecrets:secretID"];
                tuple = new Tuple<string, string>(clientID, secretID);
            }
        }
        catch (Exception ex)
        {
            logger.LogCritical("Configuration DI not set up correctly",ex);
        }

        return tuple;
    }
}

In my tests, I try to DI  helpers via this code:

public class HelperTests
{
    private ServiceCollection serviceCollection;
    private IHelpers helper;
    [SetUp]
    public void Setup()
    {
        serviceCollection = new ServiceCollection();
        serviceCollection.AddTransient<IHelpers, Helper>();

        ServiceProvider serviceProvider = serviceCollection.BuildServiceProvider();

        helper = serviceProvider.GetService<IHelpers>();
    }

    [Test]
    public void GetSpotifyConfiguration()
    {
        Tuple<string, string> devData = helper.SpotifyClientInformation();
        Assert.NotNull(devData.Item1);
        Assert.NotNull(devData.Item2);
    }
}

but I get the error that reads:

System.InvalidOperationException : Unable to resolve service for type
'Microsoft.Extensions.Configuration.IConfiguration' while attempting to activate 'Spotify_Angular.Helper'.

Body:
You're getting an exception as you have not registered the configuration or logger interfaces with the DI container in your set up. You could do that, but may I suggest an alternative.

Rather than creating concrete implementations and registering them/creating a service provider, mock the dependencies. It'll make this process a lot easier and is more canonical in terms of how you should write your unit tests.

Include a reference to Moq then for the success case do something like:

[Test]
public void SpotifyClientInformation_ReturnsExpectedClientIdAndSecretIdTuple()
{
    var logger = Mock.Of<ILogger<Helper>>();

    var expectedClientId = "My client Id";
    var expectedSecretId = "My secret Id";
    var configurationMock = new Mock<IConfiguration>();
    configurationMock.Setup(m => m["SpotifySecrets:clientID"]).Returns(expectedClientId);
    configurationMock.Setup(m => m["SpotifySecrets:secretID"]).Returns(expectedSecretId);
    var configuration = configurationMock.Object;

    var helper = new Helper(configuration, logger);

    var (actualClientId, actualSecretId) = helper.SpotifyClientInformation();

    Assert.Multiple(() =>
    {
        Assert.That(actualClientId, Is.EqualTo(expectedClientId));
        Assert.That(actualSecretId, Is.EqualTo(expectedSecretId));
    });
}

Arrange the dependencies and set up the test state; Act by invoking SpotifyClientInformation; and finally Assert that the resulting tuple has the expected values.

Following on from there you can easily increase your coverage for the null configuration case

[Test]
public void SpotifyClientInformation_WithNullConfiguration_ReturnsNull()
{
    var logger = Mock.Of<ILogger<Helper>>();
    var helper = new Helper(null, logger);

    var actualResult = helper.SpotifyClientInformation();

    Assert.That(actualResult, Is.Null);
}

It is possible to assert the log message with another test but I don't believe it's realistic. All you're doing is reading values from the configuration instance and creating the tuple and I don't think either will produce an exception. Attempting to read a configuration key that doesn't exist returns null.

A better way if you wanted to capture that scenario with a log message would be to do it in the constructor

public class Helper : IHelpers
{
    private IConfiguration configuration;
    private readonly ILogger<Helper> logger;
    public Helper(IConfiguration _config, ILogger<Helper> _logger)
    {
        configuration = _config;
        logger = _logger;

        if (configuration == null)
        {
            logger.LogCritical("Configuration DI not set up correctly");
        }
    }
    public Tuple<string, string> SpotifyClientInformation()
    {
        if (configuration == null)
        {
            return null;
        }

        string clientID = configuration["SpotifySecrets:clientID"];
        //Todo move secretID to more secure location
        string secretID = configuration["SpotifySecrets:secretID"];
        return new Tuple<string, string>(clientID, secretID);
    }
}

Then if you want to assert the log message

[Test]
public void Initialize_NullConfiguration_GeneratesCriticalLog()
{
    var expectedLogMessage = "Configuration DI not set up correctly";

    var logger = Mock.Of<ILogger<Helper>>();

    var helper = new Helper(null, logger);

    Mock.Get(logger).Verify(m => m.Log(
            LogLevel.Critical,
            It.IsAny<EventId>(),
            It.Is<It.IsAnyType>((o, t) => HasLogMessage(o, expectedLogMessage)),
            It.IsAny<KeyNotFoundException>(),
            (Func<It.IsAnyType, Exception, string>) It.IsAny<object>()),
        Times.Once
    );
}

private static bool HasLogMessage(object state, string expectedMessage)
{
    var loggedValues = (IReadOnlyList<KeyValuePair<string, object>>) state;
    var unformattedMessage = loggedValues[^1].Value.ToString();
    return unformattedMessage.Equals(expectedMessage, StringComparison.CurrentCultureIgnoreCase);
}

Personally I don't worry about null guarding DI staples like loggers and configuration. If I had to, I'd raise an ArgumentNullException to really ram it home that this class can't/shouldn't operate without it and I should fix the DI configuration before deploying. Doing that would mean you could do away with the null check in the SpotifyClientInformation method plus any null checking for blocks that consume SpotifyClientInformation.


问:
HTML : How to sort files by user seleted
I want to sort files as the user selected.

When I seelect a image named 3,2,1 and click the button "Click me", it
  will show 1,2,3 in console.log()

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>

    <input id="tmpFiles" name="img[]" type="file" accept="image/*" multiple>
    <button onclick="myFunction()">Click me</button>

```

答:
try this. this should be work.

$(document).ready(function(){
      $('#tmpFiles').on("change", function(){
            var selectedFiless = this.files;
            for (var i = 0; i < selectedFiless.length; ++i) {
                var name = selectedFiless.item(i).name;
                alert(name);
            }
        });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.2/jquery.min.js"></script>
<html lang="en">
<head>

</head>
<body>

    <input id="tmpFiles" name="img[]" type="file" accept="image/*" multiple>

</body>
</html></code>```

Body:
try this. this should be work.

$(document).ready(function(){
      $('#tmpFiles').on("change", function(){
            var selectedFiless = this.files;
            for (var i = 0; i < selectedFiless.length; ++i) {
                var name = selectedFiless.item(i).name;
                alert(name);
            }
        });
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.2/jquery.min.js"></script>
<html lang="en">
<head>

</head>
<body>

    <input id="tmpFiles" name="img[]" type="file" accept="image/*" multiple>

</body>
</html>


问:
Text recognizer changes the behavior of saving data edit text
I am using 2 EditText, one for title and other for body text. i am getting the body text from my image through text recognizer and title from just simply typing the title. But when i call the function for text recognizer and then saving the data, my title text shows a strange behavior and give me the alert dialogue of missing title even i type the title. I don't know why with text recognizer function the Title edit text is showing me alert dialog of missing title. here is my code

```<code>private boolean hasTitle() {
    return !titleText.getText().toString().trim().isEmpty();
}

if (hasBody() || hasImage() && !hasTitle()) { // if user missing title
                    AlertDialogNoTitle(); // it should not enter here while i type the title but with recognizer it show alertdialogue. By Log, i am getting the correct text for the title which is not zero
                   // setResult(RESULT_CANCELED, data);
                   // finish();
                } else if (hasTitle()) { // if they have title
                    data.putExtra("USER TITLE", titleText.getText().toString());
                    data.putExtra("USER TEXT", bodyText.getText().toString());
                    if (cardsNamesSingleString != null) {
                        data.putExtra("USER CARDS", cardsNamesSingleString);
                        Util.saveToInternalStorageCard(ArrayImageName, bitmaps);
                    }
                    setResult(RESULT_OK, data);
                    finish();
                } else { // no entry
                    setResult(RESULT_CANCELED, data);
                    finish();
                }
            }
</code>```

my text recognizer for the body text only

```<code> private void detect() {
    //perform text detection here

    //TODO 1. define TextRecognizer
    TextRecognizer recognizer = new TextRecognizer.Builder(NoteActivity.this).build();

    //TODO 2. Get bitmap from imageview
    Bitmap bitmap = ((BitmapDrawable)frontCard.getDrawable()).getBitmap();
    //TODO 3. get frame from bitmap
    Frame frame = new Frame.Builder().setBitmap(bitmap).build();
    //TODO 4. get data from frame
    SparseArray<TextBlock> sparseArray =  recognizer.detect(frame);

    //TODO 5. set data on textview
    StringBuilder stringBuilder = new StringBuilder();

    for(int i=0;i < sparseArray.size(); i++){
        TextBlock tx = sparseArray.get(i);
        stringBuilder.append(tx.getValue());
        stringBuilder.append("\n");
    }
        bodyText.setText(stringBuilder.toString());
    }
</code>```

答:
try this

if ((hasImage() && !hasTitle()) || (hasBody() && !hasTitle()))

Body:
I am using 2 EditText, one for title and other for body text. i am getting the body text from my image through text recognizer and title from just simply typing the title. But when i call the function for text recognizer and then saving the data, my title text shows a strange behavior and give me the alert dialogue of missing title even i type the title. I don't know why with text recognizer function the Title edit text is showing me alert dialog of missing title. here is my code

private boolean hasTitle() {
    return !titleText.getText().toString().trim().isEmpty();
}

if (hasBody() || hasImage() && !hasTitle()) { // if user missing title
                    AlertDialogNoTitle(); // it should not enter here while i type the title but with recognizer it show alertdialogue. By Log, i am getting the correct text for the title which is not zero
                   // setResult(RESULT_CANCELED, data);
                   // finish();
                } else if (hasTitle()) { // if they have title
                    data.putExtra("USER TITLE", titleText.getText().toString());
                    data.putExtra("USER TEXT", bodyText.getText().toString());
                    if (cardsNamesSingleString != null) {
                        data.putExtra("USER CARDS", cardsNamesSingleString);
                        Util.saveToInternalStorageCard(ArrayImageName, bitmaps);
                    }
                    setResult(RESULT_OK, data);
                    finish();
                } else { // no entry
                    setResult(RESULT_CANCELED, data);
                    finish();
                }
            }

my text recognizer for the body text only

 private void detect() {
    //perform text detection here

    //TODO 1. define TextRecognizer
    TextRecognizer recognizer = new TextRecognizer.Builder(NoteActivity.this).build();

    //TODO 2. Get bitmap from imageview
    Bitmap bitmap = ((BitmapDrawable)frontCard.getDrawable()).getBitmap();
    //TODO 3. get frame from bitmap
    Frame frame = new Frame.Builder().setBitmap(bitmap).build();
    //TODO 4. get data from frame
    SparseArray<TextBlock> sparseArray =  recognizer.detect(frame);

    //TODO 5. set data on textview
    StringBuilder stringBuilder = new StringBuilder();

    for(int i=0;i < sparseArray.size(); i++){
        TextBlock tx = sparseArray.get(i);
        stringBuilder.append(tx.getValue());
        stringBuilder.append("\n");
    }
        bodyText.setText(stringBuilder.toString());
    }


问:
mutate_if - warning message
Hello everybody,

```<code>library(dplyr)
library(tibble)
mtcars %>%
  rownames_to_column("modelle") %>%
  mutate_if(~is.numeric(.x) & mean(.x) > 50, ~(.x / 1000))

Warning message:
In mean.default(.x) : argument is not numeric or logical: returning NA
</code>```

This error seems to be because of the character vector. It works, but it´s still very ugly. Did I do anything wrong and what can be done better in that case?

Thank you!

答:
R does not short-circuit vectorized &, so this is running both is.numeric and mean on all columns. Since your first column (modelle) is obviously character, it is failing.

You actually don't need it to be vectorized, however. If you change from the vectorized & to the binary &&, R short-circuits it and you get the behavior you want.

mtcars %>%
  rownames_to_column("modelle") %>%
  mutate_if(~is.numeric(.x) && mean(.x) > 50, ~(.x / 1000)) %>%
  head()
#             modelle  mpg cyl  disp    hp drat    wt  qsec vs am gear carb
# 1         Mazda RX4 21.0   6 0.160 0.110 3.90 2.620 16.46  0  1    4    4
# 2     Mazda RX4 Wag 21.0   6 0.160 0.110 3.90 2.875 17.02  0  1    4    4
# 3        Datsun 710 22.8   4 0.108 0.093 3.85 2.320 18.61  1  1    4    1
# 4    Hornet 4 Drive 21.4   6 0.258 0.110 3.08 3.215 19.44  1  0    3    1
# 5 Hornet Sportabout 18.7   8 0.360 0.175 3.15 3.440 17.02  0  0    3    2
# 6           Valiant 18.1   6 0.225 0.105 2.76 3.460 20.22  1  0    3    1
```

<p>Further demonstration that <code>&</code> is not short-circuiting.</p>

<pre class="lang-r prettyprint-override"><code>mymean <- function(x, ...) {
  if (is.character(x)) {
    message("character?")
    return(Inf) # this is certainly not the right thing to do in general ...
  } else mean(x, ...)
}
mtcars %>%
  rownames_to_column("modelle") %>%
  mutate_if(~is.numeric(.x) & mymean(.x) > 50, ~(.x / 1000)) %>%
  head()
# character?
#             modelle  mpg cyl  disp    hp drat    wt  qsec vs am gear carb
# 1         Mazda RX4 21.0   6 0.160 0.110 3.90 2.620 16.46  0  1    4    4
# 2     Mazda RX4 Wag 21.0   6 0.160 0.110 3.90 2.875 17.02  0  1    4    4
# 3        Datsun 710 22.8   4 0.108 0.093 3.85 2.320 18.61  1  1    4    1
# 4    Hornet 4 Drive 21.4   6 0.258 0.110 3.08 3.215 19.44  1  0    3    1
# 5 Hornet Sportabout 18.7   8 0.360 0.175 3.15 3.440 17.02  0  0    3    2
# 6           Valiant 18.1   6 0.225 0.105 2.76 3.460 20.22  1  0    3    1
</code>```

If short-circuiting were taking place, then mymean would never get to the message. (I don't think this mymean is a viable replacement here, for a couple of reasons: (1) the use of Inf was solely to ensure the condition outside of the call to mean worked, but if an error/warning occurs and a numeric is expected, then one should typically return NA or NaN, not a number ... even if you might not consider Inf a real usable number. (2) It is addressing a symptom, not the problem. The problem is the absence of short-circuiting in vectorized logical expressions.)

Title: mutate_if - warning message

Body:
Hello everybody,

library(dplyr)
library(tibble)
mtcars %>%
  rownames_to_column("modelle") %>%
  mutate_if(~is.numeric(.x) & mean(.x) > 50, ~(.x / 1000))

Warning message:
In mean.default(.x) : argument is not numeric or logical: returning NA

This error seems to be because of the character vector. It works, but it´s still very ugly. Did I do anything wrong and what can be done better in that case?

Thank you!

Body:
R does not short-circuit vectorized &, so this is running both is.numeric and mean on all columns. Since your first column (modelle) is obviously character, it is failing.

You actually don't need it to be vectorized, however. If you change from the vectorized & to the binary &&, R short-circuits it and you get the behavior you want.

mtcars %>%
  rownames_to_column("modelle") %>%
  mutate_if(~is.numeric(.x) && mean(.x) > 50, ~(.x / 1000)) %>%
  head()
#             modelle  mpg cyl  disp    hp drat    wt  qsec vs am gear carb
# 1         Mazda RX4 21.0   6 0.160 0.110 3.90 2.620 16.46  0  1    4    4
# 2     Mazda RX4 Wag 21.0   6 0.160 0.110 3.90 2.875 17.02  0  1    4    4
# 3        Datsun 710 22.8   4 0.108 0.093 3.85 2.320 18.61  1  1    4    1
# 4    Hornet 4 Drive 21.4   6 0.258 0.110 3.08 3.215 19.44  1  0    3    1
# 5 Hornet Sportabout 18.7   8 0.360 0.175 3.15 3.440 17.02  0  0    3    2
# 6           Valiant 18.1   6 0.225 0.105 2.76 3.460 20.22  1  0    3    1

Further demonstration that & is not short-circuiting.

mymean <- function(x, ...) {
  if (is.character(x)) {
    message("character?")
    return(Inf) # this is certainly not the right thing to do in general ...
  } else mean(x, ...)
}
mtcars %>%
  rownames_to_column("modelle") %>%
  mutate_if(~is.numeric(.x) & mymean(.x) > 50, ~(.x / 1000)) %>%
  head()
# character?
#             modelle  mpg cyl  disp    hp drat    wt  qsec vs am gear carb
# 1         Mazda RX4 21.0   6 0.160 0.110 3.90 2.620 16.46  0  1    4    4
# 2     Mazda RX4 Wag 21.0   6 0.160 0.110 3.90 2.875 17.02  0  1    4    4
# 3        Datsun 710 22.8   4 0.108 0.093 3.85 2.320 18.61  1  1    4    1
# 4    Hornet 4 Drive 21.4   6 0.258 0.110 3.08 3.215 19.44  1  0    3    1
# 5 Hornet Sportabout 18.7   8 0.360 0.175 3.15 3.440 17.02  0  0    3    2
# 6           Valiant 18.1   6 0.225 0.105 2.76 3.460 20.22  1  0    3    1

If short-circuiting were taking place, then mymean would never get to the message. (I don't think this mymean is a viable replacement here, for a couple of reasons: (1) the use of Inf was solely to ensure the condition outside of the call to mean worked, but if an error/warning occurs and a numeric is expected, then one should typically return NA or NaN, not a number ... even if you might not consider Inf a real usable number. (2) It is addressing a symptom, not the problem. The problem is the absence of short-circuiting in vectorized logical expressions.)


问:
How to tell jaxb(moxy) to serialise a @Transit field?
I have a field @Transient parameter which I want my ORM to ignore, however I do want moxy to serialise it. I tried using @XmlElement but still does not work (parameter is missing from the json).

```<code>@Transient
@XmlElement
private boolean isReleasedFromCustoms;
</code>```

and

```<code>public boolean isReleasedFromCustoms() {

    boolean isReleased = true;

    for (int i = 0; isReleased && i < this.products.size(); i++) {
        isReleased = (this.products.get(i).getCustomsStatus() % 10) == 0;
    }

    return isReleased;
}
</code>```

How can I tell MOXy to ignore the @Transient annotation and to serialise the parameter?

答:
I got with the solution and forgot to put it here...

basically I had the getter for that field but the setter was missing hence the field was ignored by the json serialiser (moxy in my case).

Body:
I have a field @Transient parameter which I want my ORM to ignore, however I do want moxy to serialise it. I tried using @XmlElement but still does not work (parameter is missing from the json).

@Transient
@XmlElement
private boolean isReleasedFromCustoms;

and

public boolean isReleasedFromCustoms() {

    boolean isReleased = true;

    for (int i = 0; isReleased && i < this.products.size(); i++) {
        isReleased = (this.products.get(i).getCustomsStatus() % 10) == 0;
    }

    return isReleased;
}

How can I tell MOXy to ignore the @Transient annotation and to serialise the parameter?


问:
ASP.NET Core 3.0 Web API routing not working
I am trying to access a jwt controller in my dotnet core 3.1 solution.

Here is my jwt controller:

```<code>[Authorize]
[ApiController]
[Route("api/[controller]")]
public class JwtController : ControllerBase
{
        #region Variables
        private readonly IUserAuthorisationServices _tokenService;
        private readonly IOptions<JwtTokenOptions> jwtOptions;
        private readonly ILogger logger;
        private readonly JsonSerializerSettings _serializerSettings;
        #endregion

        public JwtController(IUserAuthorisationServices tokenService,
                             IOptions<JwtTokenOptions> jwtOptions,
                             ILoggerFactory loggerFactory)
        {
            if (loggerFactory is null) throw new ArgumentNullException(nameof(loggerFactory));

            _tokenService = tokenService ?? throw new ArgumentNullException(nameof(tokenService));

            jwtOptions = jwtOptions ?? throw new ArgumentNullException(nameof(jwtOptions));
            logger = loggerFactory.CreateLogger<JwtController>();
            _serializerSettings = new JsonSerializerSettings {
                Formatting = Formatting.Indented
            };
            //loggingRepository = _errorRepository;
            //ThrowIfInvalidOptions(this.jwtOptions);
        }

  [AllowAnonymous]
  [Route("authenticate")]
  [HttpPost]
  public async Task<IActionResult> Authenticate([FromBody] LoginViewModel model)
  {
            var userContext = _tokenService.Authenticate(model.Email, model.Password);

            if (userContext.Principal == null) {
                logger.LogInformation($"Invalid username ({model.Email}) or password ({model.Password})");
                return BadRequest(new { message = "Username or password is incorrect" });
            }

            return Ok(await _tokenService.CreateTokenAsync(userContext).ConfigureAwait(false));
  }

   [Route("JWTStatus")]
   [HttpGet]
   public static IActionResult GetJwtStatus()
   {
            // It made it here so it was authenticated.
            return new OkResult();
   }
}
</code>```

I have stepped my way through the process and it gets to this middleware and then cannot find the controller returning immediately and at the same time providing the browser with a 404.

This is what I am using to access this controller action:

```<code>login(email: string, password: string) {
    this.userLogin.Email = email;
    this.userLogin.Password = password;

    // Do the fetch!
    const t = fetch("/api/authenticate",
            {
                method: "POST",
                body: JSON.stringify(this.userLogin),
                headers: new Headers({ "content-type": "application/json" })
            })
        .then(response => {
</code>```

I note the fetch is using "api/authenticate" and when I look at the HttpRequest its got the same url yet it wont find it.

Here is the middleware that it gets to before just returning.

```<code>namespace JobsLedger.AUTHORISATION.API.SessionMiddleware
{
    public class ConfigureSessionMiddleware
    {
        private readonly RequestDelegate _next;

        public ConfigureSessionMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task InvokeAsync(HttpContext httpContext, IUserSession userSession, ISessionServices sessionServices)
        {
            if (httpContext == null)
            {
                throw new ArgumentNullException(nameof(httpContext));
            }

            if (userSession == null)
            {
                throw new ArgumentNullException(nameof(userSession));
            }

            if (sessionServices == null)
            {
                throw new ArgumentNullException(nameof(sessionServices));
            }

            if (httpContext.User.Identities.Any(id => id.IsAuthenticated))
            {
                if (httpContext.Session.GetString("connectionString") == null) // Session needs to be set..
                {
                    userSession.UserId = httpContext.User.Claims.FirstOrDefault(x => x.Type == "userId")?.Value;
                    userSession.ConnectionString = sessionServices.ConnectionStringFromUserId(userSession.UserId);
                    httpContext.Session.SetString("userId", userSession.UserId);
                    httpContext.Session.SetString("connectionString", userSession.ConnectionString);
                }
                else  //  Session set so all we need to is to build userSession for data access..
                {
                    userSession.UserId = httpContext.Session.GetString("userId");
                    userSession.ConnectionString = httpContext.Session.GetString("connectionString");
                }
            }

            // Call the next delegate/middleware in the pipeline
            await _next.Invoke(httpContext).ConfigureAwait(false);
        }
    }
}
</code>```

Its suppose to jump straight past this as there are no user identities as this hasnt been set yet. So really it goes straight to:

```<code>await _next.Invoke(httpContext).ConfigureAwait(false);
</code>```

Then onto the controller action.. but it just goes straight out with a 404.

In the output window I am getting:

```<code>Microsoft.AspNetCore.Hosting.Diagnostics: Information: Request starting HTTP/2.0 POST https://localhost:44301/api/authenticate text/plain;charset=UTF-8 76
Microsoft.AspNetCore.Cors.Infrastructure.CorsService: Information: CORS policy execution successful.
Microsoft.AspNetCore.Hosting.Diagnostics: Information: Request finished in 17.1363ms 404
</code>```

You can see the 404.

How is it cant find the action?

Is it possibly due to it being https and http 2.0?

For completeness here is the httpContext at the point of that middleware:

UPDATE...

I do not use MVC in the startup either just endpoints...

Maybe its the pipeline in Startup.cs.. here is my startup.cs

```<code>[assembly: NeutralResourcesLanguage("en")]

namespace JobsLedger.API {
    public class Startup {
        //private const string SecretKey = "needtogetthisfromenvironment";

        //private readonly SymmetricSecurityKey
        //  _signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(SecretKey));
        private readonly IWebHostEnvironment _env;
        private readonly IConfiguration _configuration;  // { get; }

        public Startup(IWebHostEnvironment env, IConfiguration configuration) {
            _env = env;
            _configuration = configuration;
        }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services) {
            // Add framework services.
            services.AddCors();
            services.AddControllers();
            services.AddOptions();

            services.AddDbContext<CATALOGContext>(options => options.UseSqlServer(_configuration.GetConnectionString("CatalogConnection"), b => b.MigrationsAssembly("JobsLedger.CATALOG")));
            services.AddDbContext<DATAContext>(options => options.UseSqlServer(_configuration.GetConnectionString("TenantDbConnection"), a => a.MigrationsAssembly("JobsLedger.DATA")));

            // Make authentication compulsory across the board (i.e. shut
            // down EVERYTHING unless explicitly opened up).
            // Use policy auth.
            services.AddAuthorization(options => {
                options.AddPolicy("TenantAdmin", policy => policy.RequireClaim(ClaimTypes.Role, "TenantAdmin"));
                options.AddPolicy("Admin", policy => policy.RequireClaim(ClaimTypes.Role, "Admin"));
                options.AddPolicy("Employee", policy => policy.RequireClaim(ClaimTypes.Role, "Employee"));
            });

            //services.ConfigureApplicationInjection();

            // Get jwt options from app settings
            var tokenOptions = _configuration.GetSection("Authentication").Get<JwtTokenOptions>();

            services.AddAuthentication(x => {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options => {
                options.TokenValidationParameters = new TokenValidationParameters {
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidateLifetime = true,
                    ValidateIssuerSigningKey = true,
                    RequireExpirationTime = true,
                    ValidIssuer = tokenOptions.Issuer,
                    ValidAudience = tokenOptions.Audience,
                    IssuerSigningKey = new SymmetricSecurityKey(
                        Encoding.UTF8.GetBytes(tokenOptions.SigningKey)),
                    ClockSkew = TimeSpan.Zero
                };
            });

            services
                .AddDistributedMemoryCache()
                .AddSession()

                // Repositories - DATA
                .AddScoped<IClientDATARepository, ClientDATARepository>()
                .AddScoped<ILoggingDATARepository, LoggingDATARepository>()
                .AddScoped<IJobDATARepository, JobDATARepository>()
                .AddScoped<IBrandDATARepository, BrandDATARepository>()
                .AddScoped<ITypeDATARepository, TypeDATARepository>()
                .AddScoped<IStateDATARepository, StateDATARepository>()
                .AddScoped<IStatusDATARepository, StatusDATARepository>()
                .AddScoped<ISuburbDATARepository, SuburbDATARepository>()
                .AddScoped<ICounterDATARepository, CounterDATARepository>()

                // Repositories - CATALOG
                .AddScoped<ITenantCATALOGRepository, TenantCATALOGRepository>()
                .AddScoped<IUserCATALOGRepository, UserCATALOGRepository>()
                .AddScoped<IRoleCATALOGRepository, RoleCATALOGRepository>()
                .AddScoped<ICounterCATALOGRepository, CounterCATALOGRepository>()
                .AddScoped<ISuburbCATALOGRepository, SuburbCATALOGRepository>()
                .AddScoped<IStateCATALOGRepository, StateCATALOGRepository>()

                // Business services
                // Services - API
                .AddScoped<IClientServices, ClientServices>()
                .AddScoped<IJobServices, JobServices>()

                //Services - Catalog
                .AddScoped<ITenantServices, TenantServices>()
                .AddScoped<IUserServices, UserServices>()
                //.AddScoped<IUserValidateService, UserValidateService>()

                // Services - Shared
                .AddScoped<IAddressDropdownServices, AddressDropdownServices>()

                //Services - Auth
                .AddScoped<ICryptoService, CryptoService>()
                .AddScoped<IUserAuthorisationServices, UserAuthorisationServices>()
                .AddScoped<IUserSession, UserSession>()
                .AddScoped<ISessionServices, SessionServices>()

                // CATALOG services - Initialisations.
                .AddScoped<ICATALOGCounterInitialiser, CATALOGCounterInitialiser>()
                .AddScoped<ICATALOGStateInitialiser, CATALOGStateInitialiser>()
                .AddScoped<ICATALOGSuburbInitialiser, CATALOGSuburbInitialiser>()
                .AddScoped<IRoleInitialiser, CATALOGRoleInitialiser>()
                .AddScoped<ICATALOGTenantAndUserInitialisations, CATALOGTenantAndUserInitialiser>()

                // DATA Services - Initialisations.
                .AddScoped<IBrandInitialiser, BrandInitialiser>()
                .AddScoped<IDATACounterInitialiser, DATACounterInitialiser>()
                .AddScoped<IDATAStateInitialiser, DATAStateInitialiser>()
                .AddScoped<IDATASuburbInitialiser, DATASuburbInitialiser>()
                .AddScoped<IStatusInitialiser, StatusInitialiser>()
                .AddScoped<ITypeInitialiser, TypeInitialiser>()
                .AddScoped<IVisitTypeInitialiser, VisitTypeInitialiser>()

                // TESTDATA Services - Initialisations.
                .AddScoped<ITESTDATAInitialisations, TESTDATAInitialisations>()
                .AddScoped<ITESTDATATenantAndUserInitialisations, TESTDATATenantAndUserInitialisations>()

                .AddTransient<IDATAContextFactory, DATAContextFactory>()
                .AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); // For getting the user.
        }

        public static void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
            if (env.IsDevelopment()) {
                app.UseDeveloperExceptionPage();
            }
            else {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseExceptionHandler(options => {
                options.Run(async context => {
                    var ex = context.Features.Get<IExceptionHandlerPathFeature>();
                    if (ex?.Error != null) {
                        Debugger.Break();
                    }
                });
            });

            app.UseRouting();

            // global cors policy
            app.UseCors(x => x
                .AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader());

            app.UseAuthentication();
            app.UseHttpsRedirection();
            app.UseFileServer();
            app.UseStaticFiles();
            app.UseSession();
            app.UseAuthorization();

            app.UseConfigureSession();

            app.EnsureCATALOGMigrationAndInitialise();
            app.EnsureDATAMigrationsAndInitialise();

            app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
        }
    }
}
</code>```

答:
Okay! got it. According to your current route configuration, your routing endpoints are:

```<code>/authenticate // <-- not api/authenticate
/JWTStatus    // <-- not api/JWTStatus
</code>```

Because you are overriding the controller level route in action.

If you want api/authenticate and api/JWTStatus as your routing endpoints, then your action level route should be as follows:

```<code>[Authorize]
[ApiController]
//Remove the controller level route from here
public class JwtController : ControllerBase
{
    [AllowAnonymous]
    [Route("api/authenticate")] // <-- Here it is
    [HttpPost]
    public async Task<IActionResult> Authenticate([FromBody] LoginViewModel model)
    {
       .........
    }

    [Route("api/JWTStatus")] // <-- Here it is
    [HttpGet]
    public IActionResult GetJwtStatus()
    {
       .......
    }
}
</code>```

But my suggestion is to follow the following convention:

```<code>[Authorize]
[ApiController]
[Route("api/[controller]/[action]")] // <-- Here it is
public class JwtController : ControllerBase
{
     [AllowAnonymous]
     [HttpPost]
     public async Task<IActionResult> Authenticate([FromBody] LoginViewModel model)
     {
        .......
     }

     [HttpGet]
     public IActionResult GetJwtStatus()
     {
        ......
     }
}
</code>```

Now no action level route is required anymore and your endpoints will be:

```<code>api/Jwt/Authenticate
api/Jwt/GetJwtStatus
</code>```

Body:
I am trying to access a jwt controller in my dotnet core 3.1 solution.

Here is my jwt controller:

[Authorize]
[ApiController]
[Route("api/[controller]")]
public class JwtController : ControllerBase
{
        #region Variables
        private readonly IUserAuthorisationServices _tokenService;
        private readonly IOptions<JwtTokenOptions> jwtOptions;
        private readonly ILogger logger;
        private readonly JsonSerializerSettings _serializerSettings;
        #endregion

        public JwtController(IUserAuthorisationServices tokenService,
                             IOptions<JwtTokenOptions> jwtOptions,
                             ILoggerFactory loggerFactory)
        {
            if (loggerFactory is null) throw new ArgumentNullException(nameof(loggerFactory));

            _tokenService = tokenService ?? throw new ArgumentNullException(nameof(tokenService));

            jwtOptions = jwtOptions ?? throw new ArgumentNullException(nameof(jwtOptions));
            logger = loggerFactory.CreateLogger<JwtController>();
            _serializerSettings = new JsonSerializerSettings {
                Formatting = Formatting.Indented
            };
            //loggingRepository = _errorRepository;
            //ThrowIfInvalidOptions(this.jwtOptions);
        }

  [AllowAnonymous]
  [Route("authenticate")]
  [HttpPost]
  public async Task<IActionResult> Authenticate([FromBody] LoginViewModel model)
  {
            var userContext = _tokenService.Authenticate(model.Email, model.Password);

            if (userContext.Principal == null) {
                logger.LogInformation($"Invalid username ({model.Email}) or password ({model.Password})");
                return BadRequest(new { message = "Username or password is incorrect" });
            }

            return Ok(await _tokenService.CreateTokenAsync(userContext).ConfigureAwait(false));
  }

   [Route("JWTStatus")]
   [HttpGet]
   public static IActionResult GetJwtStatus()
   {
            // It made it here so it was authenticated.
            return new OkResult();
   }
}

I have stepped my way through the process and it gets to this middleware and then cannot find the controller returning immediately and at the same time providing the browser with a 404.

This is what I am using to access this controller action:

login(email: string, password: string) {
    this.userLogin.Email = email;
    this.userLogin.Password = password;

    // Do the fetch!
    const t = fetch("/api/authenticate",
            {
                method: "POST",
                body: JSON.stringify(this.userLogin),
                headers: new Headers({ "content-type": "application/json" })
            })
        .then(response => {

I note the fetch is using "api/authenticate" and when I look at the HttpRequest its got the same url yet it wont find it.

Here is the middleware that it gets to before just returning.

namespace JobsLedger.AUTHORISATION.API.SessionMiddleware
{
    public class ConfigureSessionMiddleware
    {
        private readonly RequestDelegate _next;

        public ConfigureSessionMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task InvokeAsync(HttpContext httpContext, IUserSession userSession, ISessionServices sessionServices)
        {
            if (httpContext == null)
            {
                throw new ArgumentNullException(nameof(httpContext));
            }

            if (userSession == null)
            {
                throw new ArgumentNullException(nameof(userSession));
            }

            if (sessionServices == null)
            {
                throw new ArgumentNullException(nameof(sessionServices));
            }

            if (httpContext.User.Identities.Any(id => id.IsAuthenticated))
            {
                if (httpContext.Session.GetString("connectionString") == null) // Session needs to be set..
                {
                    userSession.UserId = httpContext.User.Claims.FirstOrDefault(x => x.Type == "userId")?.Value;
                    userSession.ConnectionString = sessionServices.ConnectionStringFromUserId(userSession.UserId);
                    httpContext.Session.SetString("userId", userSession.UserId);
                    httpContext.Session.SetString("connectionString", userSession.ConnectionString);
                }
                else  //  Session set so all we need to is to build userSession for data access..
                {
                    userSession.UserId = httpContext.Session.GetString("userId");
                    userSession.ConnectionString = httpContext.Session.GetString("connectionString");
                }
            }

            // Call the next delegate/middleware in the pipeline
            await _next.Invoke(httpContext).ConfigureAwait(false);
        }
    }
}

Its suppose to jump straight past this as there are no user identities as this hasnt been set yet. So really it goes straight to:

await _next.Invoke(httpContext).ConfigureAwait(false);

Then onto the controller action.. but it just goes straight out with a 404.

In the output window I am getting:

Microsoft.AspNetCore.Hosting.Diagnostics: Information: Request starting HTTP/2.0 POST https://localhost:44301/api/authenticate text/plain;charset=UTF-8 76
Microsoft.AspNetCore.Cors.Infrastructure.CorsService: Information: CORS policy execution successful.
Microsoft.AspNetCore.Hosting.Diagnostics: Information: Request finished in 17.1363ms 404

You can see the 404.

How is it cant find the action?

Is it possibly due to it being https and http 2.0?

For completeness here is the httpContext at the point of that middleware:

UPDATE...

I do not use MVC in the startup either just endpoints...

Maybe its the pipeline in Startup.cs.. here is my startup.cs

[assembly: NeutralResourcesLanguage("en")]

namespace JobsLedger.API {
    public class Startup {
        //private const string SecretKey = "needtogetthisfromenvironment";

        //private readonly SymmetricSecurityKey
        //  _signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(SecretKey));
        private readonly IWebHostEnvironment _env;
        private readonly IConfiguration _configuration;  // { get; }

        public Startup(IWebHostEnvironment env, IConfiguration configuration) {
            _env = env;
            _configuration = configuration;
        }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services) {
            // Add framework services.
            services.AddCors();
            services.AddControllers();
            services.AddOptions();

            services.AddDbContext<CATALOGContext>(options => options.UseSqlServer(_configuration.GetConnectionString("CatalogConnection"), b => b.MigrationsAssembly("JobsLedger.CATALOG")));
            services.AddDbContext<DATAContext>(options => options.UseSqlServer(_configuration.GetConnectionString("TenantDbConnection"), a => a.MigrationsAssembly("JobsLedger.DATA")));

            // Make authentication compulsory across the board (i.e. shut
            // down EVERYTHING unless explicitly opened up).
            // Use policy auth.
            services.AddAuthorization(options => {
                options.AddPolicy("TenantAdmin", policy => policy.RequireClaim(ClaimTypes.Role, "TenantAdmin"));
                options.AddPolicy("Admin", policy => policy.RequireClaim(ClaimTypes.Role, "Admin"));
                options.AddPolicy("Employee", policy => policy.RequireClaim(ClaimTypes.Role, "Employee"));
            });

            //services.ConfigureApplicationInjection();

            // Get jwt options from app settings
            var tokenOptions = _configuration.GetSection("Authentication").Get<JwtTokenOptions>();

            services.AddAuthentication(x => {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options => {
                options.TokenValidationParameters = new TokenValidationParameters {
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidateLifetime = true,
                    ValidateIssuerSigningKey = true,
                    RequireExpirationTime = true,
                    ValidIssuer = tokenOptions.Issuer,
                    ValidAudience = tokenOptions.Audience,
                    IssuerSigningKey = new SymmetricSecurityKey(
                        Encoding.UTF8.GetBytes(tokenOptions.SigningKey)),
                    ClockSkew = TimeSpan.Zero
                };
            });

            services
                .AddDistributedMemoryCache()
                .AddSession()

                // Repositories - DATA
                .AddScoped<IClientDATARepository, ClientDATARepository>()
                .AddScoped<ILoggingDATARepository, LoggingDATARepository>()
                .AddScoped<IJobDATARepository, JobDATARepository>()
                .AddScoped<IBrandDATARepository, BrandDATARepository>()
                .AddScoped<ITypeDATARepository, TypeDATARepository>()
                .AddScoped<IStateDATARepository, StateDATARepository>()
                .AddScoped<IStatusDATARepository, StatusDATARepository>()
                .AddScoped<ISuburbDATARepository, SuburbDATARepository>()
                .AddScoped<ICounterDATARepository, CounterDATARepository>()

                // Repositories - CATALOG
                .AddScoped<ITenantCATALOGRepository, TenantCATALOGRepository>()
                .AddScoped<IUserCATALOGRepository, UserCATALOGRepository>()
                .AddScoped<IRoleCATALOGRepository, RoleCATALOGRepository>()
                .AddScoped<ICounterCATALOGRepository, CounterCATALOGRepository>()
                .AddScoped<ISuburbCATALOGRepository, SuburbCATALOGRepository>()
                .AddScoped<IStateCATALOGRepository, StateCATALOGRepository>()

                // Business services
                // Services - API
                .AddScoped<IClientServices, ClientServices>()
                .AddScoped<IJobServices, JobServices>()

                //Services - Catalog
                .AddScoped<ITenantServices, TenantServices>()
                .AddScoped<IUserServices, UserServices>()
                //.AddScoped<IUserValidateService, UserValidateService>()

                // Services - Shared
                .AddScoped<IAddressDropdownServices, AddressDropdownServices>()

                //Services - Auth
                .AddScoped<ICryptoService, CryptoService>()
                .AddScoped<IUserAuthorisationServices, UserAuthorisationServices>()
                .AddScoped<IUserSession, UserSession>()
                .AddScoped<ISessionServices, SessionServices>()

                // CATALOG services - Initialisations.
                .AddScoped<ICATALOGCounterInitialiser, CATALOGCounterInitialiser>()
                .AddScoped<ICATALOGStateInitialiser, CATALOGStateInitialiser>()
                .AddScoped<ICATALOGSuburbInitialiser, CATALOGSuburbInitialiser>()
                .AddScoped<IRoleInitialiser, CATALOGRoleInitialiser>()
                .AddScoped<ICATALOGTenantAndUserInitialisations, CATALOGTenantAndUserInitialiser>()

                // DATA Services - Initialisations.
                .AddScoped<IBrandInitialiser, BrandInitialiser>()
                .AddScoped<IDATACounterInitialiser, DATACounterInitialiser>()
                .AddScoped<IDATAStateInitialiser, DATAStateInitialiser>()
                .AddScoped<IDATASuburbInitialiser, DATASuburbInitialiser>()
                .AddScoped<IStatusInitialiser, StatusInitialiser>()
                .AddScoped<ITypeInitialiser, TypeInitialiser>()
                .AddScoped<IVisitTypeInitialiser, VisitTypeInitialiser>()

                // TESTDATA Services - Initialisations.
                .AddScoped<ITESTDATAInitialisations, TESTDATAInitialisations>()
                .AddScoped<ITESTDATATenantAndUserInitialisations, TESTDATATenantAndUserInitialisations>()

                .AddTransient<IDATAContextFactory, DATAContextFactory>()
                .AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); // For getting the user.
        }

        public static void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
            if (env.IsDevelopment()) {
                app.UseDeveloperExceptionPage();
            }
            else {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseExceptionHandler(options => {
                options.Run(async context => {
                    var ex = context.Features.Get<IExceptionHandlerPathFeature>();
                    if (ex?.Error != null) {
                        Debugger.Break();
                    }
                });
            });

            app.UseRouting();

            // global cors policy
            app.UseCors(x => x
                .AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader());

            app.UseAuthentication();
            app.UseHttpsRedirection();
            app.UseFileServer();
            app.UseStaticFiles();
            app.UseSession();
            app.UseAuthorization();

            app.UseConfigureSession();

            app.EnsureCATALOGMigrationAndInitialise();
            app.EnsureDATAMigrationsAndInitialise();

            app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
        }
    }
}

Body:
Okay! got it. According to your current route configuration, your routing endpoints are:

/authenticate // <-- not api/authenticate
/JWTStatus    // <-- not api/JWTStatus

Because you are overriding the controller level route in action.

If you want api/authenticate and api/JWTStatus as your routing endpoints, then your action level route should be as follows:

[Authorize]
[ApiController]
//Remove the controller level route from here
public class JwtController : ControllerBase
{
    [AllowAnonymous]
    [Route("api/authenticate")] // <-- Here it is
    [HttpPost]
    public async Task<IActionResult> Authenticate([FromBody] LoginViewModel model)
    {
       .........
    }

    [Route("api/JWTStatus")] // <-- Here it is
    [HttpGet]
    public IActionResult GetJwtStatus()
    {
       .......
    }
}

But my suggestion is to follow the following convention:

[Authorize]
[ApiController]
[Route("api/[controller]/[action]")] // <-- Here it is
public class JwtController : ControllerBase
{
     [AllowAnonymous]
     [HttpPost]
     public async Task<IActionResult> Authenticate([FromBody] LoginViewModel model)
     {
        .......
     }

     [HttpGet]
     public IActionResult GetJwtStatus()
     {
        ......
     }
}

Now no action level route is required anymore and your endpoints will be:

api/Jwt/Authenticate
api/Jwt/GetJwtStatus


问:
Spring Data JPA - Named query ignoring null parameters
I have the following repository:

```<code>@Repository
public interface EntityRepository extends JpaRepository<Entity, Long> {

    List<Entity> findAllByFirstId(Long firstId);
    List<Entity> findAllBySecondId(Long secondId);
    List<Entity> findAllByFirstIdAndSecondId(Long firstId, Long secondId);
}
</code>```

The constructor implementing an interface generated with io.swagger:swagger-codegen-maven-plugin uses Optional<Long> as optional request parameters (the underlying service uses also the same parameters):

```<code>ResponseEntity<List<Entity>> entities(Optional<Long> firstId, Optional<Long> secondId);
</code>```

I would like to filter the entities based on the parameters firstId and secondId which are never nulls at the database but can be passed through the constructor (the parameter for searching is optional).

The problem comes with the named queries when the null is passed as the parameter is optional, the JpaReposotory uses the null as a criterion for the searching in the database. That's what I don't want - I want to ignore the filtering based on this parameter as long as it is null.

My workaround solution based on Optional is:

```<code>public List<Entity> entities(Optional<Long> firstId, Optional<Long> secondId) {

    return firstId
        .or(() -> secondId)
        .map(value -> {
            if (firstId.isEmpty()) {
                return entityRepository.findAllBySecondId(value);
            }
            if (secondId.isEmpty()) {
                return entityRepository.findAllByFirstId(value);
            }
            return entityRepository.findAllByFirstIdAndSecondId(
            firstId.get(), secondId.get());
        })
        .orElse(entityRepository.findAll())
        .stream()
        .map(...)     // Mapping between DTO and entity. For sake of brevity
                      // I used the same onject Entity for both controler and repository
                      // as long as it not related to the question

        .collect(Collectors.toList());
}
</code>```

This issue has been already asked: Spring Data - ignore parameter if it has a null value and a ticket created DATAJPA-209.

As long as the question is almost 3 years old and the ticket dates back to 2012, I would like to ask if there exists a more comfortable and universal way to avoid the overhead of handling the Optional and duplicating the repository methods. The solution for 2 such parameters looks acceptable, however I'd like to implement the very same filtering for 4-5 parameters.

答:
You need Specification utility class like this

```<code>public class EntitySpecifications {
    public static Specification<Entity> firstIdEquals(Optional<Long> firstId) {// or Long firstId. It is better to avoid Optional method parameters.
        return (root, query, builder) ->
            firstId.isPresent() ? // or firstId != null if you use Long method parameter
            builder.equal(root.get("firstId"), firstId.get()) :
            builder.conjunction(); // to ignore this clause
    }

    public static Specification<Entity> secondIdEquals(Optional<Long> secondId) {
        return (root, query, builder) ->
            secondId.isPresent() ?
            builder.equal(root.get("secondId"), secondId.get()) :
            builder.conjunction(); // to ignore this clause
    }
}
</code>```

Then your EntityRepository have to extend JpaSpecificationExecutor

```<code>@Repository
public interface EntityRepository
    extends JpaRepository<Entity, Long>, JpaSpecificationExecutor<Entity> {

}
</code>```

Usage:

```<code>@Service
public class EntityService {

    @Autowired
    EntityRepository repository;

    public List<Entity> getEntities(Optional<Long> firstId, Optional<Long> secondId) {
        Specification<Entity> spec =
            Specifications.where(EntitySpecifications.firstIdEquals(firstId)) //Spring Data JPA 2.0: use Specification.where
                          .and(EntitySpecifications.secondIdEquals(secondId));

        return repository.findAll(spec);
    }
}
</code>```

Body:
I have the following repository:

@Repository
public interface EntityRepository extends JpaRepository<Entity, Long> {

    List<Entity> findAllByFirstId(Long firstId);
    List<Entity> findAllBySecondId(Long secondId);
    List<Entity> findAllByFirstIdAndSecondId(Long firstId, Long secondId);
}

The constructor implementing an interface generated with io.swagger:swagger-codegen-maven-plugin uses Optional<Long> as optional request parameters (the underlying service uses also the same parameters):

ResponseEntity<List<Entity>> entities(Optional<Long> firstId, Optional<Long> secondId);

I would like to filter the entities based on the parameters firstId and secondId which are never nulls at the database but can be passed through the constructor (the parameter for searching is optional).

The problem comes with the named queries when the null is passed as the parameter is optional, the JpaReposotory uses the null as a criterion for the searching in the database. That's what I don't want - I want to ignore the filtering based on this parameter as long as it is null.

My workaround solution based on Optional is:

public List<Entity> entities(Optional<Long> firstId, Optional<Long> secondId) {

    return firstId
        .or(() -> secondId)
        .map(value -> {
            if (firstId.isEmpty()) {
                return entityRepository.findAllBySecondId(value);
            }
            if (secondId.isEmpty()) {
                return entityRepository.findAllByFirstId(value);
            }
            return entityRepository.findAllByFirstIdAndSecondId(
            firstId.get(), secondId.get());
        })
        .orElse(entityRepository.findAll())
        .stream()
        .map(...)     // Mapping between DTO and entity. For sake of brevity
                      // I used the same onject Entity for both controler and repository
                      // as long as it not related to the question

        .collect(Collectors.toList());
}

This issue has been already asked: Spring Data - ignore parameter if it has a null value and a ticket created DATAJPA-209.

As long as the question is almost 3 years old and the ticket dates back to 2012, I would like to ask if there exists a more comfortable and universal way to avoid the overhead of handling the Optional and duplicating the repository methods. The solution for 2 such parameters looks acceptable, however I'd like to implement the very same filtering for 4-5 parameters.

Body:
You need Specification utility class like this

public class EntitySpecifications {
    public static Specification<Entity> firstIdEquals(Optional<Long> firstId) {// or Long firstId. It is better to avoid Optional method parameters.
        return (root, query, builder) ->
            firstId.isPresent() ? // or firstId != null if you use Long method parameter
            builder.equal(root.get("firstId"), firstId.get()) :
            builder.conjunction(); // to ignore this clause
    }

    public static Specification<Entity> secondIdEquals(Optional<Long> secondId) {
        return (root, query, builder) ->
            secondId.isPresent() ?
            builder.equal(root.get("secondId"), secondId.get()) :
            builder.conjunction(); // to ignore this clause
    }
}

Then your EntityRepository have to extend JpaSpecificationExecutor

@Repository
public interface EntityRepository
    extends JpaRepository<Entity, Long>, JpaSpecificationExecutor<Entity> {

}

Usage:

@Service
public class EntityService {

    @Autowired
    EntityRepository repository;

    public List<Entity> getEntities(Optional<Long> firstId, Optional<Long> secondId) {
        Specification<Entity> spec =
            Specifications.where(EntitySpecifications.firstIdEquals(firstId)) //Spring Data JPA 2.0: use Specification.where
                          .and(EntitySpecifications.secondIdEquals(secondId));

        return repository.findAll(spec);
    }
}


问:
Date comparison in Laravel 5.8
I have the date stored in database and current date using Carbon,
format: MM/DD/YYYY

I want to compare that the date stored in database has passed away as compared to today's date, comparison in Laravel Query Builder to select data!

I'm working in laravel 5.8
Please, suggest solution!

答:
You can compare it with now():

if ($this->created_at > now()) {
    return 'Date is in the future';
} else {
    return 'Date is in the past';
}
```

Title: Date comparison in Laravel 5.8


问:
How can I delete a downloaded file using Selenium RemoteWebDriver?
I am writing a test to check that a file can be downloaded from a particular web page and I want it to be able to run both locally and remotely (i.e. on a node via Selenium grid). Before anyone links me to the 'do you really need to download the file?' article, I have already managed to download and check the file, I just need a way of deleting it after the test has completed. Just calling File.delete(); or similar will only work locally (as far as I'm aware) so I can't use that to delete the file from the node machine. I'm aware of the class org.openqa.selenium.io.TemporaryFileSystem however I can't find any instructions for how to use it.

Can anyone offer a better solution than 'just run a script on the node machine to delete the file'? Thanks!

答:
The Below Code will sequentially delete all the files from folder</p>

```<code>    File path = new File("Path of Folder");
    File[] files = path.listFiles();
    for (File file : files) {
        System.out.println("Deleted filename :"+ file.getName());
        file.delete();
    }
</code>```

Body:
The Below Code will sequentially delete all the files from folder

    File path = new File("Path of Folder");
    File[] files = path.listFiles();
    for (File file : files) {
        System.out.println("Deleted filename :"+ file.getName());
        file.delete();
    }


问:
When the keyboard appears, the Flutter widgets resize. How to prevent this?
I have a Column of Expanded widgets like this:

```<code> return new Container(
      child: new Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: <Widget>[
          new Expanded(
            flex: 1,
            child: convertFrom,
          ),
          new Expanded(
            flex: 1,
            child: convertTo,
          ),
          new Expanded(
            flex: 1,
            child: description,
          ),
        ],
      ),
    );
</code>```

It looks like this:

convertFrom, includes a TextField. When I tap on this text field, the Android keyboard appears on the screen. This changes the screen size, so the widgets resize like this:

Is there a way to have the keyboard "overlay" the screen so that my Column doesn't resize? If I don't use Expanded widgets and hardcode a height for each widget, the widgets don't resize, but I get the black-and-yellow striped error when the keyboard appears (because there isn't enough space). This also isn't flexible for all screen sizes.

I'm not sure if this is an Android-specific or Flutter-specific.

答:
Most other answers suggest using resizeToAvoidBottomPadding=false. In my experience this allows the keyboard to cover up text fields if they are underneath where the keyboard would appear.

My current solution is to force my column to be the same height as the screen, then place it in a SingleChildScrollView so that Flutter automatically scrolls my screen up just enough when the keyboard is used.

```<code>Widget build(BuildContext context) {
  return Scaffold(
    body: SingleChildScrollView(
      physics: const NeverScrollableScrollPhysics(),
      child: ConstrainedBox(
        constraints: BoxConstraints(
          minWidth: MediaQuery.of(context).size.width,
          minHeight: MediaQuery.of(context).size.height,
        ),
        child: IntrinsicHeight(
          child: Column(
            mainAxisSize: MainAxisSize.max,
            children: <Widget>[
              // CONTENT HERE
            ],
          ),
        ),
      ),
    ),
  );
}
</code>```

I use NeverScrollableScrollPhysics so that the user cannot scroll around themselves.

Body:
I have a Column of Expanded widgets like this:

 return new Container(
      child: new Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: <Widget>[
          new Expanded(
            flex: 1,
            child: convertFrom,
          ),
          new Expanded(
            flex: 1,
            child: convertTo,
          ),
          new Expanded(
            flex: 1,
            child: description,
          ),
        ],
      ),
    );

It looks like this:

convertFrom, includes a TextField. When I tap on this text field, the Android keyboard appears on the screen. This changes the screen size, so the widgets resize like this:

Is there a way to have the keyboard "overlay" the screen so that my Column doesn't resize? If I don't use Expanded widgets and hardcode a height for each widget, the widgets don't resize, but I get the black-and-yellow striped error when the keyboard appears (because there isn't enough space). This also isn't flexible for all screen sizes.

I'm not sure if this is an Android-specific or Flutter-specific.

Body:
Most other answers suggest using resizeToAvoidBottomPadding=false. In my experience this allows the keyboard to cover up text fields if they are underneath where the keyboard would appear.

My current solution is to force my column to be the same height as the screen, then place it in a SingleChildScrollView so that Flutter automatically scrolls my screen up just enough when the keyboard is used.

Widget build(BuildContext context) {
  return Scaffold(
    body: SingleChildScrollView(
      physics: const NeverScrollableScrollPhysics(),
      child: ConstrainedBox(
        constraints: BoxConstraints(
          minWidth: MediaQuery.of(context).size.width,
          minHeight: MediaQuery.of(context).size.height,
        ),
        child: IntrinsicHeight(
          child: Column(
            mainAxisSize: MainAxisSize.max,
            children: <Widget>[
              // CONTENT HERE
            ],
          ),
        ),
      ),
    ),
  );
}

I use NeverScrollableScrollPhysics so that the user cannot scroll around themselves.