问:
Vue JS dynamic components in routes. Handling loading and error
In my vue application, I am importing the components dynamically which are then being used in the routes. So when you go to a specific route, the component chunk will be fetched dynamically.

Sometimes it takes time to fetch the components and sometimes due to network error the component couldn't be fetched. So I want to understand how can I handle the error and loading state gracefully.

答:
Vue allows you to define your component as a factory function that asynchronously resolves your component definition. This is called an async component factory.

Usually when we lazy load our router views with Webpack we do:

```<code>export default [
  {
    path: '/',
    name: 'home',
    component: () => import('@views/home'),
    //               ^^^^^^^^^^^^^^^^^^^^^
    //               The `import` function returns a Promise with our component definition.
  },
] // RouteConfig[]
</code>```

But, what happens when we need to handle the loading state?

Since Vue 2.3.0 and Vue Router 2.4.0, the async component factory can also return an object:

```<code>export default [
  {
    path: '/',
    name: 'home',
    component: () => ({
      // The component to load (should be a Promise)
      component: import('./MyComponent.vue'),
      // A component to use while the async component is loading
      loading: LoadingComponent,
      // A component to use if the load fails
      error: ErrorComponent,
      // Delay before showing the loading component. Default: 200ms.
      delay: 200,
      // The error component will be displayed if a timeout is
      // provided and exceeded. Default: Infinity.
      timeout: 3000
    })
  },
] // RouteConfig[]
</code>```

You may want to reuse the same loading and error components for different views, along with some delay and timeout defaults. If that is the case, you can use a strategy found in this vue enterprise boilerplate created by Chris Fritz, a Vue core team member.

```<code>// Lazy-loads view components, but with better UX. A loading view
// will be used if the component takes a while to load, falling
// back to a timeout view in case the page fails to load. You can
// use this component to lazy-load a route with:
//
// component: () => lazyLoadView(import('@views/my-view'))
//
// NOTE: Components loaded with this strategy DO NOT have access
// to in-component guards, such as beforeRouteEnter,
// beforeRouteUpdate, and beforeRouteLeave. You must either use
// route-level guards instead or lazy-load the component directly:
//
// component: () => import('@views/my-view')
//
function lazyLoadView(AsyncView) {
  const AsyncHandler = () => ({
    component: AsyncView,
    // A component to use while the component is loading.
    loading: require('@views/_loading').default,
    // Delay before showing the loading component.
    // Default: 200 (milliseconds).
    delay: 400,
    // A fallback component in case the timeout is exceeded
    // when loading the component.
    error: require('@views/_timeout').default,
    // Time before giving up trying to load the component.
    // Default: Infinity (milliseconds).
    timeout: 10000,
  })

  return Promise.resolve({
    functional: true,
    render(h, { data, children }) {
      // Transparently pass any props or children
      // to the view component.
      return h(AsyncHandler, data, children)
    },
  })
}
</code>```

And use it like so:

```<code>export default [
  {
    path: '/',
    name: 'home',
    component: () => lazyLoadView(import('@views/home')),
  },
] // RouteConfig[]
</code>```

Body:
Vue allows you to define your component as a factory function that asynchronously resolves your component definition. This is called an async component factory.

Usually when we lazy load our router views with Webpack we do:

export default [
  {
    path: '/',
    name: 'home',
    component: () => import('@views/home'),
    //               ^^^^^^^^^^^^^^^^^^^^^
    //               The `import` function returns a Promise with our component definition.
  },
] // RouteConfig[]

But, what happens when we need to handle the loading state?

Since Vue 2.3.0 and Vue Router 2.4.0, the async component factory can also return an object:

export default [
  {
    path: '/',
    name: 'home',
    component: () => ({
      // The component to load (should be a Promise)
      component: import('./MyComponent.vue'),
      // A component to use while the async component is loading
      loading: LoadingComponent,
      // A component to use if the load fails
      error: ErrorComponent,
      // Delay before showing the loading component. Default: 200ms.
      delay: 200,
      // The error component will be displayed if a timeout is
      // provided and exceeded. Default: Infinity.
      timeout: 3000
    })
  },
] // RouteConfig[]

You may want to reuse the same loading and error components for different views, along with some delay and timeout defaults. If that is the case, you can use a strategy found in this vue enterprise boilerplate created by Chris Fritz, a Vue core team member.

// Lazy-loads view components, but with better UX. A loading view
// will be used if the component takes a while to load, falling
// back to a timeout view in case the page fails to load. You can
// use this component to lazy-load a route with:
//
// component: () => lazyLoadView(import('@views/my-view'))
//
// NOTE: Components loaded with this strategy DO NOT have access
// to in-component guards, such as beforeRouteEnter,
// beforeRouteUpdate, and beforeRouteLeave. You must either use
// route-level guards instead or lazy-load the component directly:
//
// component: () => import('@views/my-view')
//
function lazyLoadView(AsyncView) {
  const AsyncHandler = () => ({
    component: AsyncView,
    // A component to use while the component is loading.
    loading: require('@views/_loading').default,
    // Delay before showing the loading component.
    // Default: 200 (milliseconds).
    delay: 400,
    // A fallback component in case the timeout is exceeded
    // when loading the component.
    error: require('@views/_timeout').default,
    // Time before giving up trying to load the component.
    // Default: Infinity (milliseconds).
    timeout: 10000,
  })

  return Promise.resolve({
    functional: true,
    render(h, { data, children }) {
      // Transparently pass any props or children
      // to the view component.
      return h(AsyncHandler, data, children)
    },
  })
}

And use it like so:

export default [
  {
    path: '/',
    name: 'home',
    component: () => lazyLoadView(import('@views/home')),
  },
] // RouteConfig[]


来源: stackexchange

问:
Does VLOOKUP compare cells
I am currently using the VLOOKUP function for excel and I was wondering does the VLOOKUP actually compare cells or does it just use the cell straight across from it?

This is my formula "=VLOOKUP(A2,Sheet3!A2:B1814,2,FALSE)"

As you can see the VLOOKUP function works find for the first product image but it doesnt for the rest of them( it will give #N/A for most of them because the cell in the pic in the right is empty which is ok), but if you look at the picture on the left, cell A4 is the same as cell A3 on the picture on the right and it is still given me #N/A(this is because they are not in the same cells)

So my question is, is there a way for excel to check the table 1(left pic) to see is there a matching name on table2(right pic) by searching the rows?

Thanks

答:
You have to use absolute references for your table array, otherwise the area will be shifted, when you copy your formula down.</p>

```<code>=VLOOKUP(A2;Sheet3!$A$2:$B$1814;2;FALSE)
</code>```

ContentLicense: CC BY-SA 3.0

Title: Does VLOOKUP compare cells

Body:
You have to use absolute references for your table array, otherwise the area will be shifted, when you copy your formula down.

=VLOOKUP(A2;Sheet3!$A$2:$B$1814;2;FALSE)


问:
Angular how to show live value of json object
In angular , I am trying to display one json object to client html. Using below route on server side.

```<code>const express = require('express');
const jsonRoute = express.Router();

jsonRoute .route('/json').get(function (req, res) {
    var JsonObj = { rank: 73 } ;
  res.end(JSON.stringify(JsonObj));
});

setInterval(function(){
    JsonObj.rank = parseInt(Math.random()*100);
}, 1000); // this interval may be anything.from ms to minutes.

module.exports = jsonRoute ;
</code>```

this works on http://localhost:4000/json and displays ,

```<code>{"rank":73}
</code>```

But does not show the values changed in setInterval. And same route i am using in a angular service (using http).

```<code>import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
@Injectable({
  providedIn: 'root'
})
export class getjsonService {
  uri = "http://localhost:4000/json";
  constructor(private http: HttpClient) { }
  jsondata(){
    return this.http.get(`${this.uri}`);
  }
}
</code>```

This value i am displaying in component html page. The problem is, it is not showing updated value of json. Please suggest how can i show live json value in angular. Please note, in realtime my json object going to be big in size , around 100 keys and value and i want to show live value for all key. And also change value interval may not be fix as one second. it may be in milliseconds as well.

Thanks

答:
In your node.js code, you are re-inializing the JsonObj variable every time the request is made.  You should store the value as a global variable:

```<code>const express = require('express');
const jsonRoute = express.Router();

var JsonObj = { rank: 73 };

jsonRoute .route('/json').get(function (req, res) {
    res.json(JsonObj);
});

setInterval(function(){
    JsonObj.rank = parseInt(Math.random()*100);
}, 1000); // this interval may be anything.from ms to minutes.

module.exports = jsonRoute ;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In angular , I am trying to display one json object to client html. Using below route on server side.

const express = require('express');
const jsonRoute = express.Router();

jsonRoute .route('/json').get(function (req, res) {
    var JsonObj = { rank: 73 } ;
  res.end(JSON.stringify(JsonObj));
});

setInterval(function(){
    JsonObj.rank = parseInt(Math.random()*100);
}, 1000); // this interval may be anything.from ms to minutes.

module.exports = jsonRoute ;

this works on http://localhost:4000/json and displays ,

{"rank":73}

But does not show the values changed in setInterval. And same route i am using in a angular service (using http).

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
@Injectable({
  providedIn: 'root'
})
export class getjsonService {
  uri = "http://localhost:4000/json";
  constructor(private http: HttpClient) { }
  jsondata(){
    return this.http.get(`${this.uri}`);
  }
}

This value i am displaying in component html page. The problem is, it is not showing updated value of json. Please suggest how can i show live json value in angular. Please note, in realtime my json object going to be big in size , around 100 keys and value and i want to show live value for all key. And also change value interval may not be fix as one second. it may be in milliseconds as well.

Thanks

Body:
In your node.js code, you are re-inializing the JsonObj variable every time the request is made.  You should store the value as a global variable:

const express = require('express');
const jsonRoute = express.Router();

var JsonObj = { rank: 73 };

jsonRoute .route('/json').get(function (req, res) {
    res.json(JsonObj);
});

setInterval(function(){
    JsonObj.rank = parseInt(Math.random()*100);
}, 1000); // this interval may be anything.from ms to minutes.

module.exports = jsonRoute ;


问:
Plink timeout and proxy under linux
I have made a script in bash which create a connection to a list of server.
After each connection, if it succeed, i execute a command.
Connections are under a loop.

For know i use Plink.
My script works, but it takes too much time when the server is unreachable.
I encountered another issue when i wanted to reach a server through a proxy.

I have two goals :

Configure the timeout of Plink in command line under Linux to make it shorter ("FATAL ERROR: Connection timed out" takes to much time to appear).

Configure the proxy configuration of Plink to have the equivalent of the SOCKS5 and proxy hostname of PuTTY.

I don't know if it is possible.
If you have a better way, i'll be glad to know it

regards,
Mageni

答:
Since your client is running Linux, I suggest using the openSSH ssh client that almost certainly comes with it, rather than plink.

1) OpenSSH's ssh client supports setting connection timeouts from commandline, e.g. to have it time out after 5 seconds you would use:

```<code>    ssh -o ConnectTimeout=5 <server>
</code>```

2) Not entirely what you mean by this goal. Are you trying to connect to an SSH server through a socks5 proxy, or trying to configure a socks5 proxy locally by using an ssh client to proxy traffic to a remote system running an SSH server? If you elaborate, I can amend this response to include how to do either one.

Title: Plink timeout and proxy under linux

Body:
Since your client is running Linux, I suggest using the openSSH ssh client that almost certainly comes with it, rather than plink.

1) OpenSSH's ssh client supports setting connection timeouts from commandline, e.g. to have it time out after 5 seconds you would use:

    ssh -o ConnectTimeout=5 <server>

2) Not entirely what you mean by this goal. Are you trying to connect to an SSH server through a socks5 proxy, or trying to configure a socks5 proxy locally by using an ssh client to proxy traffic to a remote system running an SSH server? If you elaborate, I can amend this response to include how to do either one.


问:
How practical is it to intercept certain SMS messages in Android but allow others to be handled by the built-in messaging app?
I've been developing an Android app that allows the operator to control equipment through API calls, which are sent and received via text messages.

Since we want people to still be able to use their phones as phones, we still want users to be able to send and receive text message with the built-in SMS app.

However, the issue with my app is that it is not the default SMS app, which means that these control messages:

Look like total garbage, so I would want to be able to delete these messages from a user's inbox (or have them never reach the inbox).

They also show a notification, since they're an SMS message and are handled by the system SMS app as such.

If I block a number, using the built-in SMS app, my app won't receive it either - so the logic, therefore, is to make my app the default SMS app so that it can intercept all messages before deciding how they should be handled. The problem now is that no other messages will reach the built-in SMS app.

One way around this is to forward messages to this built-in SMS app's inbox, but the built-in SMS app would no longer be able to send messages.

The inevitable answer that I expect is the only technically viable option is that I will have to implement a full SMS client in its entirety; however, this seems a really poor approach to me and massively pollutes the scope of development.

Is there really no way for me to create a default SMS app that can then "forward" an incoming SMS to either the built-in SMS app or my own app (for controlling the aforementioned machinery)?

答:
Use port-addressed data (binary) SMS. These are routed directly to your app on the way in, bypassing the "default SMS app". Outgoing binary SMS are also not stored in the "default SMS app"s SENT or OUTBOX, so your users won't see them.

See http://codetheory.in/android-sms/ for details about how to do this, or search Stackoverflow or other sites for howtos or tutorials for sending and receiving port-addressed data (binary) SMS.


问:
Can't get asp .net core 2.2 to validate my JWT
(TL;DR: check the last update)

The first issue with this is that the API has changed between the different versions of .net core.

The second one is that every example I find online is slightly different with not real authoritative answer as to what does what; rather I keep finding posts with 'oh, changing this worked for me', but it looks like everyone is, like me, experimenting with it rather than having a full understanding.

Anyhow, here is the code:

```<code>        Services.AddAuthentication(A =>
        {
            A.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            A.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        })
        .AddJwtBearer(O =>
        {
            O.RequireHttpsMetadata = false;
            O.SaveToken = true;
            O.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(AuthJWTPublicKey)),
                ValidateIssuer = false,
                ValidateAudience = false
            };
        });
