来源: stackexchange

问:
C/C++: goto into the for loop
I have a bit unusual situation - I want to use goto statement to jump into the loop, not to jump out from it.

There are strong reasons to do so - this code must be part of some function which makes some calculations after the first call, returns with request for new data and needs one more call to continue. Function pointers (obvious solution) can't be used because we need interoperability with code which does not support function pointers.

I want to know whether code below is safe, i.e. it will be correctly compiled by all standard-compliant C/C++ compilers (we need both C and C++).

```<code>function foo(int not_a_first_call, int *data_to_request, ...other parameters... )
{
    if( not_a_first_call )
        goto request_handler;
    for(i=0; i<n; i++)
    {
        *data_to_request = i;
        return;
request_handler:
        ...process data...
    }
}
</code>```

I've studied standards, but there isn't much information about such use case. I also wonder whether replacing for by equivalent while will be beneficial from the portability point of view.

Thanks in advance.

UPD: Thanks to all who've commented!

to all commenters :) yes, I understand that I can't jump over initializers of local variables and that I have to save/restore i on each call.

about strong reasons :) This code must implement reverse communication interface. Reverse communication is a coding pattern which tries to avoid using function pointers. Sometimes it have to be used because of legacy code which expects that you will use it.

Unfortunately, r-comm-interface can't be implemented in a nice way. You can't use function pointers and you can't easily split work into several functions.

答:
It seems to me that you didn't declare i. From the point of declaration completely depends whether or not this is legal what you are doing, but see below for the initialization

In C you may declare it before the loop or as loop variable. But if it is declared as loop variable its value will not be initialized when you use it, so this is undefined behavior. And if you declare it before the for the assignment of 0 to it will not be performed.

In C++ you can't jump across the constructor of the variable, so you must declare it before the goto.

In both languages you have a more important problem, this is if the value of i is well defined, and if it is initialized if that value makes sense.

Really if there is any way to avoid this, don't do it. Or if this is really, really, performance critical check the assembler if it really does what you want.

ContentLicense: CC BY-SA 3.0

Title: C/C++: goto into the for loop

Body:
I have a bit unusual situation - I want to use goto statement to jump into the loop, not to jump out from it.

There are strong reasons to do so - this code must be part of some function which makes some calculations after the first call, returns with request for new data and needs one more call to continue. Function pointers (obvious solution) can't be used because we need interoperability with code which does not support function pointers.

I want to know whether code below is safe, i.e. it will be correctly compiled by all standard-compliant C/C++ compilers (we need both C and C++).

function foo(int not_a_first_call, int *data_to_request, ...other parameters... )
{
    if( not_a_first_call )
        goto request_handler;
    for(i=0; i<n; i++)
    {
        *data_to_request = i;
        return;
request_handler:
        ...process data...
    }
}

I've studied standards, but there isn't much information about such use case. I also wonder whether replacing for by equivalent while will be beneficial from the portability point of view.

Thanks in advance.

UPD: Thanks to all who've commented!

to all commenters :) yes, I understand that I can't jump over initializers of local variables and that I have to save/restore i on each call.

about strong reasons :) This code must implement reverse communication interface. Reverse communication is a coding pattern which tries to avoid using function pointers. Sometimes it have to be used because of legacy code which expects that you will use it.

Unfortunately, r-comm-interface can't be implemented in a nice way. You can't use function pointers and you can't easily split work into several functions.


问:
How to pass array value to the function of javascript? PHP Laravel
I have an array in the javascript named as country_id[] and selected_country[]. When the user select the country in country array, it will save inside the country_id[] array and when the user select the country inside the selected country, it will save inside the selected_country[] . Then, I want to pass the value of country_id[] and selected_country[] to the function at script function. This is to move the data from right to left and left to right. The picture is attached here.

But it says that, error below.

ERROR :

```<code>179:575 Uncaught ReferenceError: country_id is not defined
</code>```

Form :

```<code><form method="POST" action="{{route('admin-insurance-region-duplicateRegion')}}" onsubmit="return false;">
            @csrf
        <input name="id" value="{{$region->id}}" type="hidden" class="form-control" required>
        <div class="row">
            <div class="col-md-6">
                <div class="form-group">
                    <label>Choose Country</label>
                    <select class="form-control" name="country_id[]" multiple  size="10" style="height: 100%;">
                        @foreach ($countries as $item)
                        <option  value="{{$item->id}}" selected>{{$item->name}}</option>
                        @endforeach
                    </select>
                </div>
            </div>
            <div class="col-md-6">
                <div class="form-group">
                    <label>Selected Country</label>
                    <select class="form-control" name="selected_country[]" multiple  size="10" style="height: 100%;">
                        @foreach ($country_region as $item)
                            <option  value="{{$item->id}}" selected>{{$item->name}}</option>
                        @endforeach
                    </select>
                </div>
            </div>
            <button onclick="moveRight()">Move option to the right</button>
            <button onclick="moveLeft()">Move option to the Left</button>
        </div>
</code>```

JAVASCRIPT :

```<code><script>

        function moveRight() {

            var selItem = document.forms[0].country_id.selectedIndex;
            if (selItem == -1) {
                window.alert("You must first select an item on the left side.")
            } else {
                document.forms[0].selected_country.add(document.forms[0].country_id[selItem], null);
            }
        }

        function moveLeft() {
            var selItem = document.forms[0].selected_country.selectedIndex;
            if (selItem == -1) {
                window.alert("You must first select an item on the left side.")
            } else {
                document.forms[0].country_id.add(document.forms[0].selected_country[selItem], null);
            }
        }

</script>
</code>```

答:
Add Id attribute within 'country' and 'selected country' select box.

like.

```<code><select class="form-control" id="country_id" name="country_id[]" multiple  size="10">
  -----
</select>

<select class="form-control" id="selected_country" name="selected_country[]" multiple  size="10">
 -----
</select>
</code>```

DEMO.

<form method="POST" action="{{route('admin-insurance-region-duplicateRegion')}}" onsubmit="return false;">
 Choose Country
 <select class="form-control" id="country_id" name="country_id[]" multiple  size="10">
  <option  value="1" selected>1</option>
  <option  value="2" selected>2</option>
  <option  value="3" selected>3</option>
 </select>
 Selected Country
 <select class="form-control" id="selected_country" name="selected_country[]" multiple  size="10">
  <option  value="s1" selected>s1</option>
  <option  value="s2" selected>s2</option>
  <option  value="s3" selected>s3</option>
 </select>

 <button onclick="moveRight()">Move option to the right</button>
 <button onclick="moveLeft()">Move option to the Left</button>

```

ContentLicense: CC BY-SA 4.0

Body:
I have an array in the javascript named as country_id[] and selected_country[]. When the user select the country in country array, it will save inside the country_id[] array and when the user select the country inside the selected country, it will save inside the selected_country[] . Then, I want to pass the value of country_id[] and selected_country[] to the function at script function. This is to move the data from right to left and left to right. The picture is attached here.

But it says that, error below.

ERROR :

179:575 Uncaught ReferenceError: country_id is not defined

Form :

<form method="POST" action="{{route('admin-insurance-region-duplicateRegion')}}" onsubmit="return false;">
            @csrf
        <input name="id" value="{{$region->id}}" type="hidden" class="form-control" required>

                    Choose Country
                    <select class="form-control" name="country_id[]" multiple  size="10" style="height: 100%;">
                        @foreach ($countries as $item)
                        <option  value="{{$item->id}}" selected>{{$item->name}}</option>
                        @endforeach
                    </select>

                    Selected Country
                    <select class="form-control" name="selected_country[]" multiple  size="10" style="height: 100%;">
                        @foreach ($country_region as $item)
                            <option  value="{{$item->id}}" selected>{{$item->name}}</option>
                        @endforeach
                    </select>

            <button onclick="moveRight()">Move option to the right</button>
            <button onclick="moveLeft()">Move option to the Left</button>

JAVASCRIPT :

Body:
Add Id attribute within 'country' and 'selected country' select box.

like.

<select class="form-control" id="country_id" name="country_id[]" multiple  size="10">
  -----
</select>

<select class="form-control" id="selected_country" name="selected_country[]" multiple  size="10">
 -----
</select>

DEMO.

<form method="POST" action="{{route('admin-insurance-region-duplicateRegion')}}" onsubmit="return false;">
 <label>Choose Country</label>
 <select class="form-control" id="country_id" name="country_id[]" multiple  size="10">
  <option  value="1" selected>1</option>
  <option  value="2" selected>2</option>
  <option  value="3" selected>3</option>
 </select>
 <label>Selected Country</label>
 <select class="form-control" id="selected_country" name="selected_country[]" multiple  size="10">
  <option  value="s1" selected>s1</option>
  <option  value="s2" selected>s2</option>
  <option  value="s3" selected>s3</option>
 </select>
 </div>
 </div>
 <button onclick="moveRight()">Move option to the right</button>
 <button onclick="moveLeft()">Move option to the Left</button>
</div>

<script>
function moveRight() {

var selItem = document.forms[0].country_id.selectedIndex;
 if (selItem == -1) {
 window.alert("You must first select an item on the left side.")
 } else {
 document.forms[0].selected_country.add(document.forms[0].country_id[selItem], null);
 }
}

function moveLeft() {
 var selItem = document.forms[0].selected_country.selectedIndex;
 if (selItem == -1) {
 window.alert("You must first select an item on the left side.")
 } else {
 document.forms[0].country_id.add(document.forms[0].selected_country[selItem], null);
 }
}

</script>


问:
Update Azure keyvault secret through Azure API
I am trying to update keyvault secret in Azure through Postman. But getting Authorization error.
Any suggestions. Anything I am missing. Thanks in advance

```<code>{
  "error": {
    "code": "Unauthorized",
    "message": "AKV10022: Invalid audience. Expected https://vault.azure.net, found: https://management.azure.com/."
  }
}
</code>```

Using the below to update the secret:

```<code>PUT https://demokv.vault.azure.net/secrets/secretname?api-version=7.0
</code>```

in Body:

```<code>{
  "value": "mysecretvalue"
}
</code>```

答:
As mentioned in another  reply, the audience of your token is not correct, to call Azure Keyvault REST API - Set Secret - Set Secret, the audience should be https://vault.azure.net.

To get the token, you could use the client credential flow in the postman.

1.Register an AD App in azure ad, then get values for signing in and create a new application secret.

2.Navigate to the keyvault in the portal, add the service principal of the AD App to the Access policies.

In the postman, follow the screenshot below, fix the properties that got from step 1.

```<code>POST https://login.microsoftonline.com/<tenant-id>/oauth2/v2.0/token