</code>```

I have a valid JWT but any call to my controller results in an immediate error 401.

I have tried to decorate the controller with:

[Authorize]

[Authorize(Roles = "offline_access")]

[Authorize(AuthenticationSchemes =
  JwtBearerDefaults.AuthenticationScheme, Roles = "offline_access")]

but no luck

The JWT content is:

```<code>{
   "jti":"837c2dd1-cca5-491e-84a4-b17429366df5",
   "exp":1558355152,
   "nbf":0,
   "iat":1558354852,
   "iss":"xxxx",
   "aud":"account",
   "sub":"4ed1c313-c692-44db-86d3-7605f3e2c2c1",
   "typ":"Bearer",
   "azp":"test-app",
   "auth_time":1558354850,
   "session_state":"e40c9a95-ae8a-4d6e-b2a4-ad5e833867ea",
   "acr":"1",
   "realm_access":{
      "roles":[
         "offline_access",
         "uma_authorization"
      ]
   },
   "resource_access":{
      "account":{
         "roles":[
            "manage-account",
            "manage-account-links",
            "view-profile"
         ]
      }
   },
   "scope":"openid email profile",
   "email_verified":true,
   "name":"firstd6d05 last29954",
   "preferred_username":"xxxx",
   "given_name":"firstd6d05",
   "family_name":"last29954",
   "email":"xxxx",
   "group":[
      "/Administrators"
   ]
}
</code>```

My goal is purely to verify the signature of the JWT (and eventually it's expiration) and have access to the token in the controller.

I am passing the JWT through the header, under 'Authorization' and with the text 'Bearer' in front of the token.

What am I missing?

Following the answer below, I did the following change:

I added:

```<code>Services.AddTransient<IClaimsTransformation, ClaimsTransformer>();
</code>```

and then added the following class with a break

```<code>internal class ClaimsTransformer : IClaimsTransformation
{
    public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
    {
        Debugger.Break();
    }
}
</code>```

but I am still getting a 401 with the Keycloak token; so it looks like it doesn't get to the claims transformer before being rejected.

I added the debug output of ASP.

It is at: https://pastebin.com/qvGsQG6j

The relevant part seems to be:

```<code>    info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2]
          => ConnectionId:0HLN4CPASJL8F => RequestId:0HLN4CPASJL8F:00000001 RequestPath:/helpers/log => Test.WebControllers.HelpersController.GetLog (Test)
          Authorization failed.
    Microsoft.AspNetCore.Authorization.DefaultAuthorizationService:Info:Authorization failed.
    Microsoft.AspNetCore.Authorization.DefaultAuthorizationService:Info:Authorization failed.
    info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[3]
          => ConnectionId:0HLN4CPASJL8F => RequestId:0HLN4CPASJL8F:00000001 RequestPath:/helpers/log => Test.WebControllers.HelpersController.GetLog (Test)
          Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
    Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Info:Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
    Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Info:Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
    info: Microsoft.AspNetCore.Mvc.ChallengeResult[1]
          => ConnectionId:0HLN4CPASJL8F => RequestId:0HLN4CPASJL8F:00000001 RequestPath:/helpers/log => Test.WebControllers.HelpersController.GetLog (Test)
</code>```

This specific line may explain the issue:

Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'

but 'failed' seems a bit vague to me.

Last test:

I have this token:

```<code>eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoibXkgbmFtZSIsImh0dHA6Ly9zY2hlbWFzLnhtbHNvYXAub3JnL3dzLzIwMDUvMDUvaWRlbnRpdHkvY2xhaW1zL2VtYWlsYWRkcmVzcyI6Im5vQGVtYWlsLmNvbSIsImh0dHA6Ly9zY2hlbWFzLm1pY3Jvc29mdC5jb20vd3MvMjAwOC8wNi9pZGVudGl0eS9jbGFpbXMvZXhwaXJhdGlvbiI6IjA1LzMxLzIwMTkgMDA6MTM6MjAiLCJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9zaWQiOiI3Y2FjZjdiNS04NjY5LTQ2OWUtOTg4NS1kNDgwNGYyOGNjNGEiLCJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA5LzA5L2lkZW50aXR5L2NsYWltcy9hY3RvciI6ImQyZjZiNzI0LWE0ZjktNGJkZC1hNjQ3LTRkM2UxYTU5NjhkZSIsIm5iZiI6MTU1OTE3NTIwMCwiZXhwIjoxNTU5MjYxNjAwLCJpc3MiOiJ0ZXN0IiwiYXVkIjoidGVzdC1hcHAifQ.y42RUvMM69aDTvCydoU3mOKu2giub6OvKpd-RNVmom4
</code>```

with the key:

```<code>MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjayVuqZOuKK38rhsRwrRGzVcv/7b4fHXrzpol3K5TTAPttNUaQvCKQD7BQN+V8nvkBsQcxPk5ONnxzbFb/npENC4UtwK5J6iiVrinE7sDrWZQNo9LkwbuG9x0fuuf8U3H2CnwZEfFaf2kbU1v7XosNGi+aYASupvhwoiJtK+17ZPloxSQy3Qny2tQWi7Dh/Cr5+m5JBy6HeGLq2cq+oalFYzrGGmQXndLtJpBZgrPd7nR6lJSMiRcJtcpxTJbYTEVVXoB0SR1bPmYYB/6y7klVDVedTow+1mwZrDMrbRiTBPSifCIBs3rxLQaL207blg+kj+EVLED5fZSOBlOyTOYQIDAQAB
</code>```

it decodes to (as tested by jwt.io):

```<code>{
  "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name": "my name",
  "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress": "no@email.com",
  "http://schemas.microsoft.com/ws/2008/06/identity/claims/expiration": "05/31/2019 00:13:20",
  "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/sid": "7cacf7b5-8669-469e-9885-d4804f28cc4a",
  "http://schemas.xmlsoap.org/ws/2009/09/identity/claims/actor": "d2f6b724-a4f9-4bdd-a647-4d3e1a5968de",
  "nbf": 1559175200,
  "exp": 1559261600,
  "iss": "test",
  "aud": "test-app"
}
</code>```

it is generated by the following code:

```<code>        var Expiration = DateTime.UtcNow + TimeSpan.FromDays(1);
        var Identity = new ClaimsIdentity(new[]
        {
            new Claim(ClaimTypes.Name,          "my name"),
            new Claim(ClaimTypes.Email,         "no@email.com"),
            new Claim(ClaimTypes.Expiration,    Expiration.ToString(CultureInfo.InvariantCulture)),
            new Claim(ClaimTypes.Sid,           Guid.NewGuid().ToString()),
            new Claim(ClaimTypes.Actor,         Guid.NewGuid().ToString()),
        });

        var Token = new JwtSecurityToken
        (
            issuer:             "test",
            audience:           "test-app",
            claims:             Identity.Claims,
            notBefore:          DateTime.UtcNow,
            expires:            Expiration,
            signingCredentials: new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_JwtRsaPublicKey)), SecurityAlgorithms.HmacSha256)
        );

        var TokenString = new JwtSecurityTokenHandler().WriteToken(Token);
        return TokenString;
</code>```

In asp, I have the following code:

```<code>                    Services.AddAuthentication(A =>
                    {
                        A.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                        A.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                    })
                    .AddJwtBearer(O =>
                    {
                        O.RequireHttpsMetadata = false;
                        O.SaveToken = true;
                        O.IncludeErrorDetails = true;
                        O.TokenValidationParameters = new TokenValidationParameters
                        {
                            ValidateIssuerSigningKey = true,
                            IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(AuthJWTPublicKey)),
                            ValidateIssuer = false,
                            ValidateAudience = false
                        };
                    });
</code>```

and I have a controller method with:

```<code>{
   "jti":"837c2dd1-cca5-491e-84a4-b17429366df5",
   "exp":1558355152,
   "nbf":0,
   "iat":1558354852,
   "iss":"xxxx",
   "aud":"account",
   "sub":"4ed1c313-c692-44db-86d3-7605f3e2c2c1",
   "typ":"Bearer",
   "azp":"test-app",
   "auth_time":1558354850,
   "session_state":"e40c9a95-ae8a-4d6e-b2a4-ad5e833867ea",
   "acr":"1",
   "realm_access":{
      "roles":[
         "offline_access",
         "uma_authorization"
      ]
   },
   "resource_access":{
      "account":{
         "roles":[
            "manage-account",
            "manage-account-links",
            "view-profile"
         ]
      }
   },
   "scope":"openid email profile",
   "email_verified":true,
   "name":"firstd6d05 last29954",
   "preferred_username":"xxxx",
   "given_name":"firstd6d05",
   "family_name":"last29954",
   "email":"xxxx",
   "group":[
      "/Administrators"
   ]
}
</code>```0

But I keep getting a 401, no matter what I try, I get a 401...

Even if I set ValidateIssuerSigningKey to false. I get a 401

The setup is:

In ConfigureServices, I have:

```<code>{
   "jti":"837c2dd1-cca5-491e-84a4-b17429366df5",
   "exp":1558355152,
   "nbf":0,
   "iat":1558354852,
   "iss":"xxxx",
   "aud":"account",
   "sub":"4ed1c313-c692-44db-86d3-7605f3e2c2c1",
   "typ":"Bearer",
   "azp":"test-app",
   "auth_time":1558354850,
   "session_state":"e40c9a95-ae8a-4d6e-b2a4-ad5e833867ea",
   "acr":"1",
   "realm_access":{
      "roles":[
         "offline_access",
         "uma_authorization"
      ]
   },
   "resource_access":{
      "account":{
         "roles":[
            "manage-account",
            "manage-account-links",
            "view-profile"
         ]
      }
   },
   "scope":"openid email profile",
   "email_verified":true,
   "name":"firstd6d05 last29954",
   "preferred_username":"xxxx",
   "given_name":"firstd6d05",
   "family_name":"last29954",
   "email":"xxxx",
   "group":[
      "/Administrators"
   ]
}
</code>```1

In Configure, I have:

```<code>{
   "jti":"837c2dd1-cca5-491e-84a4-b17429366df5",
   "exp":1558355152,
   "nbf":0,
   "iat":1558354852,
   "iss":"xxxx",
   "aud":"account",
   "sub":"4ed1c313-c692-44db-86d3-7605f3e2c2c1",
   "typ":"Bearer",
   "azp":"test-app",
   "auth_time":1558354850,
   "session_state":"e40c9a95-ae8a-4d6e-b2a4-ad5e833867ea",
   "acr":"1",
   "realm_access":{
      "roles":[
         "offline_access",
         "uma_authorization"
      ]
   },
   "resource_access":{
      "account":{
         "roles":[
            "manage-account",
            "manage-account-links",
            "view-profile"
         ]
      }
   },
   "scope":"openid email profile",
   "email_verified":true,
   "name":"firstd6d05 last29954",
   "preferred_username":"xxxx",
   "given_name":"firstd6d05",
   "family_name":"last29954",
   "email":"xxxx",
   "group":[
      "/Administrators"
   ]
}
</code>```2

答:
I am not sure what is stored in the variable but it looks like it's not a private token:

```<code>IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(AuthJWTPublicKey)),
</code>```

This is as far as I know a private symmetric key, perhaps you are passing a wrong value in there?

Body:
(TL;DR: check the last update)

The first issue with this is that the API has changed between the different versions of .net core.

The second one is that every example I find online is slightly different with not real authoritative answer as to what does what; rather I keep finding posts with 'oh, changing this worked for me', but it looks like everyone is, like me, experimenting with it rather than having a full understanding.

Anyhow, here is the code:

        Services.AddAuthentication(A =>
        {
            A.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            A.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        })
        .AddJwtBearer(O =>
        {
            O.RequireHttpsMetadata = false;
            O.SaveToken = true;
            O.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(AuthJWTPublicKey)),
                ValidateIssuer = false,
                ValidateAudience = false
            };
        });

I have a valid JWT but any call to my controller results in an immediate error 401.

I have tried to decorate the controller with:

[Authorize]

[Authorize(Roles = "offline_access")]

[Authorize(AuthenticationSchemes =
  JwtBearerDefaults.AuthenticationScheme, Roles = "offline_access")]

but no luck

The JWT content is:

{
   "jti":"837c2dd1-cca5-491e-84a4-b17429366df5",
   "exp":1558355152,
   "nbf":0,
   "iat":1558354852,
   "iss":"xxxx",
   "aud":"account",
   "sub":"4ed1c313-c692-44db-86d3-7605f3e2c2c1",
   "typ":"Bearer",
   "azp":"test-app",
   "auth_time":1558354850,
   "session_state":"e40c9a95-ae8a-4d6e-b2a4-ad5e833867ea",
   "acr":"1",
   "realm_access":{
      "roles":[
         "offline_access",
         "uma_authorization"
      ]
   },
   "resource_access":{
      "account":{
         "roles":[
            "manage-account",
            "manage-account-links",
            "view-profile"
         ]
      }
   },
   "scope":"openid email profile",
   "email_verified":true,
   "name":"firstd6d05 last29954",
   "preferred_username":"xxxx",
   "given_name":"firstd6d05",
   "family_name":"last29954",
   "email":"xxxx",
   "group":[
      "/Administrators"
   ]
}

My goal is purely to verify the signature of the JWT (and eventually it's expiration) and have access to the token in the controller.

I am passing the JWT through the header, under 'Authorization' and with the text 'Bearer' in front of the token.

What am I missing?

Following the answer below, I did the following change:

I added:

Services.AddTransient<IClaimsTransformation, ClaimsTransformer>();

and then added the following class with a break

internal class ClaimsTransformer : IClaimsTransformation
{
    public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
    {
        Debugger.Break();
    }
}

but I am still getting a 401 with the Keycloak token; so it looks like it doesn't get to the claims transformer before being rejected.

I added the debug output of ASP.

It is at: https://pastebin.com/qvGsQG6j

The relevant part seems to be:

    info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2]
          => ConnectionId:0HLN4CPASJL8F => RequestId:0HLN4CPASJL8F:00000001 RequestPath:/helpers/log => Test.WebControllers.HelpersController.GetLog (Test)
          Authorization failed.
    Microsoft.AspNetCore.Authorization.DefaultAuthorizationService:Info:Authorization failed.
    Microsoft.AspNetCore.Authorization.DefaultAuthorizationService:Info:Authorization failed.
    info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[3]
          => ConnectionId:0HLN4CPASJL8F => RequestId:0HLN4CPASJL8F:00000001 RequestPath:/helpers/log => Test.WebControllers.HelpersController.GetLog (Test)
          Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
    Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Info:Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
    Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Info:Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
    info: Microsoft.AspNetCore.Mvc.ChallengeResult[1]
          => ConnectionId:0HLN4CPASJL8F => RequestId:0HLN4CPASJL8F:00000001 RequestPath:/helpers/log => Test.WebControllers.HelpersController.GetLog (Test)

This specific line may explain the issue:

Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'

but 'failed' seems a bit vague to me.

Last test:

I have this token:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoibXkgbmFtZSIsImh0dHA6Ly9zY2hlbWFzLnhtbHNvYXAub3JnL3dzLzIwMDUvMDUvaWRlbnRpdHkvY2xhaW1zL2VtYWlsYWRkcmVzcyI6Im5vQGVtYWlsLmNvbSIsImh0dHA6Ly9zY2hlbWFzLm1pY3Jvc29mdC5jb20vd3MvMjAwOC8wNi9pZGVudGl0eS9jbGFpbXMvZXhwaXJhdGlvbiI6IjA1LzMxLzIwMTkgMDA6MTM6MjAiLCJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9zaWQiOiI3Y2FjZjdiNS04NjY5LTQ2OWUtOTg4NS1kNDgwNGYyOGNjNGEiLCJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA5LzA5L2lkZW50aXR5L2NsYWltcy9hY3RvciI6ImQyZjZiNzI0LWE0ZjktNGJkZC1hNjQ3LTRkM2UxYTU5NjhkZSIsIm5iZiI6MTU1OTE3NTIwMCwiZXhwIjoxNTU5MjYxNjAwLCJpc3MiOiJ0ZXN0IiwiYXVkIjoidGVzdC1hcHAifQ.y42RUvMM69aDTvCydoU3mOKu2giub6OvKpd-RNVmom4

with the key:

MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjayVuqZOuKK38rhsRwrRGzVcv/7b4fHXrzpol3K5TTAPttNUaQvCKQD7BQN+V8nvkBsQcxPk5ONnxzbFb/npENC4UtwK5J6iiVrinE7sDrWZQNo9LkwbuG9x0fuuf8U3H2CnwZEfFaf2kbU1v7XosNGi+aYASupvhwoiJtK+17ZPloxSQy3Qny2tQWi7Dh/Cr5+m5JBy6HeGLq2cq+oalFYzrGGmQXndLtJpBZgrPd7nR6lJSMiRcJtcpxTJbYTEVVXoB0SR1bPmYYB/6y7klVDVedTow+1mwZrDMrbRiTBPSifCIBs3rxLQaL207blg+kj+EVLED5fZSOBlOyTOYQIDAQAB

it decodes to (as tested by jwt.io):

{
  "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name": "my name",
  "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress": "no@email.com",
  "http://schemas.microsoft.com/ws/2008/06/identity/claims/expiration": "05/31/2019 00:13:20",
  "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/sid": "7cacf7b5-8669-469e-9885-d4804f28cc4a",
  "http://schemas.xmlsoap.org/ws/2009/09/identity/claims/actor": "d2f6b724-a4f9-4bdd-a647-4d3e1a5968de",
  "nbf": 1559175200,
  "exp": 1559261600,
  "iss": "test",
  "aud": "test-app"
}

it is generated by the following code:

        var Expiration = DateTime.UtcNow + TimeSpan.FromDays(1);
        var Identity = new ClaimsIdentity(new[]
        {
            new Claim(ClaimTypes.Name,          "my name"),
            new Claim(ClaimTypes.Email,         "no@email.com"),
            new Claim(ClaimTypes.Expiration,    Expiration.ToString(CultureInfo.InvariantCulture)),
            new Claim(ClaimTypes.Sid,           Guid.NewGuid().ToString()),
            new Claim(ClaimTypes.Actor,         Guid.NewGuid().ToString()),
        });

        var Token = new JwtSecurityToken
        (
            issuer:             "test",
            audience:           "test-app",
            claims:             Identity.Claims,
            notBefore:          DateTime.UtcNow,
            expires:            Expiration,
            signingCredentials: new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_JwtRsaPublicKey)), SecurityAlgorithms.HmacSha256)
        );

        var TokenString = new JwtSecurityTokenHandler().WriteToken(Token);
        return TokenString;

In asp, I have the following code:

                    Services.AddAuthentication(A =>
                    {
                        A.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                        A.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                    })
                    .AddJwtBearer(O =>
                    {
                        O.RequireHttpsMetadata = false;
                        O.SaveToken = true;
                        O.IncludeErrorDetails = true;
                        O.TokenValidationParameters = new TokenValidationParameters
                        {
                            ValidateIssuerSigningKey = true,
                            IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(AuthJWTPublicKey)),
                            ValidateIssuer = false,
                            ValidateAudience = false
                        };
                    });

and I have a controller method with:

  [Authorize]

But I keep getting a 401, no matter what I try, I get a 401...

Even if I set ValidateIssuerSigningKey to false. I get a 401

The setup is:

In ConfigureServices, I have:

Services.AddMvc()
and the code above

In Configure, I have:

Application.UseAuthentication();
Application.UseMvc(Routes => { Routes.MapRoute("default_route", "{controller}/{action}/{id?}"); });

Body:
I am not sure what is stored in the variable but it looks like it's not a private token:

IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(AuthJWTPublicKey)),

This is as far as I know a private symmetric key, perhaps you are passing a wrong value in there?


问:
Index a Interface with a const enum and infer type in a switch statement in TypeScript
I am trying to automatically infer the type of some data passed in a switch statement based on the enum value fulfilling the case condition.

To achieve this I've defined a const enum:

```<code>const enum MESSAGES {
  open = 1,
  close,
  redo
}
</code>```

Then I use it to index a Interface:

```<code>interface MessagePayloadContent {
  [MESSAGES.open]: string;
  [MESSAGES.close]: number;
  [MESSAGES.redo]: boolean;
}
</code>```

At this point I define the object that I will evaluate in the switch statement:

```<code>interface MessagePayload<T extends MESSAGES> {
  scope: T;
  content: MessagePayloadContent[T];
}
</code>```

Finally I use the above in a switch statement.

I would expect that the interpreter can infer, based on the value being passed to each case, what type of data will be contained in the object.

On the contrary I get the errors as in the comments in the code below:

```<code>function pick(payload: MessagePayload<MESSAGES>): void {
  switch (payload.scope) {
    case MESSAGES.open:
      open(payload.content); // Argument of type 'string | number | boolean' is not assignable to parameter of type 'string'.
      break;
    case MESSAGES.close:
      close(payload.content as number); // This is my current workaround.
      break;
    case MESSAGES.redo:
      redo(payload.content); // Argument of type 'string | number | boolean' is not assignable to parameter of type 'boolean'.
      break;
  }
}