client_id=<client_id>
&scope=https://vault.azure.net/.default
&client_secret=<client_secret>
&grant_type=client_credentials
</code>```

Then copy the token to call the REST API to set secret, it will work fine.

Body:
I am trying to update keyvault secret in Azure through Postman. But getting Authorization error.
Any suggestions. Anything I am missing. Thanks in advance

{
  "error": {
    "code": "Unauthorized",
    "message": "AKV10022: Invalid audience. Expected https://vault.azure.net, found: https://management.azure.com/."
  }
}

Using the below to update the secret:

PUT https://demokv.vault.azure.net/secrets/secretname?api-version=7.0

in Body:

{
  "value": "mysecretvalue"
}

Body:
As mentioned in another  reply, the audience of your token is not correct, to call Azure Keyvault REST API - Set Secret - Set Secret, the audience should be https://vault.azure.net.

To get the token, you could use the client credential flow in the postman.

1.Register an AD App in azure ad, then get values for signing in and create a new application secret.

2.Navigate to the keyvault in the portal, add the service principal of the AD App to the Access policies.

In the postman, follow the screenshot below, fix the properties that got from step 1.

POST https://login.microsoftonline.com/<tenant-id>/oauth2/v2.0/token

client_id=<client_id>
&scope=https://vault.azure.net/.default
&client_secret=<client_secret>
&grant_type=client_credentials

Then copy the token to call the REST API to set secret, it will work fine.


问:
Spring-boot application not authenticating when using OAuth2 (updated #2)
I am trying create a OAuth2 client to access a third-part OAuth2 Server. I have this lines added to my application.properties file:

```<code>spring.security.oauth2.client.registration.mercadolivre=mercadolivre
spring.security.oauth2.client.registration.mercadolivre.client-id=...
spring.security.oauth2.client.registration.mercadolivre.client-secret=...
spring.security.oauth2.client.registration.mercadolivre.client-authentication-method=basic
spring.security.oauth2.client.registration.mercadolivre.authorization-grant-type=authorization_code
spring.security.oauth2.client.registration.mercadolivre.redirect-uri=http://localhost:8080
spring.security.oauth2.client.provider.mercadolivre.authorization-uri=https://auth.mercadolivre.com.br/authorization
spring.security.oauth2.client.provider.mercadolivre.token-uri=https://auth.mercadolivre.com.br/oauth
</code>```

I have this Spring-security configuration:

```<code>@Configuration
@EnableWebSecurity
@EnableOAuth2Sso
public class Security extends WebSecurityConfigurerAdapter {
  @Override
  public void configure(HttpSecurity http) throws Exception {
      http
        .csrf().disable()
        .authorizeRequests()
          .antMatchers("/css/**", "/images/**", "/js/**", "/**").permitAll()
          .anyRequest().authenticated()
        .and()
          .oauth2Login()
        .and()
        .logout()
          .logoutUrl("/logout");
  }
...
}
</code>```

and this html for my open and secured areas:

```<code>  <body>
    <ul>
      <!--<li class="navbar-brand">
        <img th:src="@{/img/logo.png}" class="sticky" width="120px" height="120px" alt="logo">
      </li> -->

      <li>
        Loja
      </li>

      <li class="right" sec:authorize="isAnonymous()">
        <a class="button" th:href="@{/oauth2/authorization/mercadolivre}">Entrar</button>
      </li>

      <li sec:authorize="isAuthenticated()">
        Logged in as: <span sec:authentication="name">Bob</span>
      </li>

      <li class="right" sec:authorize="isAuthenticated()">
        <a class="button" th:href="@{/logout}">Sair</button>
      </li>
    </ul>
  </body>
</code>```

but when I open the application on the browser, and try login, I am forwarded to the autorization page correctly, but when I redirect back to my application, I am not authenticated.

Anyone can see what's wrong here?

UPDATE

After I change my spring-security configuration to this

```<code>@Configuration
@EnableWebSecurity
@EnableOAuth2Sso
public class Security extends WebSecurityConfigurerAdapter {
  @Override
  public void configure(HttpSecurity http) throws Exception {
      http
        .csrf().disable()
        .authorizeRequests()
          .antMatchers("/css/**", "/images/**", "/js/**", "/**").permitAll()
          .anyRequest().authenticated()
        .and()
        .formLogin()
          .loginPage("/login")
          .loginProcessingUrl("/doLogin").permitAll()
        .and()
        .oauth2Login()
          .loginPage("/login")
          .loginProcessingUrl("/login/oauth")
        .and()
        .logout()
          .logoutUrl("/logout");
  }
...
}
</code>```

and the application.properties redirect_uri to this:

```<code>spring.security.oauth2.client.registration.mercadolivre.redirect-uri=http://localhost:8080/login/oauth
</code>```

Now when I try signin I got this error:

```<code>java.lang.NullPointerException: null
        at org.springframework.security.oauth2.client.endpoint.DefaultAuthorizationCodeTokenResponseClient.getTokenResponse(DefaultAuthorizationCodeTokenResponseClient.java:84) ~[spring-security-oauth2-client-5.2.1.RELEASE.jar!/:5.2.1.RELEASE]
        at org.springframework.security.oauth2.client.endpoint.DefaultAuthorizationCodeTokenResponseClient.getTokenResponse(DefaultAuthorizationCodeTokenResponseClient.java:52) ~[spring-security-oauth2-client-5.2.1.RELEASE.jar!/:5.2.1.RELEASE]
        at org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationProvider.authenticate(OAuth2LoginAuthenticationProvider.java:103) ~[spring-security-oauth2-client-5.2.1.RELEASE.jar!/:5.2.1.RELEASE]
        at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:175) ~[spring-security-core-5.2.1.RELEASE.jar!/:5.2.1.RELEASE]
        at org.springframework.security.oauth2.client.web.OAuth2LoginAuthenticationFilter.attemptAuthentication(OAuth2LoginAuthenticationFilter.java:185) ~[spring-security-oauth2-client-5.2.1.RELEASE.jar!/:5.2.1.RELEASE]
        at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:212) ~[spring-security-web-5.2.1.RELEASE.jar!/:5.2.1.RELEASE]
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.2.1.RELEASE.jar!/:5.2.1.RELEASE]
        at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:200) ~[spring-security-web-5.2.1.RELEASE.jar!/:5.2.1.RELEASE]
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.2.1.RELEASE.jar!/:5.2.1.RELEASE]
        at org.springframework.security.oauth2.client.web.OAuth2AuthorizationRequestRedirectFilter.doFilterInternal(OAuth2AuthorizationRequestRedirectFilter.java:160) ~[spring-security-oauth2-client-5.2.1.RELEASE.jar!/:5.2.1.RELEASE]
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.3.RELEASE.jar!/:5.2.3.RELEASE]
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.2.1.RELEASE.jar!/:5.2.1.RELEASE]
        at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116) ~[spring-security-web-5.2.1.RELEASE.jar!/:5.2.1.RELEASE]
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.2.1.RELEASE.jar!/:5.2.1.RELEASE]
        at org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter(HeaderWriterFilter.java:92) ~[spring-security-web-5.2.1.RELEASE.jar!/:5.2.1.RELEASE]
        at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:77) ~[spring-security-web-5.2.1.RELEASE.jar!/:5.2.1.RELEASE]
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.3.RELEASE.jar!/:5.2.3.RELEASE]
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.2.1.RELEASE.jar!/:5.2.1.RELEASE]
        at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) ~[spring-security-web-5.2.1.RELEASE.jar!/:5.2.1.RELEASE]
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.2.1.RELEASE.jar!/:5.2.1.RELEASE]
        at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) ~[spring-security-web-5.2.1.RELEASE.jar!/:5.2.1.RELEASE]
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.3.RELEASE.jar!/:5.2.3.RELEASE]
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.2.1.RELEASE.jar!/:5.2.1.RELEASE]
        at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215) ~[spring-security-web-5.2.1.RELEASE.jar!/:5.2.1.RELEASE]
        at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178) ~[spring-security-web-5.2.1.RELEASE.jar!/:5.2.1.RELEASE]
        at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:358) ~[spring-web-5.2.3.RELEASE.jar!/:5.2.3.RELEASE]
        at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:271) ~[spring-web-5.2.3.RELEASE.jar!/:5.2.3.RELEASE]
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.30.jar!/:9.0.30]
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.30.jar!/:9.0.30]
        at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.2.3.RELEASE.jar!/:5.2.3.RELEASE]
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.3.RELEASE.jar!/:5.2.3.RELEASE]
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.30.jar!/:9.0.30]
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.30.jar!/:9.0.30]
        at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.2.3.RELEASE.jar!/:5.2.3.RELEASE]
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.3.RELEASE.jar!/:5.2.3.RELEASE]
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.30.jar!/:9.0.30]
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.30.jar!/:9.0.30]
        at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.2.3.RELEASE.jar!/:5.2.3.RELEASE]
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.3.RELEASE.jar!/:5.2.3.RELEASE]
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.30.jar!/:9.0.30]
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.30.jar!/:9.0.30]
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.30.jar!/:9.0.30]
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) ~[tomcat-embed-core-9.0.30.jar!/:9.0.30]
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541) ~[tomcat-embed-core-9.0.30.jar!/:9.0.30]
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) ~[tomcat-embed-core-9.0.30.jar!/:9.0.30]
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) ~[tomcat-embed-core-9.0.30.jar!/:9.0.30]
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) ~[tomcat-embed-core-9.0.30.jar!/:9.0.30]
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) ~[tomcat-embed-core-9.0.30.jar!/:9.0.30]
        at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:367) ~[tomcat-embed-core-9.0.30.jar!/:9.0.30]
        at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) ~[tomcat-embed-core-9.0.30.jar!/:9.0.30]
        at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:860) ~[tomcat-embed-core-9.0.30.jar!/:9.0.30]
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1598) ~[tomcat-embed-core-9.0.30.jar!/:9.0.30]
        at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.30.jar!/:9.0.30]
        at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) ~[na:na]
        at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) ~[na:na]
        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.30.jar!/:9.0.30]
        at java.base/java.lang.Thread.run(Thread.java:830) ~[na:na]