const open = (d: string) => d;
const close = (d: number) => d;
const redo = (d: MessagePayloadContent[MESSAGES.redo]) => d;
</code>```

What I don't fully get is that in some other circumstances this does work, so I wonder why some other times it does not.

答:
The problem here is that the type MessagePayload<MESSAGES> is not what you think it is.  Interfaces don't generally distribute over unions, so it just evaluates to:

```<code>interface OopsMessagePayload {
  scope: MESSAGES;
  content: string | number | boolean;
}
</code>```

Which means that if you check the scope property, it does not narrow the type of the content property.

TypeScript does have some type-level constructs that distribute over unions, so there should be a way to define

```<code>type MessagePayloadDistributive<T> = ...
</code>```

such that

```<code>MessagePayloadDistributive<MESSAGES>
</code>```

evaluates to

```<code>MessagePayload<MESSAGES.open> |
MessagePayload<MESSAGES.closed> |
MessagePayload<MESSAGES.redo>
</code>```

I will use distributive conditional types in which if you have a type like type D<T> = T extends U ? V : W where the checked type T is a bare type parameter, the conditional check will be distributed across unions:

```<code>type MessagePayloadDistributive<T extends MESSAGES> = T extends any
  ? MessagePayload<T>
  : never;

type SomeMessagePayload = MessagePayloadDistributive<MESSAGES>;
</code>```

If you inspect that, SomeMessagePayload evaluates to the desired type above.  And then the following code will work as you expect:

```<code>function pick(payload: SomeMessagePayload): void {
  switch (payload.scope) {
    case MESSAGES.open:
      open(payload.content); // okay
      break;
    case MESSAGES.close:
      close(payload.content); // okay
      break;
    case MESSAGES.redo:
      redo(payload.content); // okay
      break;
  }
}
</code>```

Okay, hope that helps.  Good luck!

Link to code

Body:
I am trying to automatically infer the type of some data passed in a switch statement based on the enum value fulfilling the case condition.

To achieve this I've defined a const enum:

const enum MESSAGES {
  open = 1,
  close,
  redo
}

Then I use it to index a Interface:

interface MessagePayloadContent {
  [MESSAGES.open]: string;
  [MESSAGES.close]: number;
  [MESSAGES.redo]: boolean;
}

At this point I define the object that I will evaluate in the switch statement:

interface MessagePayload<T extends MESSAGES> {
  scope: T;
  content: MessagePayloadContent[T];
}

Finally I use the above in a switch statement.

I would expect that the interpreter can infer, based on the value being passed to each case, what type of data will be contained in the object.

On the contrary I get the errors as in the comments in the code below:

function pick(payload: MessagePayload<MESSAGES>): void {
  switch (payload.scope) {
    case MESSAGES.open:
      open(payload.content); // Argument of type 'string | number | boolean' is not assignable to parameter of type 'string'.
      break;
    case MESSAGES.close:
      close(payload.content as number); // This is my current workaround.
      break;
    case MESSAGES.redo:
      redo(payload.content); // Argument of type 'string | number | boolean' is not assignable to parameter of type 'boolean'.
      break;
  }
}

const open = (d: string) => d;
const close = (d: number) => d;
const redo = (d: MessagePayloadContent[MESSAGES.redo]) => d;

What I don't fully get is that in some other circumstances this does work, so I wonder why some other times it does not.

Body:
The problem here is that the type MessagePayload<MESSAGES> is not what you think it is.  Interfaces don't generally distribute over unions, so it just evaluates to:

interface OopsMessagePayload {
  scope: MESSAGES;
  content: string | number | boolean;
}

Which means that if you check the scope property, it does not narrow the type of the content property.

TypeScript does have some type-level constructs that distribute over unions, so there should be a way to define

type MessagePayloadDistributive<T> = ...

such that

MessagePayloadDistributive<MESSAGES>

evaluates to

MessagePayload<MESSAGES.open> |
MessagePayload<MESSAGES.closed> |
MessagePayload<MESSAGES.redo>

I will use distributive conditional types in which if you have a type like type D<T> = T extends U ? V : W where the checked type T is a bare type parameter, the conditional check will be distributed across unions:

type MessagePayloadDistributive<T extends MESSAGES> = T extends any
  ? MessagePayload<T>
  : never;

type SomeMessagePayload = MessagePayloadDistributive<MESSAGES>;

If you inspect that, SomeMessagePayload evaluates to the desired type above.  And then the following code will work as you expect:

function pick(payload: SomeMessagePayload): void {
  switch (payload.scope) {
    case MESSAGES.open:
      open(payload.content); // okay
      break;
    case MESSAGES.close:
      close(payload.content); // okay
      break;
    case MESSAGES.redo:
      redo(payload.content); // okay
      break;
  }
}

Okay, hope that helps.  Good luck!

<a href="https://typescript-play.js.org/#code/HYQwtgpgzgDiDGEAEBhA9gE2QbwFBKXjWCgBckJgBXMJAWQFEBlJgQQHFmk8CC0ZKSALxIAjABp8veABs0UCJN5IAThAxopAXylES5foJEAKDAC4kZFQEtgAcwCUwgHxIMAbl3EyhOQuFIphbUYABGECpOQq4eXvqq6mgBQfTQUCB2EAAKIACeciAY6MCklKQA2owsHMwAdGoaALpRMZ5StqUqAGYIyHRpGdl5BUXEpSXcUgSVzGycTLWGwI0WVrZ2nsoz1fO1svIQK0gh4SqbvNtzdQ1oR6FoaDIQIMDnOlKkuQJIAEoB-VB0pkcvk0IViuMKlUrkxGm0CB0Ij1EKlAYMQSMADwAFQoAA9xhgoPRZjUmK4eLwoEQBBZsecCHpIRYAUChqDwWMyuVsXDtLgPl8+gNgcMwRgACLWNahKikawANwgOPxhOJ0LJrhEuIgBMoRKQL1yUyQAH5UWyMeKcc4TcEIEqzoLvkw0JBWeixYV-iL2SMpTK5YrlRr5s54UgulRgPB5cQkDBrPAANbGOAc8xIV3u31WwoOCwKtDWDCTZRQADu1lI8AAFoF0yNatTDE5Kcp4CB-KG6kszCblEs016MHsuSUHO4kAB6adINDJvID3ihNQgZMM6Rdvqk3b7BT95QdvwQYcZsclMqTmdzhdLo8rtcb5ed7u766JQ8PhIaM9NplXlOs7zouxrfkgq7PM+yg6AQOg6EAA" rel="nofollow noreferrer">Link to code


问:
jQuery loop over JSON result from AJAX Success?
On the jQuery AJAX success callback I want to loop over the results of the object.     This is an example of how the response looks in Firebug.

```<code>[
 {"TEST1":45,"TEST2":23,"TEST3":"DATA1"},
 {"TEST1":46,"TEST2":24,"TEST3":"DATA2"},
 {"TEST1":47,"TEST2":25,"TEST3":"DATA3"}
]
</code>```

How can I loop over the results so that I would have access to each of the elements?
I have tried something like below but this does not seem to be working.

```<code>jQuery.each(data, function(index, itemData) {
  // itemData.TEST1
  // itemData.TEST2
  // itemData.TEST3
});
</code>```

答:
I am partial to ES2015 arrow function for finding values in an array

```<code>const result = data.find(x=> x.TEST1 === '46');
</code>```

Checkout Array.prototype.find() HERE

ContentLicense: CC BY-SA 2.5

Body:
On the jQuery AJAX success callback I want to loop over the results of the object.     This is an example of how the response looks in Firebug.

[
 {"TEST1":45,"TEST2":23,"TEST3":"DATA1"},
 {"TEST1":46,"TEST2":24,"TEST3":"DATA2"},
 {"TEST1":47,"TEST2":25,"TEST3":"DATA3"}
]

How can I loop over the results so that I would have access to each of the elements?
I have tried something like below but this does not seem to be working.

jQuery.each(data, function(index, itemData) {
  // itemData.TEST1
  // itemData.TEST2
  // itemData.TEST3
});

Body:
I am partial to ES2015 arrow function for finding values in an array

const result = data.find(x=> x.TEST1 === '46');

Checkout Array.prototype.find() HERE


问:
Unicode chars and Spring JavaMailSenderImpl, no unicode chars under Linux!
I'm using Spring and JavaMailSenderImpl, a famous spring class to send emails. My emails contain a lot of unicode chars like èéàò or most notably the dreaded € symbol. My classes work fine when the run on windows. The emails sent are with all the chars (plain text, no html). If I install my app on a Linux virtual server, I'll get all ? instead of the special chars. Is it Spring, Java configuration or something else?

Update

Basically the architecture is this: there is a Spring Web Application and I use spring JavaMailSenderImpl to get the work done. This is the configuration in servlet-context:

```<code><bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
    <property name="host" value="${email.server}" />
    <property name="username" value="${email.server_user}"></property>
    <property name="password" value="${email.server_pass}"></property>
</bean>
</code>```

I'm using the same host on windows and linux to send mail (that is not the same machine where the application runs on... It is just a standard mail service provider over SMTP).

The code I use to send the email is simply:

```<code>SimpleMailMessage msg = new SimpleMailMessage();
            msg.setTo(adminEmail);
            msg.setFrom(adminEmail);
            msg.setSubject(subject);
            msg.setText(message);
            mailSender.send(msg);