</code>```

(the redirect url looks fine, including with necessary code attached: http://localhost:8080/login/oauth?code=...&state=...)

update 2

my current setup is below. with this, i am forwarded to the service autorization page, but when I return to my project, I am not authenticated (the authorization code for getting access tokens is appended to the url with success).

App.java

```<code>@EnableOAuth2Client
@EnableOAuth2Sso
@SpringBootApplication
@RestController
public class App extends WebSecurityConfigurerAdapter {

    @GetMapping("/user")
    public Map<String, Object> user(@AuthenticationPrincipal OAuth2User principal) {
            return Collections.singletonMap("name", principal.getAttribute("name"));
    }

    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
            http
                    .authorizeRequests(a -> a
                            .antMatchers("/", "/error", "/webjars/**", "/css/**", "/js/**", "/img/**").permitAll()
                            .anyRequest().authenticated()
                    )
                    .exceptionHandling(e -> e
                            .authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED))
                    )
                    .csrf(c -> c
                .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
            )
                    .logout(l -> l
                        .logoutSuccessUrl("/").permitAll()
                    )
                    .oauth2Login();
    }

}
</code>```

application.properties

```<code>security.basic.enabled=false

spring.security.oauth2.client.registration.mercadolivre.client-id=...
spring.security.oauth2.client.registration.mercadolivre.client-secret=...

spring.security.oauth2.client.registration.mercadolivre.client-authentication-method=basic
spring.security.oauth2.client.registration.mercadolivre.authorization-grant-type=authorization_code
spring.security.oauth2.client.registration.mercadolivre.scope=read
spring.security.oauth2.client.registration.mercadolivre.redirect-uri=http://localhost:8080

spring.security.oauth2.client.provider.mercadolivre.authorization-uri=https://auth.mercadolibre.com/authorization
spring.security.oauth2.client.provider.mercadolivre.token-uri=https://api.mercadolivre.com.br/oauth/token
spring.security.oauth2.client.provider.mercadolivre.user-info-uri=https://api.mercadolibre.com/users/me
spring.security.oauth2.client.provider.mercadolivre.user-info-authentication-method=form

spring.security.oauth2.client.clientId=...
spring.security.oauth2.client.clientSecret=...
spring.security.oauth2.client.accessTokenUri=https://api.mercadolivre.com.br/oauth/token
spring.security.oauth2.client.userAuthorizationUri=https://auth.mercadolibre.com/authorization
spring.security.oauth2.client.clientAuthenticationScheme=form

spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
spring.thymeleaf.cache=false
</code>```

index.html

```<code><!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8"/>
    <title></title>
    <link rel="stylesheet" type="text/css" th:href="@{/webjars/bootstrap/css/bootstrap.min.css}"/>
</head>
<body>
  <nav class="navbar navbar-expand-lg fixed-top navbar-dark bg-dark">
    <a class="navbar-brand" href="#">
      <img th:src="@{/img/bootstrap-solid.svg}" width="30" height="30" class="d-inline-block align-top" alt="kleber app store">
      Kleber App Store
    </a>

    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav mr-auto">
      </ul>
      <ul class="navbar-nav">
        <li class="nav-item" sec:authorize="isAnonymous()">
          <a class="nav-link" href="/oauth2/authorization/mercadolivre">
            Fazer login com Mercado Livre
          </a>
        </li>
        <li class="nav-item" sec:authorize="isAuthenticated()">
          <a class="nav-link" href="#">
            Logged in as: <span sec:authentication="name">Bob</span>
          </a>
        </li>
        <li class="nav-item" sec:authorize="isAuthenticated()">
          <a class="btn btn-primary" th:href="@{/logout}">
            Logout
          </a>
        </li>
      </ul>
    </div>
  </nav>

  <script type="text/javascript" th:src="@{/webjars/jquery/jquery.min.js}"></script>
  <script type="text/javascript" th:src="@{/webjars/bootstrap/js/bootstrap.min.js}"></script>
  <script type="text/javascript" th:src="@{/webjars/js-cookie/js.cookie.js}"></script>
  <script type="text/javascript" th:src="@{/js/script.js}"></script>