</code>```

Even setting:

```<code>System.setProperty("mail.mime.charset", "utf8");
</code>```

at application startup doesn't solve the situation. In fact, before I was getting ? instead of €, now I get �...

答: The problem is likely to be when you translate between an array of bytes (e.g. reading from a file) and a java.lang.String. Can you give more detail on your application's architecture?

Body:
I'm using Spring and JavaMailSenderImpl, a famous spring class to send emails. My emails contain a lot of unicode chars like èéàò or most notably the dreaded € symbol. My classes work fine when the run on windows. The emails sent are with all the chars (plain text, no html). If I install my app on a Linux virtual server, I'll get all ? instead of the special chars. Is it Spring, Java configuration or something else?

Update

Basically the architecture is this: there is a Spring Web Application and I use spring JavaMailSenderImpl to get the work done. This is the configuration in servlet-context:

<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
    <property name="host" value="${email.server}" />
    <property name="username" value="${email.server_user}"></property>
    <property name="password" value="${email.server_pass}"></property>
</bean>

I'm using the same host on windows and linux to send mail (that is not the same machine where the application runs on... It is just a standard mail service provider over SMTP).

The code I use to send the email is simply:

SimpleMailMessage msg = new SimpleMailMessage();
            msg.setTo(adminEmail);
            msg.setFrom(adminEmail);
            msg.setSubject(subject);
            msg.setText(message);
            mailSender.send(msg);

Even setting:

System.setProperty("mail.mime.charset", "utf8");

at application startup doesn't solve the situation. In fact, before I was getting ? instead of €, now I get �...


问:
Generate a string from a dictionary keys (combinations) and assing a boolean value based on values
I have a structure similar, to a dictionary of dictionaries:

```<code>cont  = {

'perm': { 'r': False, 'rw': True}

'prig':  { 'sq': False, 'rot':False, 'rq':True}

'anon':  {'100': False, '500':True, '99':False; '400':False}

}
</code>```

From this structure I need to generate a string from keys, and know if the string is False or True based on the values:

Example:

```<code>'perm', 'prig', 'anon' will become: 'r,sq,100' or 'rw,sq,100' or 'r,rq,100'.
</code>```

I need to generate all permutations of the second level keys.

For each string, I need to associate a Boolean value using 'AND' are True or False.
For the example above:

```<code>False,False,False -> False;  True,False,False -> True,False,True, False -> False;
</code>```

答:
You can use itertools.product:

```<code>import itertools
cont = {'perm': {'r': False, 'rw': True}, 'prig': {'sq': False, 'rot': False, 'rq': True}, 'anon': {'100': False, '500': True, '99': False, '400': False}}
keys = {a:list(b) for a, b in cont.items()}
p = list(itertools.product(*_keys.values()))
result = [[cont[[a for a, b in keys.items() if c in b][0]][c] for c in i] for i in p]
new_result = [any(i) for i in result]
</code>```

Output:

```<code>#result:
[[False, False, False], [False, False, True], [False, False, False], [False, False, False], [False, False, False], [False, False, True], [False, False, False], [False, False, False], [False, True, False], [False, True, True], [False, True, False], [False, True, False], [True, False, False], [True, False, True], [True, False, False], [True, False, False], [True, False, False], [True, False, True], [True, False, False], [True, False, False], [True, True, False], [True, True, True], [True, True, False], [True, True, False]]
#new_result
[False, True, False, False, False, True, False, False, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True]
#list(map(','.join, prod))
['r,sq,100', 'r,sq,500', 'r,sq,99', 'r,sq,400', 'r,rot,100', 'r,rot,500', 'r,rot,99', 'r,rot,400', 'r,rq,100', 'r,rq,500', 'r,rq,99', 'r,rq,400', 'rw,sq,100', 'rw,sq,500', 'rw,sq,99', 'rw,sq,400', 'rw,rot,100', 'rw,rot,500', 'rw,rot,99', 'rw,rot,400', 'rw,rq,100', 'rw,rq,500', 'rw,rq,99', 'rw,rq,400']
</code>```

Body:
I have a structure similar, to a dictionary of dictionaries:

cont  = {

'perm': { 'r': False, 'rw': True}

'prig':  { 'sq': False, 'rot':False, 'rq':True}

'anon':  {'100': False, '500':True, '99':False; '400':False}

}

From this structure I need to generate a string from keys, and know if the string is False or True based on the values:

Example:

'perm', 'prig', 'anon' will become: 'r,sq,100' or 'rw,sq,100' or 'r,rq,100'.

I need to generate all permutations of the second level keys.

For each string, I need to associate a Boolean value using 'AND' are True or False.
For the example above:

False,False,False -> False;  True,False,False -> True,False,True, False -> False;

Body:
You can use itertools.product:

import itertools
cont = {'perm': {'r': False, 'rw': True}, 'prig': {'sq': False, 'rot': False, 'rq': True}, 'anon': {'100': False, '500': True, '99': False, '400': False}}
keys = {a:list(b) for a, b in cont.items()}
p = list(itertools.product(*_keys.values()))
result = [[cont[[a for a, b in keys.items() if c in b][0]][c] for c in i] for i in p]
new_result = [any(i) for i in result]

Output:

#result:
[[False, False, False], [False, False, True], [False, False, False], [False, False, False], [False, False, False], [False, False, True], [False, False, False], [False, False, False], [False, True, False], [False, True, True], [False, True, False], [False, True, False], [True, False, False], [True, False, True], [True, False, False], [True, False, False], [True, False, False], [True, False, True], [True, False, False], [True, False, False], [True, True, False], [True, True, True], [True, True, False], [True, True, False]]
#new_result
[False, True, False, False, False, True, False, False, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True]
#list(map(','.join, prod))
['r,sq,100', 'r,sq,500', 'r,sq,99', 'r,sq,400', 'r,rot,100', 'r,rot,500', 'r,rot,99', 'r,rot,400', 'r,rq,100', 'r,rq,500', 'r,rq,99', 'r,rq,400', 'rw,sq,100', 'rw,sq,500', 'rw,sq,99', 'rw,sq,400', 'rw,rot,100', 'rw,rot,500', 'rw,rot,99', 'rw,rot,400', 'rw,rq,100', 'rw,rq,500', 'rw,rq,99', 'rw,rq,400']


问:
How to randomly fill the rows of the matrix?
I have a matrix with n-rows and n-columns. I need to make sure that the numbers in each row are unique.</p>

```<code>let matrix = [];
let matrixRows = 3;
let matrixColumns = 5;

for ( let i = 0; i < matrixRows; i++ ) {
    matrix[ i ] = [];
    let j = 0;
    while (j < matrixColumns) {
        matrix[ i ][ j ] = Math.floor(Math.random() * 5) + 1;
        j++;
    }
}

console.log( matrix.join('\n') );

It should look something like this

"1,2,3,4,5 \\ here is line break (new row)
1,4,2,5,3 \\ here is line break (new row)
5,4,2,3,1"
</code>```

答:
You could create an array of numbers upto matrixColumns using Array.from(). Then shuffle the array randomly in every iteration and create rows (from this answer)

// https://stackoverflow.com/a/18806417/3082296
function shuffle(arr) {
  let i = arr.length,
    copy = [...arr], // take a copy
    output = [];

  while (i--) {
    const j = Math.floor(Math.random() * (i + 1));
    output.push(copy.splice(j, 1)[0]);
  }
  return  output
}

let matrix = [];
let matrixRows = 3;
let matrixColumns = 5;

// Natural numbers upto matrixColumns
const numbers = Array.from({ length: matrixColumns }, (_, i) => ++i)
const output = Array.from({ length: matrixRows }, _ => shuffle(numbers))

console.log(output)```

Body:
I have a matrix with n-rows and n-columns. I need to make sure that the numbers in each row are unique.

let matrix = [];
let matrixRows = 3;
let matrixColumns = 5;

for ( let i = 0; i < matrixRows; i++ ) {
    matrix[ i ] = [];
    let j = 0;
    while (j < matrixColumns) {
        matrix[ i ][ j ] = Math.floor(Math.random() * 5) + 1;
        j++;
    }
}

console.log( matrix.join('\n') );

It should look something like this

"1,2,3,4,5 \\ here is line break (new row)
1,4,2,5,3 \\ here is line break (new row)
5,4,2,3,1"


问:
fluent-ffmpeg: how split stereo mp3 to 2 mono file in node.js?
I'm trying to convert an mp3 file stereo  to  2 mp3 mono node's fluent-ffmpeg module. This is example for terminal:

```<code>ffmpeg -i stereo.wav -map_channel 0.0.0 left.wav -map_channel 0.0.1 right.wav
</code>```

I need the implementation of this functionality in fluent-ffmpeg.

答:
not sure about the mono, but if you want to split a file, you can use </p>

```<code>ffmpeg(local_dir).outputOptions('-f segment')
        .outputOptions(`-segment_time ${length of each mp3 }`).save(`${save_dir}out%03d.mp3`)
</code>```

<p>hope it can help you </p>

Body:
I'm trying to convert an mp3 file stereo  to  2 mp3 mono node's fluent-ffmpeg module. This is example for terminal:

ffmpeg -i stereo.wav -map_channel 0.0.0 left.wav -map_channel 0.0.1 right.wav

I need the implementation of this functionality in fluent-ffmpeg.

Body:
not sure about the mono, but if you want to split a file, you can use

ffmpeg(local_dir).outputOptions('-f segment')
        .outputOptions(`-segment_time ${length of each mp3 }`).save(`${save_dir}out%03d.mp3`)

hope it can help you


问:
How to place a small square box across every td element having text in css?
I am working on a table in html in which I want to place a square box across every td element in css

```<code><tr>
    <td style="width:8%; text-align:center; border: 1px solid #000; margin-left: 30px;"><?php echo $program["series_title"]; ?></td>
    <td style="width:8%; text-align:center; border: 1px solid #000; margin-left: 30px;"><?php echo $program["episode_title"]; ?></td>
    <td style="width:8%; text-align:center; border: 1px solid #000; margin-left: 30px;"><?php echo $program["description"]; ?></td>
    <td style="width:8%; text-align:center; border: 1px solid #000; margin-left: 30px;"><?php echo $program["series_title_fr"]; ?></td>
    <td style="width:8%; text-align:center; border: 1px solid #000; margin-left: 30px;"><?php echo $program["episode_title_fr"]; ?></td>
    <td style="width:8%; text-align:center; border: 1px solid #000; margin-left: 30px;"><?php echo $program["description_fr"]; ?></td>
    <td style="width:8%; text-align:center; border: 1px solid #000; margin-left: 30px;"> <?php echo basename($file, ".mp4"); ?></td>
</tr>
</code>```

The above html/php code display the table/td element in the following fashion:

Problem Statement:

I am wondering what changes I should make in the inline css code above so that I am able to make a small square box (as shown below) across every td element having text in css. At this moment, as shown above in an image it is
making a big square box

答:
You can use cellpadding and cellspacing table attributes. Please try this..</p>

```<code>  <table border="1" cellpadding="5" cellspacing="10">
  <tr>
    <td>
      <?php echo $program["series_title"]; ?>
    </td>
    <td>
      <?php echo $program["episode_title"]; ?>
    </td>
    <td>
      <?php echo $program["description"]; ?>
    </td>
    <td>
      <?php echo $program["series_title_fr"]; ?>
    </td>
    <td>
      <?php echo $program["episode_title_fr"]; ?>
    </td>
    <td>
      <?php echo $program["description_fr"]; ?>
    </td>
  </tr>
</table>
</code>```

Body:
I am working on a table in html in which I want to place a square box across every td element in css

    <?php echo $program["series_title"]; ?>
    <?php echo $program["episode_title"]; ?>
    <?php echo $program["description"]; ?>
    <?php echo $program["series_title_fr"]; ?>
    <?php echo $program["episode_title_fr"]; ?>
    <?php echo $program["description_fr"]; ?>
     <?php echo basename($file, ".mp4"); ?>

The above html/php code display the table/td element in the following fashion:

Problem Statement:

I am wondering what changes I should make in the inline css code above so that I am able to make a small square box (as shown below) across every td element having text in css. At this moment, as shown above in an image it is
making a big square box

Body:
You can use cellpadding and cellspacing table attributes. Please try this..

  <table border="1" cellpadding="5" cellspacing="10">
  <tr>
    <td>
      <?php echo $program["series_title"]; ?>
    </td>
    <td>
      <?php echo $program["episode_title"]; ?>
    </td>
    <td>
      <?php echo $program["description"]; ?>
    </td>
    <td>
      <?php echo $program["series_title_fr"]; ?>
    </td>
    <td>
      <?php echo $program["episode_title_fr"]; ?>
    </td>
    <td>
      <?php echo $program["description_fr"]; ?>
    </td>
  </tr>
</table>


问:
Loading indication with a delay and anti-flickering in RxJS
I want to implement loading indication using RxJS (version 6). A loading indicator (a spinner) would be shown in a component before asynchronous data call finishes. I have some rules to implement (whether these rules are correct might be another question, maybe leave a comment):

If the data arrives successfully earlier than in 1 second, no indicator should be shown (and data should be rendered normally)

If the call fails earlier than in 1 second, no indicator should be shown (and error message should be rendered)

If the data arrives later than in 1 second an indicator should be shown for at least 1 second (to prevent flashing spinner, the data should be rendered afterwards)

If the call fails later than in 1 second an indicator should be shown for at least 1 second

If the call takes more than 10 seconds the call should be canceled (and error message displayed)

I am implementing this in an Angular project, but I believe, that this is not Angular specific.

I have found some pieces of this puzzle, but I need help to assemble them together.

In this SO answer there is an implementation of an operator that delays the showing of a loading indicator.

A nice but incomplete implementation for Angular is described in this article.

Showing loading indicator for a minimum amount of time is described in this Medium article.

答:
Here's yet another version.  This one uses timeout to end the query at 10s.  And uses throttleTime to prevent the loader flashing.  It also only subscribes to the query once.  It produces an observable that will emit the showLoader boolean and eventually the result of the query (or an error).

// returns Observable<{showLoader: boolean, error: Error, result: T}>
function dataWithLoader(query$) {
   const timedQuery$ = query$.pipe(
       // give up on the query with an error after 10s
       timeout(10000),
       // convert results into a successful result
       map(result => ({result, showLoader: false})),
       // convert errors into an error result
       catchError(error => ({error, showLoader: false})
   );

   // return an observable that starts with {showLoader: false}
   // then emits {showLoader: true}
   // followed by {showLoader: false} when the query finishes
   // we use throttleTime() to ensure that is at least a 1s
   // gap between emissions.  So if the query finishes quickly
   // we never see the loader
   // and if the query finishes _right after_ the loader shows
   // we delay its result until the loader has been
   // up for 1 second
   return of({showLoader: false}, {showLoader: true}).pipe(
       // include the query result after the showLoader true line
       concat(timedQuery$),
       // throttle emissions so that we do not get loader appearing
       // if data arrives within 1 second
       throttleTime(1000, asyncScheduler, {leading:true, trailing: true}),
       // this hack keeps loader up at least 1 second if data arrives
       // right after loader goes up
       concatMap(x => x.showLoader ? EMPTY.pipe(delay(1000), startWith(x)) : of(x))
   );
}
```


问:
How to find or pick a suitable Chrome/Chromium revision number?
I couldn't figure out a nice way to determine a suitable revision number to use with Puppeteer Sharp.

What I did was use the version lookup feature on the "OmahaProxy - Google Chrome" site. I looked-up the version of Chrome I'm running on my computer. [That seems like a reasonable starting point.] I assumed (guessed) that the "Branch Base Position" shown in the version info was a revision number.

I then opened the Chromium continuous builds archive and looked for a build for the revision around the revision number I found from the "OmahaProxy" site.

Is there a better way to find or pick a suitable revision number?

答:
Puppeteer is always bundled with a specific revision of a specific version. I usually check the release information on Github where the expected Chromium version and revision is specified. For example:

v1.17.0

Big Changes

Chromium 76.0.3803.0 (r662092)

Then to download the right one,

Go to Chromium browser snapshots

Choose the directory of your platform (e.g., Linux_x64)

Copy the revision number into the "Filter:" field without the "r" (e.g., 662092)

Download the .zip file you need.

Additional info

The URL template below can be just plugged in with the right information:

https://commondatastorage.googleapis.com/chromium-browser-snapshots/index.html?prefix=<platform>/<revision>/

For example:
https://commondatastorage.googleapis.com/chromium-browser-snapshots/index.html?prefix=Linux_x64/662092/

The most common issue on Linux is missing dependencies, and the Puppeteer "Troubleshooting" document specifies all the Linux dependencies. (See apt instructions for Ubuntu.)

curl needs -L when downloading on the console. See Stackoverflow thread.

When one is using puppeteer-core,

you will then need to call puppeteer.connect(\[options\]) or
  puppeteer.launch(\[options\]) with an explicit executablePath
  option.

(from puppeteer vs puppeteer-core)


问:
Reading multiple columns for a row from excel, in java?
I want to read excel spreadsheet(.xlxs) having testcases preconditions column/expected result column and so on. How do i read multiple columns for specific row. Everyrow(first Column)is a testcase name.

I am able to read one row and two columns, but unsure how to read multiple columns for same row . I also don't want to hardcode column#,row# while reading it. Any suggestions?

```<code> Map<String,String> arrayExcelData = new Hashtable<String,String>();
    Iterator<Row> rowIterator = sheet.iterator();

    while (rowIterator.hasNext())
    {

      Row row = rowIterator.next();

      Cell methodNameCol = row.getCell(0);
      Cell expectedResults = row.getCell(1);

     if (expectedResults != null && methodNameCol !=null)
      {
  arrayExcelData.put(methodNameCol.getStringCellValue(),expectedResults.getStringCellValue());
        }
     workbook.close();
}
</code>```

答:
The Row class provides methods that return the index of the first and last cell (aka column) in that Row instance.  Use these indexes to iterate over the columns:</p>

```<code>Row row = rowIterator.next();
short firstCellNumber = row.getFirstCellNum();
short lastCellNumber = row.getLastCellNum();
for(short cellNumber = firstCellNumber; cellNumber < lastCellNumber; cellNumber++) {
    Cell dataCell = row.getCell(cellNumber);
    //Do something with the dataCell here
}
</code>```

Body:
I want to read excel spreadsheet(.xlxs) having testcases preconditions column/expected result column and so on. How do i read multiple columns for specific row. Everyrow(first Column)is a testcase name.

I am able to read one row and two columns, but unsure how to read multiple columns for same row . I also don't want to hardcode column#,row# while reading it. Any suggestions?

 Map<String,String> arrayExcelData = new Hashtable<String,String>();
    Iterator<Row> rowIterator = sheet.iterator();

    while (rowIterator.hasNext())
    {

      Row row = rowIterator.next();

      Cell methodNameCol = row.getCell(0);
      Cell expectedResults = row.getCell(1);

     if (expectedResults != null && methodNameCol !=null)
      {
  arrayExcelData.put(methodNameCol.getStringCellValue(),expectedResults.getStringCellValue());
        }
     workbook.close();
}

Body:
The Row class provides methods that return the index of the first and last cell (aka column) in that Row instance.  Use these indexes to iterate over the columns:

Row row = rowIterator.next();
short firstCellNumber = row.getFirstCellNum();
short lastCellNumber = row.getLastCellNum();
for(short cellNumber = firstCellNumber; cellNumber < lastCellNumber; cellNumber++) {
    Cell dataCell = row.getCell(cellNumber);
    //Do something with the dataCell here
}


问:
My intent is not matching with expected response
I'm using botkit with luis recognizer and below is the sample code:

```<code>bot.dialog('OnboardingDialog', (session) => {
   ....
....

}).triggerAction({ matches: 'OnboardingBook' })
</code>```

I have defined onboarding intent in responses as below:

OnboardingBook:{buttonTitle:'',url:'',response:'new hire can be onboarded some extra stuff',title:'Onboarding book'}

CookBook: {buttonTitle:'',url:'',response:'this is about cookbook',title:'cook'}

Ideally, if I type onboarding in my chat bot, it should return response defined in Onboarding intent. But right now its giving me other intent answer. If i type, onboarding book its giving me cook book intent.

Please help me out why few intents are matching with other than expected. Is there any logic behind this? How to resolve this problem. Please help me out.

答: When you test your LUIS app in the LUIS portal do you get the correct intent? If so then perhaps you need to save and train, the publish your LUIS app again. If you do not get the correct result in the LUIS portal then you can click inspect and edit the top scoring intent (save + train then publish to push the change live).</p>

Body:
I'm using botkit with luis recognizer and below is the sample code:

bot.dialog('OnboardingDialog', (session) => {
   ....
....

}).triggerAction({ matches: 'OnboardingBook' })

I have defined onboarding intent in responses as below:

OnboardingBook:{buttonTitle:'',url:'',response:'new hire can be onboarded some extra stuff',title:'Onboarding book'}

CookBook: {buttonTitle:'',url:'',response:'this is about cookbook',title:'cook'}

Ideally, if I type onboarding in my chat bot, it should return response defined in Onboarding intent. But right now its giving me other intent answer. If i type, onboarding book its giving me cook book intent.

Please help me out why few intents are matching with other than expected. Is there any logic behind this? How to resolve this problem. Please help me out.


问:
Zero sized arrays and array bounds checking
When compiled with either GNU Fortran (v4.4.3) or Sun Studio F95 (v8.3) and no array bounds checking the following program runs without error.  However, when array bounds checking is switched on (gfortran -fbounds-check and f95 -C, respectively) the GNU compiled executable runs again without error, whereas the Sun Studio compiled executable gives the run-time error,

```<code> ******  FORTRAN RUN-TIME SYSTEM  ******
Subscript out of range. Location:  line 44 column 20 of 'nosize.f90'
Subscript number 2 has value 1 in array 't$27'
</code>```

That's an error in the call to sub2(), which uses an automatic array dummy argument for x.  The sub1() calls run fine with either compiler and any flags.

To my knowledge this program is "legal", in that a zero sized array may be referenced like a non-zero sized array, and there is no explicit indexing of the zero length dimension of x.  But is there some zero sized array slicing or automatic array subtlety that I'm missing here?  And should I expect array bounds checking to behave the same across different compilers, or should I consider it a vendor-specific extension?

```<code>MODULE subs
  IMPLICIT NONE
CONTAINS
  SUBROUTINE sub1(x)
    IMPLICIT NONE
    REAL :: x(:,:)
    PRINT*,'------------------------------------'
    PRINT*,SHAPE(x)
    PRINT*,SIZE(x)
  END SUBROUTINE sub1

  SUBROUTINE sub2(n1,n3,x)
    IMPLICIT NONE
    INTEGER,INTENT(in) :: n1, n3
    REAL :: x(n1,n3)
    PRINT*,'------------------------------------'
    PRINT*,SHAPE(x)
    PRINT*,SIZE(x)
  END SUBROUTINE sub2
END MODULE subs

PROGRAM nosize
  USE subs
  IMPLICIT NONE
  INTEGER :: n1 = 2, n2 = 2, n3 = 0
  REAL,ALLOCATABLE :: x(:,:,:)

  ALLOCATE(x(n1,n2,n3))
  x(:,:,:) = -99.9

  PRINT*,'ALLOCATED? ',ALLOCATED(x)
  PRINT*,'SHAPE =',SHAPE(x)
  PRINT*,'SIZE  =',SIZE(x)
  PRINT*,'X     =',x

  CALL sub1(x(:,1,:))
  CALL sub2(n1,n3,x(:,1,:))

END PROGRAM nosize
</code>```

答:
It doesn't give any problems with intel's fortran compiler with -check bounds; and IBM's xlf, which in my experience is extremely strict, also didn't complain with -qcheck.

But more broadly, yes, there's no standard about what bounds checking should or shouldn't do.  I can certainly see why some compilers would flag an assignment to a zero-length array as being bad/wrong/weird; it is a strange corner-case.

Body:
When compiled with either GNU Fortran (v4.4.3) or Sun Studio F95 (v8.3) and no array bounds checking the following program runs without error.  However, when array bounds checking is switched on (gfortran -fbounds-check and f95 -C, respectively) the GNU compiled executable runs again without error, whereas the Sun Studio compiled executable gives the run-time error,

 ******  FORTRAN RUN-TIME SYSTEM  ******
Subscript out of range. Location:  line 44 column 20 of 'nosize.f90'
Subscript number 2 has value 1 in array 't$27'

That's an error in the call to sub2(), which uses an automatic array dummy argument for x.  The sub1() calls run fine with either compiler and any flags.

To my knowledge this program is "legal", in that a zero sized array may be referenced like a non-zero sized array, and there is no explicit indexing of the zero length dimension of x.  But is there some zero sized array slicing or automatic array subtlety that I'm missing here?  And should I expect array bounds checking to behave the same across different compilers, or should I consider it a vendor-specific extension?

MODULE subs
  IMPLICIT NONE
CONTAINS
  SUBROUTINE sub1(x)
    IMPLICIT NONE
    REAL :: x(:,:)
    PRINT*,'------------------------------------'
    PRINT*,SHAPE(x)
    PRINT*,SIZE(x)
  END SUBROUTINE sub1

  SUBROUTINE sub2(n1,n3,x)
    IMPLICIT NONE
    INTEGER,INTENT(in) :: n1, n3
    REAL :: x(n1,n3)
    PRINT*,'------------------------------------'
    PRINT*,SHAPE(x)
    PRINT*,SIZE(x)
  END SUBROUTINE sub2
END MODULE subs

PROGRAM nosize
  USE subs
  IMPLICIT NONE
  INTEGER :: n1 = 2, n2 = 2, n3 = 0
  REAL,ALLOCATABLE :: x(:,:,:)

  ALLOCATE(x(n1,n2,n3))
  x(:,:,:) = -99.9

  PRINT*,'ALLOCATED? ',ALLOCATED(x)
  PRINT*,'SHAPE =',SHAPE(x)
  PRINT*,'SIZE  =',SIZE(x)
  PRINT*,'X     =',x

  CALL sub1(x(:,1,:))
  CALL sub2(n1,n3,x(:,1,:))

END PROGRAM nosize


问:
how to merge data across data.frame rows based on identical column values
How would you merge values between rows that have identical values in id_3? I'm sure there's a better name for the question title but I'm struggling to find the appropriate operation/function name(s) for this procedure.

```<code>library(tidyverse)
id_1 <- c("x12", NA, "a_bc", NA)
id_2 <- c(NA, "gye", NA, "ab_c")
id_3 <- c("qwe", "ert", "abc", "abc")
param_1 <- c(0.21, 1.5, 0.23, NA)
param_12 <- c(0.05, 4.4, NA, 6.3)

df <- data.frame(id_1, id_2, id_3, param_1, param_12)
as_tibble(df)

#    id_1  id_2  id_3  param_1 param_12
#   <fct> <fct> <fct>   <dbl>    <dbl>
#  1 x12   NA    qwe      0.21     0.05
#  2 NA    gye   ert      1.5      4.4
#  3 a_bc  NA    abc      0.23     NA
#  4 NA    ab_c  abc      NA       6.3
</code>```

desired df:

```<code>#    id_1  id_2  id_3  param_1 param_12
#   <fct> <fct> <fct>   <dbl>    <dbl>
#  1 x12   NA    qwe     0.21     0.05
#  2 NA    gye   ert     1.5      4.4
#  3 a_bc  ab_c  abc     0.23     6.3
</code>```

update - with additional column formats such as character:

```<code>id_1 <- c("x12", NA, "a_bc", NA)
id_2 <- c(NA, "gye", NA, "ab_c")
id_3 <- c("qwe", "ert", "abc", "abc")
param_1 <- c(0.21, 1.5, 0.23, NA)
param_12 <- c(0.05, 4.4, NA, 6.3)
desc_1 <- c("st", NA, "ko", NA)
desc_2 <- c(NA, "lo", NA, "vf")

df <- data.frame(id_1, id_2, id_3, param_1, param_12, desc_1, desc_2)
df <- df %>% mutate(desc_1 = as.character(desc_1),
                    desc_2 = as.character(desc_2))

 # A tibble: 4 x 7
 #  id_1  id_2  id_3  param_1 param_12 desc_1 desc_2
 #  <fct> <fct> <fct>   <dbl>    <dbl> <chr>  <chr>
 #1 x12   NA    qwe      0.21     0.05 st     NA
 #2 NA    gye   ert      1.5      4.4  NA     lo
 #3 a_bc  NA    abc      0.23    NA    ko     NA
 #4 NA    ab_c  abc     NA        6.3  NA     vf

df <- df %>% group_by(id_3) %>%
      summarise_all(list(~ if(all(is.na(.))) NA else .[!is.na(.)]

`Error: Column `desc_1` can't promote group 1 to character`
</code>```

答:
We can group by 'id_3' and summarise all the columns to return NA if all the values in that particular column is NA for a group or else remove the NA and return the first non-NA element

```<code>library(tidyverse)
df %>%
   group_by(id_3) %>%
   summarise_all(list(~ if(all(is.na(.))) NA else .[!is.na(.)][1]))
# A tibble: 3 x 5
#  id_3  id_1  id_2  param_1 param_12
#  <fct> <fct> <fct>   <dbl>    <dbl>
#1 abc   a_bc  ab_c     0.23     6.3
#2 ert   <NA>  gye      1.5      4.4
#3 qwe   x12   <NA>     0.21     0.05
</code>```

-Rstudio

Update

For the second dataset, after the columns were converted to character class, OP encountered error with if(all(is.na(.))) NAl.  If the columns are of same type, we can specify NA_character, NA_real_, NA_integer_ to dispatch the correct NA for each type.  Here, we cannot do that, but there is one hacky option to return the 1st NA element in that column which will also have the correct type

```<code>df %>%
   group_by(id_3) %>%
   summarise_all(list(~ if(all(is.na(.))) .[!is.na(.)][1]
           else .[!is.na(.)]))
# A tibble: 3 x 7
#  id_3  id_1  id_2  param_1 param_12 desc_1 desc_2
#  <fct> <fct> <fct>   <dbl>    <dbl> <chr>  <chr>
#1 abc   a_bc  ab_c     0.23     6.3  ko     vf
#2 ert   <NA>  gye      1.5      4.4  <NA>   lo
#3 qwe   x12   <NA>     0.21     0.05 st     <NA>
</code>```

Body:
How would you merge values between rows that have identical values in id_3? I'm sure there's a better name for the question title but I'm struggling to find the appropriate operation/function name(s) for this procedure.

library(tidyverse)
id_1 <- c("x12", NA, "a_bc", NA)
id_2 <- c(NA, "gye", NA, "ab_c")
id_3 <- c("qwe", "ert", "abc", "abc")
param_1 <- c(0.21, 1.5, 0.23, NA)
param_12 <- c(0.05, 4.4, NA, 6.3)

df <- data.frame(id_1, id_2, id_3, param_1, param_12)
as_tibble(df)

#    id_1  id_2  id_3  param_1 param_12
#   <fct> <fct> <fct>   <dbl>    <dbl>
#  1 x12   NA    qwe      0.21     0.05
#  2 NA    gye   ert      1.5      4.4
#  3 a_bc  NA    abc      0.23     NA
#  4 NA    ab_c  abc      NA       6.3

desired df:

#    id_1  id_2  id_3  param_1 param_12
#   <fct> <fct> <fct>   <dbl>    <dbl>
#  1 x12   NA    qwe     0.21     0.05
#  2 NA    gye   ert     1.5      4.4
#  3 a_bc  ab_c  abc     0.23     6.3

update - with additional column formats such as character:

id_1 <- c("x12", NA, "a_bc", NA)
id_2 <- c(NA, "gye", NA, "ab_c")
id_3 <- c("qwe", "ert", "abc", "abc")
param_1 <- c(0.21, 1.5, 0.23, NA)
param_12 <- c(0.05, 4.4, NA, 6.3)
desc_1 <- c("st", NA, "ko", NA)
desc_2 <- c(NA, "lo", NA, "vf")

df <- data.frame(id_1, id_2, id_3, param_1, param_12, desc_1, desc_2)
df <- df %>% mutate(desc_1 = as.character(desc_1),
                    desc_2 = as.character(desc_2))

 # A tibble: 4 x 7
 #  id_1  id_2  id_3  param_1 param_12 desc_1 desc_2
 #  <fct> <fct> <fct>   <dbl>    <dbl> <chr>  <chr>
 #1 x12   NA    qwe      0.21     0.05 st     NA
 #2 NA    gye   ert      1.5      4.4  NA     lo
 #3 a_bc  NA    abc      0.23    NA    ko     NA
 #4 NA    ab_c  abc     NA        6.3  NA     vf

df <- df %>% group_by(id_3) %>%
      summarise_all(list(~ if(all(is.na(.))) NA else .[!is.na(.)]

`Error: Column `desc_1` can't promote group 1 to character`

Body:
We can group by 'id_3' and summarise all the columns to return NA if all the values in that particular column is NA for a group or else remove the NA and return the first non-NA element

library(tidyverse)
df %>%
   group_by(id_3) %>%
   summarise_all(list(~ if(all(is.na(.))) NA else .[!is.na(.)][1]))
# A tibble: 3 x 5
#  id_3  id_1  id_2  param_1 param_12
#  <fct> <fct> <fct>   <dbl>    <dbl>
#1 abc   a_bc  ab_c     0.23     6.3
#2 ert   <NA>  gye      1.5      4.4
#3 qwe   x12   <NA>     0.21     0.05

-Rstudio

Update

For the second dataset, after the columns were converted to character class, OP encountered error with if(all(is.na(.))) NAl.  If the columns are of same type, we can specify NA_character, NA_real_, NA_integer_ to dispatch the correct NA for each type.  Here, we cannot do that, but there is one hacky option to return the 1st NA element in that column which will also have the correct type

df %>%
   group_by(id_3) %>%
   summarise_all(list(~ if(all(is.na(.))) .[!is.na(.)][1]
           else .[!is.na(.)]))
# A tibble: 3 x 7
#  id_3  id_1  id_2  param_1 param_12 desc_1 desc_2
#  <fct> <fct> <fct>   <dbl>    <dbl> <chr>  <chr>
#1 abc   a_bc  ab_c     0.23     6.3  ko     vf
#2 ert   <NA>  gye      1.5      4.4  <NA>   lo
#3 qwe   x12   <NA>     0.21     0.05 st     <NA>


问:
How to set value for all the objects in array for javascript?
How to set value for all the items inside an array?

For example, I have the array: ["chin","eng","maths"]

I want to set it to {"chin" :true,"eng":true,"maths":true}

And push to firebase as a child.

答:
One possible approach is to use Array.reduce() like this:

const input = ["chin", "eng", "maths"];

let obj = input.reduce((acc, item) => (acc[item] = true, acc), {});

console.log(obj);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}</code>```

Or, you can go with spreading, but with a little overhead on performance:

```<code>let obj = input.reduce((acc, item) => ({...acc, [item]: true}), {});
</code>```

Body:
One possible approach is to use Array.reduce() like this:

const input = ["chin", "eng", "maths"];

let obj = input.reduce((acc, item) => (acc[item] = true, acc), {});

console.log(obj);

.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

Or, you can go with spreading, but with a little overhead on performance:

let obj = input.reduce((acc, item) => ({...acc, [item]: true}), {});


问:
How can I remove all white space in a string and store the data in between?
I am a new programmer (< 1 year) so please forgive if I am making a simple thing complicated.

I'm trying to remove all the white space (the tab and space characters) in a given string and store the data as individual elements in a vector as I go. I also want to account for leading and trailing white space.

I've tried using string methods to move two indexes forward in the string while checking along the way for these characters. I've rewritten the code at least five times so far and I always end up with:

```<code>terminate called after throwing an instance of 'std::out_of_range'
  what():  basic_string::at: __n (which is 7754) >= this->size() (which is 42)
Aborted (core dumped)
</code>```

#include <iostream>
#include <string>
#include <vector>

using namespace std;

void  makeTokens(string& separate);

int main()
{
    string test = "  u       65.45\t\t   36.12\t     78.25  0.00";

    makeTokens(test);

    return 0;
}

void  makeTokens(string& separate)
{
    vector<string> tokens;
    unsigned short index1, index2 = 0;

    while (separate.at(index1) == ' ' || separate.at(index1) == '\t')
    {
        index1++;
        index2 = index1 + 1;
    }

    while (index2 < separate.length())
    {
        if (separate.at(index2) == ' ' || separate.at(index2) == '\t')
        {
            tokens.push_back(separate.substr(index1, index2 - index1));

            index1 = index2;

            while (separate.at(index1) == ' ' || separate.at(index1) == '\t')
            {
                index1++;
            }

            index2 = index1 + 1;
        }
        else
        {
            index2++;
        }

        if (index2 == separate.length() - 1)
        {
            if (separate.at(index2) == ' ' || separate.at(index2) == '\t')
            {
                tokens.push_back(separate.substr(index1));
            }
        }
    }

    for (unsigned short i = 0; i < tokens.size(); i++)
    {
        cout << tokens[i] << "|" << endl;
    }
}
```

<p>I want the console to output:</p>

```u|
65.45|
36.12|
78.25|
0.00|
```

<p>If a similar test string were passed, except with white space on the end, I still want the same output.</p>

<p>EDIT:
I have changed my index declarations to:</p>

```unsigned short index1 = 0;
unsigned short index2 = 0;
```

<p>Now the console outputs:</p>

```u|
65.45|
36.12|
78.25|
```

The final 0.00 is still missing.

答:
This is easily done by using std::istringstream:

```<code>#include <string>
#include <sstream>
#include <iostream>
#include <vector>

int main()
{
  std::string test = "  u       65.45\t\t   36.12\t     78.25  0.00";
  std::istringstream strm(test);
  std::string word;
  std::vector<std::string> words;
  while (strm >> word)
      words.push_back(word);
  for (auto& v : words)
    std::cout << v << "|\n";
}
</code>```

Output:

```<code>u|
65.45|
36.12|
78.25|
0.00|
</code>```

Live Example

Body:
I am a new programmer (< 1 year) so please forgive if I am making a simple thing complicated.

I'm trying to remove all the white space (the tab and space characters) in a given string and store the data as individual elements in a vector as I go. I also want to account for leading and trailing white space.

I've tried using string methods to move two indexes forward in the string while checking along the way for these characters. I've rewritten the code at least five times so far and I always end up with:

terminate called after throwing an instance of 'std::out_of_range'
  what():  basic_string::at: __n (which is 7754) >= this->size() (which is 42)
Aborted (core dumped)

#include <iostream>
#include <string>
#include <vector>

using namespace std;

void  makeTokens(string& separate);

int main()
{
    string test = "  u       65.45\t\t   36.12\t     78.25  0.00";

    makeTokens(test);

    return 0;
}

void  makeTokens(string& separate)
{
    vector<string> tokens;
    unsigned short index1, index2 = 0;

    while (separate.at(index1) == ' ' || separate.at(index1) == '\t')
    {
        index1++;
        index2 = index1 + 1;
    }

    while (index2 < separate.length())
    {
        if (separate.at(index2) == ' ' || separate.at(index2) == '\t')
        {
            tokens.push_back(separate.substr(index1, index2 - index1));

            index1 = index2;

            while (separate.at(index1) == ' ' || separate.at(index1) == '\t')
            {
                index1++;
            }

            index2 = index1 + 1;
        }
        else
        {
            index2++;
        }

        if (index2 == separate.length() - 1)
        {
            if (separate.at(index2) == ' ' || separate.at(index2) == '\t')
            {
                tokens.push_back(separate.substr(index1));
            }
        }
    }

    for (unsigned short i = 0; i < tokens.size(); i++)
    {
        cout << tokens[i] << "|" << endl;
    }
}

I want the console to output:

u|
65.45|
36.12|
78.25|
0.00|

If a similar test string were passed, except with white space on the end, I still want the same output.

EDIT:
I have changed my index declarations to:

unsigned short index1 = 0;
unsigned short index2 = 0;

Now the console outputs:

u|
65.45|
36.12|
78.25|

The final 0.00 is still missing.

Body:
This is easily done by using std::istringstream:

#include <string>
#include <sstream>
#include <iostream>
#include <vector>

int main()
{
  std::string test = "  u       65.45\t\t   36.12\t     78.25  0.00";
  std::istringstream strm(test);
  std::string word;
  std::vector<std::string> words;
  while (strm >> word)
      words.push_back(word);
  for (auto& v : words)
    std::cout << v << "|\n";
}

Output:

u|
65.45|
36.12|
78.25|
0.00|

Live Example


问:
Is it possible to not show Google play games logo when logging into Google play games
I implemented Google login by using GoogleSignInClient class and added request scope Games.SCOPE_GAMES.
Because of using the leader board, achievement.

But I don't want to show Google play games logo like that attachment image when Google Play login. Is it possible?

```<code>GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestServerAuthCode(client_id)
                .requestScopes(Games.SCOPE_GAMES)
                .build();

mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
</code>```

答: According to the terms and conditions you can not do any modification or remove the Logo</p>

Body:
I implemented Google login by using GoogleSignInClient class and added request scope Games.SCOPE_GAMES.
Because of using the leader board, achievement.

But I don't want to show Google play games logo like that attachment image when Google Play login. Is it possible?

GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestServerAuthCode(client_id)
                .requestScopes(Games.SCOPE_GAMES)
                .build();

mGoogleSignInClient = GoogleSignIn.getClient(this, gso);


问:
Java Mockito is hitting real method rather than using mocked method
My mockito method is hitting the real method rather than invoking the mocked method. Your inputs will be helpful

Java code.

```<code>public class CheckUser {
    private final UserDao userDao;

    public CheckUser (final String domain){
        userDao = new UserDao(domain);
    }

    public IUser getExistingUser(){
            if (userDao == null) {
                throw new RuntimeException("userDao is null");
            }
            IUser existingUser = userDao.getExistingUser();
            if (existingUser == null) {
                throw new RuntimeException("ExistingUser is null");
            }
            return existingUser;
    }
}
</code>```

This is my JUnit test code.

```<code>    @Test
    public void testExistingUser() {
        UserDao mockUserDao = mock(UserDao.class);
        when(mockUserDao.getExistingUser()).thenReturn(getExistingTestUser());
    }

    private UserDao getExistingTestUser(() {
        return ExistingUserImpl.Builder(). //withfield methods. build();
    }
</code>```

I  am creating this mock object for only testing purpose. This just return the mocked MockedExistingUserImpl  object which is implemented by IUser.

```<code>public class MockedExistingUserImpl implements IUser {
    //fields
    //overriding getter methods for all fields
    //Builder for  ExistingUserImpl
}
</code>```

When ever I call userDao.getExistingUser() in my code, I am expecting to return the mocked Existing user object but it is hitting the real method and failing the test due to domain connection. We don't establish a domain connection to run Junits. Any inputs are appreciated. Thank you !

答:
The answer is to read a tutorial about Mockito and follow that. You make the typical mistake: you create a mock object, but then you don't do anything so that your production code uses that mocked object.

Just doing a mock(YourClass) doesn't magically change that new() in your production code to return a mocked instance.

You need to inject that mocked instance into the code under test. For example by using the @InjectMock annotation.

For a good intro, see https://www.baeldung.com/Mockito-annotations for example.

And note: as written right now, you will have a hard time to use Mockito for your tests. Due to the direct call to new(), you would need PowerMock(ito) to test it. So: learn how to use Mockito, and then rework your production code to be easily testable. (turning to PowerMock would be the wrong strategy).

Body:
My mockito method is hitting the real method rather than invoking the mocked method. Your inputs will be helpful

Java code.

public class CheckUser {
    private final UserDao userDao;

    public CheckUser (final String domain){
        userDao = new UserDao(domain);
    }

    public IUser getExistingUser(){
            if (userDao == null) {
                throw new RuntimeException("userDao is null");
            }
            IUser existingUser = userDao.getExistingUser();
            if (existingUser == null) {
                throw new RuntimeException("ExistingUser is null");
            }
            return existingUser;
    }
}

This is my JUnit test code.

    @Test
    public void testExistingUser() {
        UserDao mockUserDao = mock(UserDao.class);
        when(mockUserDao.getExistingUser()).thenReturn(getExistingTestUser());
    }

    private UserDao getExistingTestUser(() {
        return ExistingUserImpl.Builder(). //withfield methods. build();
    }

I  am creating this mock object for only testing purpose. This just return the mocked MockedExistingUserImpl  object which is implemented by IUser.

public class MockedExistingUserImpl implements IUser {
    //fields
    //overriding getter methods for all fields
    //Builder for  ExistingUserImpl
}

When ever I call userDao.getExistingUser() in my code, I am expecting to return the mocked Existing user object but it is hitting the real method and failing the test due to domain connection. We don't establish a domain connection to run Junits. Any inputs are appreciated. Thank you !


问:
Failing to tune decision tree classifier parameters using gridsearch
I am trying to tune parameters using GridSearchCV but keep encountering this error message

```<code>ValueError: Invalid parameter decisiontreeclassifier for estimator DecisionTreeClassifier(class_weight=None, criterion='gini', max_depth=None,
            max_features=None, max_leaf_nodes=None,
            min_impurity_decrease=0.0, min_impurity_split=None,
            min_samples_leaf=1, min_samples_split=2,
            min_weight_fraction_leaf=0.0, presort=False, random_state=None,
            splitter='best'). Check the list of available parameters with `estimator.get_params().keys()`.
</code>```

This is the code I have written

```<code>accuracy_score = make_scorer(accuracy_score,greater_is_better = True)
dtc = DecisionTreeClassifier()
depth = np.arange(1,30)
leaves = [1,2,4,5,10,20,30,40,80,100]
param_grid =[{'decisiontreeclassifier__max_depth':depth,
             'decisiontreeclassifier__min_samples_leaf':leaves}]
grid_search = GridSearchCV(estimator = dtc,param_grid = param_grid,
                           scoring=accuracy_score,cv=10)
grid_search = grid_search.fit(X_train,y_train)
</code>```

答:
Use max_depth instead of decisiontreeclassifier__max_depth in your param_grid. (The same thing applies to the other parameter.) The notation that you're using is for pipelines with multiple estimators chained together.

```<code>accuracy_score = make_scorer(accuracy_score,greater_is_better = True)
dtc = DecisionTreeClassifier()
depth = np.arange(1,30)
leaves = [1,2,4,5,10,20,30,40,80,100]
param_grid =[{'max_depth':depth,
             'min_samples_leaf':leaves}]
grid_search = GridSearchCV(estimator = dtc,param_grid = param_grid,
                           scoring=accuracy_score,cv=10)
grid_search = grid_search.fit(X_train,y_train)
</code>```

Body:
I am trying to tune parameters using GridSearchCV but keep encountering this error message

ValueError: Invalid parameter decisiontreeclassifier for estimator DecisionTreeClassifier(class_weight=None, criterion='gini', max_depth=None,
            max_features=None, max_leaf_nodes=None,
            min_impurity_decrease=0.0, min_impurity_split=None,
            min_samples_leaf=1, min_samples_split=2,
            min_weight_fraction_leaf=0.0, presort=False, random_state=None,
            splitter='best'). Check the list of available parameters with `estimator.get_params().keys()`.

This is the code I have written

accuracy_score = make_scorer(accuracy_score,greater_is_better = True)
dtc = DecisionTreeClassifier()
depth = np.arange(1,30)
leaves = [1,2,4,5,10,20,30,40,80,100]
param_grid =[{'decisiontreeclassifier__max_depth':depth,
             'decisiontreeclassifier__min_samples_leaf':leaves}]
grid_search = GridSearchCV(estimator = dtc,param_grid = param_grid,
                           scoring=accuracy_score,cv=10)
grid_search = grid_search.fit(X_train,y_train)

Body:
Use max_depth instead of decisiontreeclassifier__max_depth in your param_grid. (The same thing applies to the other parameter.) The notation that you're using is for pipelines with multiple estimators chained together.

accuracy_score = make_scorer(accuracy_score,greater_is_better = True)
dtc = DecisionTreeClassifier()
depth = np.arange(1,30)
leaves = [1,2,4,5,10,20,30,40,80,100]
param_grid =[{'max_depth':depth,
             'min_samples_leaf':leaves}]
grid_search = GridSearchCV(estimator = dtc,param_grid = param_grid,
                           scoring=accuracy_score,cv=10)
grid_search = grid_search.fit(X_train,y_train)


问:
Locating the index value of an element in a list inside a dictionary
I need to access certain values of an array inside a dictionary using its value and not its index

For example:

```<code>message_dict = {
  '123456,896':
      [[3453, 57634], [9984, 97585]],
  '157384,899':
      [[3455, 57647], [9989, 97592]]
}
</code>```

If I want to access 57634, I could do:

```<code>s = '123456,896'
message_dict[s][0][1]
</code>```

I want to use the value of [0] instead to find 57634

I tried to specify the value directly, but syntax is invalid.

```<code>s = '123456,896'
i = 3453
message_dict[s]i[1]
</code>```

This reports syntax error, but I have no idea how to specify the value, instead of the position of the value in the array.

答:
Here a solution:

```<code>next((x[1] for x in message_dict[s] if x[0] == i), None)
</code>```

Gives None if it does not find a value.

Body:
I need to access certain values of an array inside a dictionary using its value and not its index

For example:

message_dict = {
  '123456,896':
      [[3453, 57634], [9984, 97585]],
  '157384,899':
      [[3455, 57647], [9989, 97592]]
}

If I want to access 57634, I could do:

s = '123456,896'
message_dict[s][0][1]

I want to use the value of [0] instead to find 57634

I tried to specify the value directly, but syntax is invalid.

s = '123456,896'
i = 3453
message_dict[s]i[1]

This reports syntax error, but I have no idea how to specify the value, instead of the position of the value in the array.

Body:
Here a solution:

next((x[1] for x in message_dict[s] if x[0] == i), None)

Gives None if it does not find a value.