</body>
</html>
</code>```

答:
I think that the redirect Uri of the OAuth2 client should be set to something like:

```<code>spring.security.oauth2.client.registration.mercadolivre.redirect-uri=http://localhost:8080/login/oauth2/mercadolivre
</code>```

and this same URI should be entered into your third-party OAuth2 Authorization Server as redirect URL, as this is where the authorization server should send the authorization code for Spring security to fetch a token eventually.

Pero

Body:
I am trying create a OAuth2 client to access a third-part OAuth2 Server. I have this lines added to my application.properties file:

spring.security.oauth2.client.registration.mercadolivre=mercadolivre
spring.security.oauth2.client.registration.mercadolivre.client-id=...
spring.security.oauth2.client.registration.mercadolivre.client-secret=...
spring.security.oauth2.client.registration.mercadolivre.client-authentication-method=basic
spring.security.oauth2.client.registration.mercadolivre.authorization-grant-type=authorization_code
spring.security.oauth2.client.registration.mercadolivre.redirect-uri=http://localhost:8080
spring.security.oauth2.client.provider.mercadolivre.authorization-uri=https://auth.mercadolivre.com.br/authorization
spring.security.oauth2.client.provider.mercadolivre.token-uri=https://auth.mercadolivre.com.br/oauth

I have this Spring-security configuration:

@Configuration
@EnableWebSecurity
@EnableOAuth2Sso
public class Security extends WebSecurityConfigurerAdapter {
  @Override
  public void configure(HttpSecurity http) throws Exception {
      http
        .csrf().disable()
        .authorizeRequests()
          .antMatchers("/css/**", "/images/**", "/js/**", "/**").permitAll()
          .anyRequest().authenticated()
        .and()
          .oauth2Login()
        .and()
        .logout()
          .logoutUrl("/logout");
  }
...
}

and this html for my open and secured areas:

        Loja

        Entrar</button>

        Logged in as: Bob

        Sair</button>

but when I open the application on the browser, and try login, I am forwarded to the autorization page correctly, but when I redirect back to my application, I am not authenticated.

Anyone can see what's wrong here?

UPDATE

After I change my spring-security configuration to this

@Configuration
@EnableWebSecurity
@EnableOAuth2Sso
public class Security extends WebSecurityConfigurerAdapter {
  @Override
  public void configure(HttpSecurity http) throws Exception {
      http
        .csrf().disable()
        .authorizeRequests()
          .antMatchers("/css/**", "/images/**", "/js/**", "/**").permitAll()
          .anyRequest().authenticated()
        .and()
        .formLogin()
          .loginPage("/login")
          .loginProcessingUrl("/doLogin").permitAll()
        .and()
        .oauth2Login()
          .loginPage("/login")
          .loginProcessingUrl("/login/oauth")
        .and()
        .logout()
          .logoutUrl("/logout");
  }
...
}

and the application.properties redirect_uri to this:

spring.security.oauth2.client.registration.mercadolivre.redirect-uri=http://localhost:8080/login/oauth

Now when I try signin I got this error:

java.lang.NullPointerException: null
        at org.springframework.security.oauth2.client.endpoint.DefaultAuthorizationCodeTokenResponseClient.getTokenResponse(DefaultAuthorizationCodeTokenResponseClient.java:84) ~[spring-security-oauth2-client-5.2.1.RELEASE.jar!/:5.2.1.RELEASE]
        at org.springframework.security.oauth2.client.endpoint.DefaultAuthorizationCodeTokenResponseClient.getTokenResponse(DefaultAuthorizationCodeTokenResponseClient.java:52) ~[spring-security-oauth2-client-5.2.1.RELEASE.jar!/:5.2.1.RELEASE]
        at org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationProvider.authenticate(OAuth2LoginAuthenticationProvider.java:103) ~[spring-security-oauth2-client-5.2.1.RELEASE.jar!/:5.2.1.RELEASE]
        at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:175) ~[spring-security-core-5.2.1.RELEASE.jar!/:5.2.1.RELEASE]
        at org.springframework.security.oauth2.client.web.OAuth2LoginAuthenticationFilter.attemptAuthentication(OAuth2LoginAuthenticationFilter.java:185) ~[spring-security-oauth2-client-5.2.1.RELEASE.jar!/:5.2.1.RELEASE]
        at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:212) ~[spring-security-web-5.2.1.RELEASE.jar!/:5.2.1.RELEASE]
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.2.1.RELEASE.jar!/:5.2.1.RELEASE]
        at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:200) ~[spring-security-web-5.2.1.RELEASE.jar!/:5.2.1.RELEASE]
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.2.1.RELEASE.jar!/:5.2.1.RELEASE]
        at org.springframework.security.oauth2.client.web.OAuth2AuthorizationRequestRedirectFilter.doFilterInternal(OAuth2AuthorizationRequestRedirectFilter.java:160) ~[spring-security-oauth2-client-5.2.1.RELEASE.jar!/:5.2.1.RELEASE]
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.3.RELEASE.jar!/:5.2.3.RELEASE]
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.2.1.RELEASE.jar!/:5.2.1.RELEASE]
        at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116) ~[spring-security-web-5.2.1.RELEASE.jar!/:5.2.1.RELEASE]
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.2.1.RELEASE.jar!/:5.2.1.RELEASE]
        at org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter(HeaderWriterFilter.java:92) ~[spring-security-web-5.2.1.RELEASE.jar!/:5.2.1.RELEASE]
        at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:77) ~[spring-security-web-5.2.1.RELEASE.jar!/:5.2.1.RELEASE]
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.3.RELEASE.jar!/:5.2.3.RELEASE]
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.2.1.RELEASE.jar!/:5.2.1.RELEASE]
        at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) ~[spring-security-web-5.2.1.RELEASE.jar!/:5.2.1.RELEASE]
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.2.1.RELEASE.jar!/:5.2.1.RELEASE]
        at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) ~[spring-security-web-5.2.1.RELEASE.jar!/:5.2.1.RELEASE]
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.3.RELEASE.jar!/:5.2.3.RELEASE]
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.2.1.RELEASE.jar!/:5.2.1.RELEASE]
        at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215) ~[spring-security-web-5.2.1.RELEASE.jar!/:5.2.1.RELEASE]
        at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178) ~[spring-security-web-5.2.1.RELEASE.jar!/:5.2.1.RELEASE]
        at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:358) ~[spring-web-5.2.3.RELEASE.jar!/:5.2.3.RELEASE]
        at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:271) ~[spring-web-5.2.3.RELEASE.jar!/:5.2.3.RELEASE]
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.30.jar!/:9.0.30]
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.30.jar!/:9.0.30]
        at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.2.3.RELEASE.jar!/:5.2.3.RELEASE]
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.3.RELEASE.jar!/:5.2.3.RELEASE]
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.30.jar!/:9.0.30]
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.30.jar!/:9.0.30]
        at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.2.3.RELEASE.jar!/:5.2.3.RELEASE]
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.3.RELEASE.jar!/:5.2.3.RELEASE]
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.30.jar!/:9.0.30]
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.30.jar!/:9.0.30]
        at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.2.3.RELEASE.jar!/:5.2.3.RELEASE]
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.3.RELEASE.jar!/:5.2.3.RELEASE]
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.30.jar!/:9.0.30]
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.30.jar!/:9.0.30]
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.30.jar!/:9.0.30]
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) ~[tomcat-embed-core-9.0.30.jar!/:9.0.30]
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541) ~[tomcat-embed-core-9.0.30.jar!/:9.0.30]
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) ~[tomcat-embed-core-9.0.30.jar!/:9.0.30]
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) ~[tomcat-embed-core-9.0.30.jar!/:9.0.30]
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) ~[tomcat-embed-core-9.0.30.jar!/:9.0.30]
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) ~[tomcat-embed-core-9.0.30.jar!/:9.0.30]
        at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:367) ~[tomcat-embed-core-9.0.30.jar!/:9.0.30]
        at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) ~[tomcat-embed-core-9.0.30.jar!/:9.0.30]
        at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:860) ~[tomcat-embed-core-9.0.30.jar!/:9.0.30]
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1598) ~[tomcat-embed-core-9.0.30.jar!/:9.0.30]
        at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.30.jar!/:9.0.30]
        at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) ~[na:na]
        at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) ~[na:na]
        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.30.jar!/:9.0.30]
        at java.base/java.lang.Thread.run(Thread.java:830) ~[na:na]

(the redirect url looks fine, including with necessary code attached: http://localhost:8080/login/oauth?code=...&state=...)

update 2

my current setup is below. with this, i am forwarded to the service autorization page, but when I return to my project, I am not authenticated (the authorization code for getting access tokens is appended to the url with success).

App.java

@EnableOAuth2Client
@EnableOAuth2Sso
@SpringBootApplication
@RestController
public class App extends WebSecurityConfigurerAdapter {

    @GetMapping("/user")
    public Map<String, Object> user(@AuthenticationPrincipal OAuth2User principal) {
            return Collections.singletonMap("name", principal.getAttribute("name"));
    }

    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
            http
                    .authorizeRequests(a -> a
                            .antMatchers("/", "/error", "/webjars/**", "/css/**", "/js/**", "/img/**").permitAll()
                            .anyRequest().authenticated()
                    )
                    .exceptionHandling(e -> e
                            .authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED))
                    )
                    .csrf(c -> c
                .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
            )
                    .logout(l -> l
                        .logoutSuccessUrl("/").permitAll()
                    )
                    .oauth2Login();
    }

}

application.properties

security.basic.enabled=false

spring.security.oauth2.client.registration.mercadolivre.client-id=...
spring.security.oauth2.client.registration.mercadolivre.client-secret=...

spring.security.oauth2.client.registration.mercadolivre.client-authentication-method=basic
spring.security.oauth2.client.registration.mercadolivre.authorization-grant-type=authorization_code
spring.security.oauth2.client.registration.mercadolivre.scope=read
spring.security.oauth2.client.registration.mercadolivre.redirect-uri=http://localhost:8080

spring.security.oauth2.client.provider.mercadolivre.authorization-uri=https://auth.mercadolibre.com/authorization
spring.security.oauth2.client.provider.mercadolivre.token-uri=https://api.mercadolivre.com.br/oauth/token
spring.security.oauth2.client.provider.mercadolivre.user-info-uri=https://api.mercadolibre.com/users/me
spring.security.oauth2.client.provider.mercadolivre.user-info-authentication-method=form

spring.security.oauth2.client.clientId=...
spring.security.oauth2.client.clientSecret=...
spring.security.oauth2.client.accessTokenUri=https://api.mercadolivre.com.br/oauth/token
spring.security.oauth2.client.userAuthorizationUri=https://auth.mercadolibre.com/authorization
spring.security.oauth2.client.clientAuthenticationScheme=form

spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
spring.thymeleaf.cache=false

index.html

<!doctype html>

    <meta charset="utf-8"/>
    <title></title>
    <link rel="stylesheet" type="text/css" th:href="@{/webjars/bootstrap/css/bootstrap.min.css}"/>

      Kleber App Store

            Fazer login com Mercado Livre

            Logged in as: Bob

            Logout

Body:
I think that the redirect Uri of the OAuth2 client should be set to something like:

spring.security.oauth2.client.registration.mercadolivre.redirect-uri=http://localhost:8080/login/oauth2/mercadolivre

and this same URI should be entered into your third-party OAuth2 Authorization Server as redirect URL, as this is where the authorization server should send the authorization code for Spring security to fetch a token eventually.

Pero


问:
Django JSONField dumping/loading
I'm using JSONField in some of my Django models and would like to migrate this data from Oracle to Postgres.

So far I haven't had any luck keeping this JSON data intact when using Django's dumpdata and loaddata commands, the data is transformed into string representations of the JSON. I've yet to find a good solution to this... Ideas?

答:
I haven't used the JSONField before, but what I do is:

```<code>import json

data_structure = json.loads(myData)
</code>```

Maybe that will work for what you need as well. There's likely a better way to deal with this.

Title: Django JSONField dumping/loading

Body:
I haven't used the JSONField before, but what I do is:

import json

data_structure = json.loads(myData)

Maybe that will work for what you need as well. There's likely a better way to deal with this.


问:
CSS :focus is ignored in Edge and Internet Explorer
I am using the focus in CSS for our placeholders to jump up when i am clicking inside but Edge is completaly ignoring my css. Its working with every browser but i dont find any solution for Edge. Any ideas what can cause the problem?

"I looked similar articles here but none of them seems working on the actual Edge. I tried also with : instead of :: at the ms- line also not working."

input {
    padding:10px;
    width:95%;
  }

 label {
    margin:10px 0;
    position:relative;
    display:inline-block;
    width:100%;
  }

  span {
    padding:10px;
    pointer-events: none;
    position:absolute;
    left:0;
    top:0;
    transition: 0.2s;
    transition-timing-function: ease;
    transition-timing-function: cubic-bezier(0.25, 0.1, 0.25, 1);
    opacity:0.5;
  }

  input:focus ~ span, input:not(:placeholder-shown) ~ span {
    opacity:1;
    transform:translateY(-100%) translateX(-10px);
    font-size:10px;
    padding:5px 10px;;

  }

  /* For IE Browsers*/

  input:focus ~ span, input:not(:-ms-input-placeholder) ~ span {
    opacity:1;
    transform:translateY(-100%) translateX(-10px);
    font-size:10px;
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label>
     <input type="password" name="E_password" value="" placeholder=" " />
     <span>Passwort*</span>
</label>  </code>```

答:
I tried to test your issue and I am able to see the issue in the MS Edge (EdgeHtml) browser. In the IE browser, your code works fine.

I tried to add some CSS code below to make it work with the MS Edge (EdgeHtml) browser.

```<code>/* For Edge Browser*/

  input:focus ~ span, input:invalid:not(:focus)::-webkit-input-placeholder {
    opacity:1;
    transform:translateY(-100%) translateX(-10px);
    font-size:10px;
  }
</code>```

Modified code:

<!doctype html>

     <input type="password" name="E_password" value="" placeholder=" " />
     Password*

```

Output in MS Edge (EdgeHtml) browser:

Output in IE 11 browser:

Reference:

Floating Label with Css not working in edge, internet explorer

Body:
I am using the focus in CSS for our placeholders to jump up when i am clicking inside but Edge is completaly ignoring my css. Its working with every browser but i dont find any solution for Edge. Any ideas what can cause the problem?

"I looked similar articles here but none of them seems working on the actual Edge. I tried also with : instead of :: at the ms- line also not working."

input {
    padding:10px;
    width:95%;
  }

 label {
    margin:10px 0;
    position:relative;
    display:inline-block;
    width:100%;
  }

  span {
    padding:10px;
    pointer-events: none;
    position:absolute;
    left:0;
    top:0;
    transition: 0.2s;
    transition-timing-function: ease;
    transition-timing-function: cubic-bezier(0.25, 0.1, 0.25, 1);
    opacity:0.5;
  }

  input:focus ~ span, input:not(:placeholder-shown) ~ span {
    opacity:1;
    transform:translateY(-100%) translateX(-10px);
    font-size:10px;
    padding:5px 10px;;

  }

  /* For IE Browsers*/

  input:focus ~ span, input:not(:-ms-input-placeholder) ~ span {
    opacity:1;
    transform:translateY(-100%) translateX(-10px);
    font-size:10px;
  }

     <input type="password" name="E_password" value="" placeholder=" " />
     Passwort*

Body:
I tried to test your issue and I am able to see the issue in the MS Edge (EdgeHtml) browser. In the IE browser, your code works fine.

I tried to add some CSS code below to make it work with the MS Edge (EdgeHtml) browser.

/* For Edge Browser*/

  input:focus ~ span, input:invalid:not(:focus)::-webkit-input-placeholder {
    opacity:1;
    transform:translateY(-100%) translateX(-10px);
    font-size:10px;
  }

Modified code:

<!doctype html>
<html>
<head>
<style>
input {
    padding:10px;
    width:95%;
  }

 label {
    margin:20px 0;
    position:relative;
    display:inline-block;
    width:100%;
  }

  span {
    padding:10px;
    pointer-events: none;
    position:absolute;
    left:0;
    top:0;
    transition: 0.2s;
    transition-timing-function: ease;
    transition-timing-function: cubic-bezier(0.25, 0.1, 0.25, 1);
    opacity:0.5;
  }

  input:focus ~ span, input:not(:placeholder-shown) ~ span {
    opacity:1;
    transform:translateY(-100%) translateX(-10px);
    font-size:10px;
    padding:5px 10px;;

  }

  /* For IE Browsers*/

  input:focus ~ span, input:not(:-ms-input-placeholder) ~ span {
    opacity:1;
    transform:translateY(-100%) translateX(-10px);
    font-size:10px;
  }

/* For Edge Browser*/

  input:focus ~ span, input:invalid:not(:focus)::-webkit-input-placeholder {
    opacity:1;
    transform:translateY(-100%) translateX(-10px);
    font-size:10px;
  }
</style>

</head>
<body>
<label>
     <input type="password" name="E_password" value="" placeholder=" " />
     <span>Password<sup><font color="red" class="imp" >*</font></span>
</label>
</body>
</html>

Output in MS Edge (EdgeHtml) browser:

Output in IE 11 browser:

Reference:

Floating Label with Css not working in edge, internet explorer


问:
Java : while loop not detecting break condition but if block does
just want to break out of this while loop. Condition doesn't break when I assumed it will, but it does get registered by the subsequent if statement.

```<code>  String current_Class_Name = "";
  int current_Class_Rating;

    while(!current_Class_Name.equals("Done")) {

      // * Get class name.
      System.out.println("What class are you rating?");
      current_Class_Name = in.nextLine();
      // *
      // if(current_Class_Name.equals("Done")) {
      // System.out.println("Detected 'Done'");
      // break;
      // }

      // * Get class rating.
      System.out.println("How many plus signs does " + current_Class_Name + " get?");
      current_Class_Rating = Integer.parseInt(in.nextLine());

      // * If user inputs an invalid rating (not a value between 0-5),
      // * keep prompting them until they enter a valid input.
      while(current_Class_Rating > 5 || current_Class_Rating < 0) {
        System.out.println("Sorry, but you can only give a rating of 0-5.");
        System.out.println("How many plus signs does " + current_Class_Name + " get?");
        current_Class_Rating = Integer.parseInt(in.nextLine());
      }

      // * TODO
      // * Add to STRING and INTEGER LISTS.
    }

</code>```

Possibly some kind of call order problem as the String is "empty" upon entering the while loop.
Sorry for any formatting.

Thanks for any and all help.

NOTE : I typically use C# and as far as I remember, a while loop will try and detect the condition case before completing an entire iteration.

EDIT : The if statement is not there to run, but to just prove two things : 1) that the break condition can be detected and 2) to break out at a given time.

EDIT : Updated to show all code in consideration.

答:
Your question appears to have been based on a misconception, the while loop will only terminate when the condition is re-evaluated to be false at the top (not on the instant of the variable being updated). However, you can make it so the prompt, the assignment and the evaluation happen at once. First, create a helper method. Like,

```<code>private static String promptForClassName(Scanner in) {
    System.out.println("What class are you rating?");
    return in.nextLine();
}
</code>```

Then, use it with the fact that assignment (as a side-effect) evaluates to the assigned value; also, please follow standard Java camel case naming conventions. Like,

```<code>String currentClassName;
while (!(currentClassName = promptForClassName(in)).equalsIgnoreCase("Done")) {
    String prompt = "How many plus signs does " + currentClassName + " get?";
    // * Get class rating.
    System.out.println(prompt);
    int currentClassRating = Integer.parseInt(in.nextLine());

    // * If user inputs an invalid rating (not a value between 0-5),
    // * keep prompting them until they enter a valid input.
    while (currentClassRating > 5 || currentClassRating < 0) {
        System.out.println("Sorry, but you can only give a rating of 0-5.");
        System.out.println(prompt);
        currentClassRating = Integer.parseInt(in.nextLine());
    }

    // * TODO
    // * Add to STRING and INTEGER LISTS.
}
System.out.println("Detected 'Done'");
</code>```

Body:
just want to break out of this while loop. Condition doesn't break when I assumed it will, but it does get registered by the subsequent if statement.

  String current_Class_Name = "";
  int current_Class_Rating;

    while(!current_Class_Name.equals("Done")) {

      // * Get class name.
      System.out.println("What class are you rating?");
      current_Class_Name = in.nextLine();
      // *
      // if(current_Class_Name.equals("Done")) {
      // System.out.println("Detected 'Done'");
      // break;
      // }

      // * Get class rating.
      System.out.println("How many plus signs does " + current_Class_Name + " get?");
      current_Class_Rating = Integer.parseInt(in.nextLine());

      // * If user inputs an invalid rating (not a value between 0-5),
      // * keep prompting them until they enter a valid input.
      while(current_Class_Rating > 5 || current_Class_Rating < 0) {
        System.out.println("Sorry, but you can only give a rating of 0-5.");
        System.out.println("How many plus signs does " + current_Class_Name + " get?");
        current_Class_Rating = Integer.parseInt(in.nextLine());
      }

      // * TODO
      // * Add to STRING and INTEGER LISTS.
    }

Possibly some kind of call order problem as the String is "empty" upon entering the while loop.
Sorry for any formatting.

Thanks for any and all help.

NOTE : I typically use C# and as far as I remember, a while loop will try and detect the condition case before completing an entire iteration.

EDIT : The if statement is not there to run, but to just prove two things : 1) that the break condition can be detected and 2) to break out at a given time.

EDIT : Updated to show all code in consideration.

Body:
Your question appears to have been based on a misconception, the while loop will only terminate when the condition is re-evaluated to be false at the top (not on the instant of the variable being updated). However, you can make it so the prompt, the assignment and the evaluation happen at once. First, create a helper method. Like,

private static String promptForClassName(Scanner in) {
    System.out.println("What class are you rating?");
    return in.nextLine();
}

Then, use it with the fact that assignment (as a side-effect) evaluates to the assigned value; also, please follow standard Java camel case naming conventions. Like,

String currentClassName;
while (!(currentClassName = promptForClassName(in)).equalsIgnoreCase("Done")) {
    String prompt = "How many plus signs does " + currentClassName + " get?";
    // * Get class rating.
    System.out.println(prompt);
    int currentClassRating = Integer.parseInt(in.nextLine());

    // * If user inputs an invalid rating (not a value between 0-5),
    // * keep prompting them until they enter a valid input.
    while (currentClassRating > 5 || currentClassRating < 0) {
        System.out.println("Sorry, but you can only give a rating of 0-5.");
        System.out.println(prompt);
        currentClassRating = Integer.parseInt(in.nextLine());
    }

    // * TODO
    // * Add to STRING and INTEGER LISTS.
}
System.out.println("Detected 'Done'");


问:
localhost didn't send any data - ERR_EMPTY_RESPONSE
Using VScode to write NodeJS

But to check, localhost isn't responding properly, it says "the page didn't send any data.
I tried looking everywhere and changed all the possible settings I can.

restored chrome settings
cleared cache, cleared history, changed port numbers, changed LAN settings.

```<code> ''''

const Joi = require('joi');
const express = require('express');
const app = express();

app.use(express.json); //to take inputs ffrom the browser
const courses = [
{id: 1, name: "course 1"},
{id: 2, name: "course 2"},
{id: 3, name: "course 3"},
 ];

app.get('/', (req, res) =>{
res.send("Hello world!!");
res.end();
});

app.get('/api/courses/', (req, res) =>{
res.send(courses);
res.end();
});

const port = process.env.port || 8080;
app.listen(port, ()=> console.log(`Listining on port ${port}..`));

 ''''
</code>```

Want to see all the courses printed on the webpage.

答:
```<code>`package.json
"dependencies": {
    "body-parser": "^1.19.0",
    "ejs": "^3.0.1",
    "express": "^4.17.1",
    "mongoclient": "^1.0.3",
    "mongodb": "^2.2.33",
    "mongoose": "^5.8.12"
  }

app.js

const express = require('express');
const bodyParser=require('body-parser');
const app=express();

var db=require('./db')
var user=require('./module/user');

const port=process.env.PORT || 8080;
//to read the name property from html or ejs form or page body parser used there for.(tunnel)
app.use(bodyParser.urlencoded({ extended: true}))
//app.use(bodyParser.json);`
</code>```

you don't need to add app.use line in "body-parser": "^1.19.0" this version, this is run
  in my era.

Body:
Using VScode to write NodeJS

But to check, localhost isn't responding properly, it says "the page didn't send any data.
I tried looking everywhere and changed all the possible settings I can.

restored chrome settings
cleared cache, cleared history, changed port numbers, changed LAN settings.

 ''''

const Joi = require('joi');
const express = require('express');
const app = express();

app.use(express.json); //to take inputs ffrom the browser
const courses = [
{id: 1, name: "course 1"},
{id: 2, name: "course 2"},
{id: 3, name: "course 3"},
 ];

app.get('/', (req, res) =>{
res.send("Hello world!!");
res.end();
});

app.get('/api/courses/', (req, res) =>{
res.send(courses);
res.end();
});

const port = process.env.port || 8080;
app.listen(port, ()=> console.log(`Listining on port ${port}..`));

 ''''

Want to see all the courses printed on the webpage.

Body:
`package.json
"dependencies": {
    "body-parser": "^1.19.0",
    "ejs": "^3.0.1",
    "express": "^4.17.1",
    "mongoclient": "^1.0.3",
    "mongodb": "^2.2.33",
    "mongoose": "^5.8.12"
  }

app.js

const express = require('express');
const bodyParser=require('body-parser');
const app=express();

var db=require('./db')
var user=require('./module/user');

const port=process.env.PORT || 8080;
//to read the name property from html or ejs form or page body parser used there for.(tunnel)
app.use(bodyParser.urlencoded({ extended: true}))
//app.use(bodyParser.json);`

you don't need to add app.use line in "body-parser": "^1.19.0" this version, this is run
  in my era.


问:
Checking a CSV for the existence of a similar value in Python
Consider the following CSV:

```<code>date,description,amount
14/02/2020,march contract,-99.00
15/02/2020,april contract,340.00
16/02/2020,march contract,150.00
17/02/2020,april contract,-100.00
</code>```

What I'd like to do is:

Iterate through all of the rows

Total the amounts of lines which have the same description

Return the last line which has that newly-calculated amount

Applied to the above example, the CSV would look like this:

```<code>16/02/2020,march contract,51.00
17/02/2020,april contract,240.00
</code>```

So far, I've tried nesting csv.reader()s inside of each other and I'm not getting the result I am wanting.

I'd like to achieve this without any libraries and/or modules.

Here is the code I have so far, where first_row is each row in the CSV and second_row is the iteration of looking for matching descriptions:

csv_reader = csv.reader(report_file)
        for first_row in csv_reader:
            description_index = 5
            amount_index = 13
            print(first_row)
            for second_row in csv_reader:
                if second_row is not first_row:
                    print(first_row[description_index] == second_row[description_index])
                        if first_row[description_index] == second_row[description_index]:
                            first_row[amount_index] = float(first_row[amount_index]) + float(second_row[amount_index])
```

答:
I suggest you should use pandas, it'll be efficient.

or if you still want to go with your way then this will help.

```<code>import csv

with open('mycsv.csv') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    value_dict = {}
    line_no = 0
    for row in csv_reader:
        if line_no == 0:
            line_no += 1
            continue
        cur_date = row[0]
        cur_mon = row[1]
        cur_val = float(row[2])
        if row[1] not in value_dict.keys():
            value_dict[cur_mon] = [cur_date, cur_val]
        else:
            old_date, old_val = value_dict[cur_mon]
            value_dict[cur_mon] = [cur_date, (old_val + cur_val)]
        line_no += 1

for key, val_list in value_dict.items():
    print(f"{val_list[0]},{key},{val_list[1]}")
</code>```

Output:

```<code>16/02/2020,march contract,51.0
17/02/2020,april contract,240.0
</code>```

Mark this as answer if it helps you.

Body:
Consider the following CSV:

date,description,amount
14/02/2020,march contract,-99.00
15/02/2020,april contract,340.00
16/02/2020,march contract,150.00
17/02/2020,april contract,-100.00

What I'd like to do is:

Iterate through all of the rows

Total the amounts of lines which have the same description

Return the last line which has that newly-calculated amount

Applied to the above example, the CSV would look like this:

16/02/2020,march contract,51.00
17/02/2020,april contract,240.00

So far, I've tried nesting csv.reader()s inside of each other and I'm not getting the result I am wanting.

I'd like to achieve this without any libraries and/or modules.

Here is the code I have so far, where first_row is each row in the CSV and second_row is the iteration of looking for matching descriptions:

csv_reader = csv.reader(report_file)
        for first_row in csv_reader:
            description_index = 5
            amount_index = 13
            print(first_row)
            for second_row in csv_reader:
                if second_row is not first_row:
                    print(first_row[description_index] == second_row[description_index])
                        if first_row[description_index] == second_row[description_index]:
                            first_row[amount_index] = float(first_row[amount_index]) + float(second_row[amount_index])

Body:
I suggest you should use pandas, it'll be efficient.

or if you still want to go with your way then this will help.

import csv

with open('mycsv.csv') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    value_dict = {}
    line_no = 0
    for row in csv_reader:
        if line_no == 0:
            line_no += 1
            continue
        cur_date = row[0]
        cur_mon = row[1]
        cur_val = float(row[2])
        if row[1] not in value_dict.keys():
            value_dict[cur_mon] = [cur_date, cur_val]
        else:
            old_date, old_val = value_dict[cur_mon]
            value_dict[cur_mon] = [cur_date, (old_val + cur_val)]
        line_no += 1

for key, val_list in value_dict.items():
    print(f"{val_list[0]},{key},{val_list[1]}")

Output:

16/02/2020,march contract,51.0
17/02/2020,april contract,240.0

Mark this as answer if it helps you.


问:
How can I find the smallest value in an array that is within an object inside of an ArrayList? The value is concatenated with other characters
I am programming a CPU scheduler for SJF in Java. I have an ArrayList that contains the job objects. Each job consists of a program ID along with an array of CPU bursts, etc. How can I find the smallest value, among all the jobs, that is selecting from just the lowest index of each array?

Okay, I will try to be more clear. Here is the code that I am using to create the jobs and add them to the ArrayList at the same time.

```<code>//add PCB objects to the jobQueue ArrayList. listOfBursts is an array.
 jobQueue.add(new PCB(processID, listOfCPUBursts));
</code>```

Let's say I have 3 PCB objects in the jobQueue ArrayList.
I need to run the CPU bursts in the order that they appear in the array, but the smallest value in the lowest index must run first. I feel like this is still not clear, so I'll try a picture.

```<code>          PCB-1's array = {4, 7, 2, 3}
          PCB-2's array = {5, 2, 1, 3}
          PCB-3's array = {3, 8, 4, 2}
</code>```

These jobs need to go to the CPU, for whatever time-slice has been entered, and then returned to the jobQueue. The order that they go to the CPU needs to be determined by the lowest value that is at index 0 for any of the PCB's. In this case, I need to find the lowest of 4, 5, or 3.

Let's say the time-slice is 3. PCB-3 goes to the CPU, uses up it's burst then gets returned to the jobQueue. Again I need to find the lowest value to send to the CPU, but now I am looking at 4, 5 and 8.

I hope that makes more sense.

答:
Declare an Array to store all the lowest values from each CPU Burst array from each job. Initialize the size of this array to the number of jobs available (ArrayList size).

Iterate through the ArrayList so as to acquire each Job object stored there.
Acquire the CPU Bursts Array from each job and sort it in ascending order. This will bring the smallest value to the beginning of each array. Grab the value at index 0 and store in the array you declared earlier.

Now you have an array of all the lowest values.

Here is some example code:

The Job Class:

```<code>public class Job {

    private int programID;
    private int[] cpuBursts;

    public Job() {}

    public Job (int programid,  int[] cpubursts) {
        this.programID = programid;
        this.cpuBursts = cpubursts;
    }

    public int getProgramID() {
        return programID;
    }

    public void setProgramID(int programID) {
        this.programID = programID;
    }

    public int[] getCpuBursts() {
        return cpuBursts;
    }

    public void setCpuBursts(int[] cpuBursts) {
        this.cpuBursts = cpuBursts;
    }
}
</code>```

Fill The Jobs and ArrayList:

```<code>ArrayList<Job> jobsList = new ArrayList<>();
Job job;

// Fill jobsList ArrayList with 10 different job objects...
Random randomGenerator = new Random();
for (int i = 0; i < 10; i++) {
    // Create a new Program ID
    int id = 2230 + (i + 1);

    // Fill a CPU Burst array with 15 random integer values...
    int[] bursts = new int[15];
    for (int j = 0; j < 15; j++) {
        int randomBurst = randomGenerator.nextInt(100) + 1;
        bursts[j] = randomBurst;
    }

    // declare a job object
    job = new Job(id, bursts);

    // Add the job to the Jobs List
    jobsList.add(job);
}
</code>```

Now you have an ArrayList named jobsList which contains 10 Job objects. Each Job object contains a integer variable named programID (which contains a unique Program ID number) and a integer array named cpuBursts which contains 15 random burst values from 1 to 100.

Now to get the lowest burst value from each Job:

```<code>/* From the 10 Job objects stored within the ArrayList,
   display the all the jobs and at the end, display the
   lowest burst detected in each Job cpuBurst array.  */
int[] lowestBursts = new int[jobsList.size()];  // To hold the lowest bursts.

// Iterate through the Jobs within the ArrayList...
for (int i = 0; i < jobsList.size(); i++) {
    // Display information about the Job...
    System.out.println("Job #" + (i + 1) + ":");
    System.out.println("Program ID: --> " + jobsList.get(i).getProgramID());
    System.out.println("CPU Bursts: --> " + Arrays.toString(jobsList.get(i).getCpuBursts()));
    System.out.println();

    // Sort the cpuBurst array in ascending order.
    Arrays.sort(jobsList.get(i).getCpuBursts());

    // Grab the first burst within the array, it will be the lowest.
    lowestBursts[i] = jobsList.get(i).getCpuBursts()[0];
}

// Now, Display all the lowest bursts from each array..
System.out.println("Lowest Burst In Each Job:");
System.out.println(Arrays.toString(lowestBursts));
</code>```

Body:
I am programming a CPU scheduler for SJF in Java. I have an ArrayList that contains the job objects. Each job consists of a program ID along with an array of CPU bursts, etc. How can I find the smallest value, among all the jobs, that is selecting from just the lowest index of each array?

Okay, I will try to be more clear. Here is the code that I am using to create the jobs and add them to the ArrayList at the same time.

//add PCB objects to the jobQueue ArrayList. listOfBursts is an array.
 jobQueue.add(new PCB(processID, listOfCPUBursts));

Let's say I have 3 PCB objects in the jobQueue ArrayList.
I need to run the CPU bursts in the order that they appear in the array, but the smallest value in the lowest index must run first. I feel like this is still not clear, so I'll try a picture.

          PCB-1's array = {4, 7, 2, 3}
          PCB-2's array = {5, 2, 1, 3}
          PCB-3's array = {3, 8, 4, 2}

These jobs need to go to the CPU, for whatever time-slice has been entered, and then returned to the jobQueue. The order that they go to the CPU needs to be determined by the lowest value that is at index 0 for any of the PCB's. In this case, I need to find the lowest of 4, 5, or 3.

Let's say the time-slice is 3. PCB-3 goes to the CPU, uses up it's burst then gets returned to the jobQueue. Again I need to find the lowest value to send to the CPU, but now I am looking at 4, 5 and 8.

I hope that makes more sense.

Body:
Declare an Array to store all the lowest values from each CPU Burst array from each job. Initialize the size of this array to the number of jobs available (ArrayList size).

Iterate through the ArrayList so as to acquire each Job object stored there.
Acquire the CPU Bursts Array from each job and sort it in ascending order. This will bring the smallest value to the beginning of each array. Grab the value at index 0 and store in the array you declared earlier.

Now you have an array of all the lowest values.

Here is some example code:

The Job Class:

public class Job {

    private int programID;
    private int[] cpuBursts;

    public Job() {}

    public Job (int programid,  int[] cpubursts) {
        this.programID = programid;
        this.cpuBursts = cpubursts;
    }

    public int getProgramID() {
        return programID;
    }

    public void setProgramID(int programID) {
        this.programID = programID;
    }

    public int[] getCpuBursts() {
        return cpuBursts;
    }

    public void setCpuBursts(int[] cpuBursts) {
        this.cpuBursts = cpuBursts;
    }
}

Fill The Jobs and ArrayList:

ArrayList<Job> jobsList = new ArrayList<>();
Job job;

// Fill jobsList ArrayList with 10 different job objects...
Random randomGenerator = new Random();
for (int i = 0; i < 10; i++) {
    // Create a new Program ID
    int id = 2230 + (i + 1);

    // Fill a CPU Burst array with 15 random integer values...
    int[] bursts = new int[15];
    for (int j = 0; j < 15; j++) {
        int randomBurst = randomGenerator.nextInt(100) + 1;
        bursts[j] = randomBurst;
    }

    // declare a job object
    job = new Job(id, bursts);

    // Add the job to the Jobs List
    jobsList.add(job);
}

Now you have an ArrayList named jobsList which contains 10 Job objects. Each Job object contains a integer variable named programID (which contains a unique Program ID number) and a integer array named cpuBursts which contains 15 random burst values from 1 to 100.

Now to get the lowest burst value from each Job:

/* From the 10 Job objects stored within the ArrayList,
   display the all the jobs and at the end, display the
   lowest burst detected in each Job cpuBurst array.  */
int[] lowestBursts = new int[jobsList.size()];  // To hold the lowest bursts.

// Iterate through the Jobs within the ArrayList...
for (int i = 0; i < jobsList.size(); i++) {
    // Display information about the Job...
    System.out.println("Job #" + (i + 1) + ":");
    System.out.println("Program ID: --> " + jobsList.get(i).getProgramID());
    System.out.println("CPU Bursts: --> " + Arrays.toString(jobsList.get(i).getCpuBursts()));
    System.out.println();

    // Sort the cpuBurst array in ascending order.
    Arrays.sort(jobsList.get(i).getCpuBursts());

    // Grab the first burst within the array, it will be the lowest.
    lowestBursts[i] = jobsList.get(i).getCpuBursts()[0];
}

// Now, Display all the lowest bursts from each array..
System.out.println("Lowest Burst In Each Job:");
System.out.println(Arrays.toString(lowestBursts));


问:
What are the ascii values of up down left right?
What are the ASCII values of the arrow keys? (up/down/left/right)</p>

答:
this is what i get:

Left - 19
Up - 5
Right - 4
Down - 24

Works in Visual Fox Pro

ContentLicense: CC BY-SA 2.5


问:
How to create type for interface in gRPC Protobuf?
We have common Auth service for all microservices.
When we validate request in response, we send JSON that look like this.

```<code>{
    Auth: bool,
    Body: interface{}
}
</code>```

While writing proto3 syntax, how can we write something like an interface type?

I have tried using Any type, but I am not able to use it as we need to pass message type in type url which I am not able to generate.

Proto message for response

```<code>message AuthResponse {
    bool Auth = 1;
    google.protobuf.Any Body = 2;
}
</code>```

Can anyone help here?

答:
You can set the body type to bytes.

If you have a pre-defined set of types that your body could be, then I suggest you change your Auth struct to something like this:

```<code>type AuthResponse struct {
    Auth bool
    Body Encodable
}

// Encodable defines types that can be encoded into a byte slice.
type Encodable interface {
    Encode() []byte
}
</code>```

Then, implement Encode() []byte on each of your types.

Alternatively, if your Body field can be anything, then perhaps a similar solution, except your Encode function would look like this:

func Encode(interface{}) []byte

In this scenario, though, you may have to use some reflection magic in order to encode it to some byte slice. You could even use JSON.

I hope this helps!

Body:
We have common Auth service for all microservices.
When we validate request in response, we send JSON that look like this.

{
    Auth: bool,
    Body: interface{}
}

While writing proto3 syntax, how can we write something like an interface type?

I have tried using Any type, but I am not able to use it as we need to pass message type in type url which I am not able to generate.

Proto message for response

message AuthResponse {
    bool Auth = 1;
    google.protobuf.Any Body = 2;
}

Can anyone help here?

Body:
You can set the body type to bytes.

If you have a pre-defined set of types that your body could be, then I suggest you change your Auth struct to something like this:

type AuthResponse struct {
    Auth bool
    Body Encodable
}

// Encodable defines types that can be encoded into a byte slice.
type Encodable interface {
    Encode() []byte
}

Then, implement Encode() []byte on each of your types.

Alternatively, if your Body field can be anything, then perhaps a similar solution, except your Encode function would look like this:

func Encode(interface{}) []byte

In this scenario, though, you may have to use some reflection magic in order to encode it to some byte slice. You could even use JSON.

I hope this helps!


问:
Adding an extra parenthesis into a method in JavaScript?
Whenever I go through JavaScript code, I see a method that haves a pair of extra parentheses.

For example:

```<code>if( (typeOf VariableName) === "function" )
</code>```

or

```<code>alert(("Hello World"))
</code>```

What does these do, and why are they needed?

答:
Do you remember [BODMAS] Rule,

Which has set of rules of arithmetic precedence for the way microprocessor do arithmetic decisions.

So highest precedence in Rule is bracket, We can set statements in bracket where end results might will affect because of Division Multipication Addition Subtraction [ DMAS ] precedences. (which in many cases are overlooked because of complexities of statements )

Body:
Whenever I go through JavaScript code, I see a method that haves a pair of extra parentheses.

For example:

if( (typeOf VariableName) === "function" )

or

alert(("Hello World"))

What does these do, and why are they needed?


问:
Azure Pipelines: Bulk approve of deployments to environments
Is there any way to approve runs via the CLI or the API (or anything else)? I'm looking for a way to bulk approve multiple runs from different pipelines but it's not available in the UI.

Let's say I have 100 pipelines that have a deployment job to a production environment. I would like to approve all awaiting for approval runs.

Currently, I cannot find something like it in the docs of the Azure DevOps REST API or the CLI.

The feature docs:
https://learn.microsoft.com/en-us/azure/devops/pipelines/process/environments
https://learn.microsoft.com/en-us/azure/devops/pipelines/process/approvals

The following question is related but I'm looking for any way of solving it but not just via API:
Approve a yaml pipeline deployment in Azure DevOps using REST api

答:
What jessehouwing's guess is correct. Now multi-stage still be in preview, and the corresponding SDK/API/extension hasn't been expanded and provided to public.

You may think that what about not using API. I have checked the corresponding code from our backend, all of operations to multi-stage approval contain one required parameter: approvalId. I'm sure you have known that this value is unique and different approval map with different approvalId value. This means, no matter which method you want to try with, approvalId is the big trouble. And based on my known, until now, there's no any api/SDK, third tool or extension can achieve this value directly.

In addition, for multi-stage YAML, its release process logic is not same with the release that defined with UI. So, all of public APIs which can work with release(UI), are not suitable with the release of multi-stage.

We have one undisclosed api, can get Approval message of multi-stage:

```<code>https://dev.azure.com/{org}/{project}/_apis/pipelines/approvals/{approvalId}
</code>```

You can try with listing approval without specifying approvalId: https://dev.azure.com/{org}/{project}/_apis/pipelines/approvals. And its response message: Query for approvals failed. A minimum of one query parameter is required.\r\nParameter name: queryParameters. This represents you must tell system the specified approval(the big trouble I mentioned previously).

In fact, for why approvalId is a necessary part, it is caused from our backend code structure. I'd suggest you raise suggestion on developing API/SDK for multi-stage here.

Body:
What jessehouwing's guess is correct. Now multi-stage still be in preview, and the corresponding SDK/API/extension hasn't been expanded and provided to public.

You may think that what about not using API. I have checked the corresponding code from our backend, all of operations to multi-stage approval contain one required parameter: approvalId. I'm sure you have known that this value is unique and different approval map with different approvalId value. This means, no matter which method you want to try with, approvalId is the big trouble. And based on my known, until now, there's no any api/SDK, third tool or extension can achieve this value directly.

In addition, for multi-stage YAML, its release process logic is not same with the release that defined with UI. So, all of public APIs which can work with release(UI), are not suitable with the release of multi-stage.

We have one undisclosed api, can get Approval message of multi-stage:

https://dev.azure.com/{org}/{project}/_apis/pipelines/approvals/{approvalId}

You can try with listing approval without specifying approvalId: https://dev.azure.com/{org}/{project}/_apis/pipelines/approvals. And its response message: Query for approvals failed. A minimum of one query parameter is required.\r\nParameter name: queryParameters. This represents you must tell system the specified approval(the big trouble I mentioned previously).

In fact, for why approvalId is a necessary part, it is caused from our backend code structure. I'd suggest you raise suggestion on developing API/SDK for multi-stage here.


问:
Management API error: persistentPreferredActivities 4
I am building an Android KIOSK app, and I try to enable kiosk mode with Android Management API by providing a device policy.

My policy json is:

```<code>    {
        "keyguardDisabled": true,
        "applications": [
                {
                  "packageName": "my.own.app",
                  "installType": "KIOSK",
                  "defaultPermissionPolicy": "GRANT"
                }
        ]
    }
</code>```

What's interesting, the policy is from official API's example, so I suppose that works.
Whatever, always get this error:

Error info persistentPreferredActivities 4

And just a google search does not give me any clue how to resolve this.

When I set installType as KIOSK, I always got this error. My clue was that my policy lacks of PersistentPreferredActivity json block. I've added it, and I still got this error. What's interesting, there's a note: "Note: To set up a kiosk, use InstallType to KIOSK rather than use persistent preferred activities." So we do not need PersistentPreferredActivity. But I do not understand the error then.

Moving on. I've tried to make kiosk mode by setting kioskCustomLauncherEnabled to true. I set "installType": "AVAILABLE", so I can run the app from Android Studio.
I applied the policy on a device successfully. When I try to open my app's Kiosk Activity I have "App is not device owner" Toast.

Basically, what I need is probably lockTaskAllowed modifier, but it's deprecated.

Could somebody help me to make the device policy for KIOSK app, please?

答:
Take note that KIOSK mode only works on fully managed devices. For a device to be fully managed, it must be provisioned from a setup wizard by using QR code containing an enrollment token or by other supported enrollment methods.

To be able to use the app in a policy, it must be available in Google Play. It should either be a public app or a private app that is made available to the enterprise (ID) you are managing with the Android Management API.

Here's the difference between "installType": "KIOSK" and kioskCustomLauncherEnabled:

"installType": "KIOSK" is used to pin a single app to the screen

```<code>policy_json = '''
{
  "applications": [
  {
    "packageName": "com.google.android.gm",
    "installType": "KIOSK",
    "defaultPermissionPolicy": "GRANT"
  }
],
  "debuggingFeaturesAllowed": true
}
'''
</code>```

Now, if you want to use a set of apps in KIOSK mode you can use kioskCustomLauncherEnabled

```<code>policy_json = '''
{
  "applications": [
    {
    "packageName": "com.android.chrome",
    "installType": "FORCE_INSTALLED",
    "defaultPermissionPolicy": "GRANT"
  },
  {
    "packageName": "com.google.android.gm",
    "installType": "FORCE_INSTALLED",
    "defaultPermissionPolicy": "GRANT"
  }
],
  "debuggingFeaturesAllowed": true,
  "kioskCustomLauncherEnabled": true,
  "keyguardDisabled": true
}
'''
</code>```

Body:
I am building an Android KIOSK app, and I try to enable kiosk mode with Android Management API by providing a device policy.

My policy json is:

    {
        "keyguardDisabled": true,
        "applications": [
                {
                  "packageName": "my.own.app",
                  "installType": "KIOSK",
                  "defaultPermissionPolicy": "GRANT"
                }
        ]
    }

What's interesting, the policy is from official API's example, so I suppose that works.
Whatever, always get this error:

Error info persistentPreferredActivities 4

And just a google search does not give me any clue how to resolve this.

When I set installType as KIOSK, I always got this error. My clue was that my policy lacks of PersistentPreferredActivity json block. I've added it, and I still got this error. What's interesting, there's a note: "Note: To set up a kiosk, use InstallType to KIOSK rather than use persistent preferred activities." So we do not need PersistentPreferredActivity. But I do not understand the error then.

Moving on. I've tried to make kiosk mode by setting kioskCustomLauncherEnabled to true. I set "installType": "AVAILABLE", so I can run the app from Android Studio.
I applied the policy on a device successfully. When I try to open my app's Kiosk Activity I have "App is not device owner" Toast.

Basically, what I need is probably lockTaskAllowed modifier, but it's deprecated.

Could somebody help me to make the device policy for KIOSK app, please?

Body:
Take note that KIOSK mode only works on fully managed devices. For a device to be fully managed, it must be provisioned from a setup wizard by using QR code containing an enrollment token or by other supported enrollment methods.

To be able to use the app in a policy, it must be available in Google Play. It should either be a public app or a private app that is made available to the enterprise (ID) you are managing with the Android Management API.

Here's the difference between "installType": "KIOSK" and kioskCustomLauncherEnabled:

"installType": "KIOSK" is used to pin a single app to the screen

policy_json = '''
{
  "applications": [
  {
    "packageName": "com.google.android.gm",
    "installType": "KIOSK",
    "defaultPermissionPolicy": "GRANT"
  }
],
  "debuggingFeaturesAllowed": true
}
'''

Now, if you want to use a set of apps in KIOSK mode you can use kioskCustomLauncherEnabled

policy_json = '''
{
  "applications": [
    {
    "packageName": "com.android.chrome",
    "installType": "FORCE_INSTALLED",
    "defaultPermissionPolicy": "GRANT"
  },
  {
    "packageName": "com.google.android.gm",
    "installType": "FORCE_INSTALLED",
    "defaultPermissionPolicy": "GRANT"
  }
],
  "debuggingFeaturesAllowed": true,
  "kioskCustomLauncherEnabled": true,
  "keyguardDisabled": true
}
'''


问:
Adding text to a pdf?
So I have a template pdf for an agenda, what I want to know is how do I detect where the date should be.

Lets say in the template there is the word “DATE:”.

After that I want add the corresponding date/text next to that space so I detect “DATE:” and after writing it looks something like “DATE: 13/02/2020” and save it as a new pdf

答:
You tagged your question both java and python-3.x. That makes it very broad. My answer, therefore, also is generic, not specific. In general you should decide which language you ask for.

For your task you will need to do two things,

first apply text extraction with coordinates to your pdf, search for that DATE marker in the text, and determine the coordinates right after that text piece; some libraries allow a shortcut and have routines that only extract text matching a regular expressions and its coordinates;

then add text to your content at those coordinates.

Neither java nor python have explicit pdf support in their core. Thus, for your task you'll have to choose a pdf library for those tasks. (Theoretically you could try and implement your own pdf processing routines, but the pdf format is quite complex, so in general that would take very long.)

So you first should check which general purpose pdf library for your chosen language appears most appropriate for those tasks and your other requirements (like licensing). There are many questions and answers on stack overflow concerning text extraction which may help you in choosing.

Some words of warning, though, not all pdfs allow proper text extraction. There are pdf generators which don't add the information required for text extraction to pdfs; some actually even add misleading information. Thus, you might have to reject some templates. Alternatively, if the template is fixed, simply determine the correct coordinates for text insertion by measuring in a pdf viewer or by trial and error.

And if you still have influence on the requirements, propose to use templates with pdf AcroForm form fields. Form field fill-in allows more control for the template designer concerning the positioning and styling of the fill-ins, and fill-in is easier than the process outlined above. If you don't want form fields in the result pdfs, simply flatten the forms after fill-in.

Title: Adding text to a pdf?