问:
sql server select column by number
Can I select specific columns by the number of the columns in SQL?
Something like</p>
```<code>SELECT columns(0), columns(3), columns(5), columns(8) FROM TABLE
</code>```

答:
i did with this query</p>

```<code>declare @colCoun int
SELECT  @colCoun =COUNT(*)   -- get column count in your table
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_catalog = 'YOUR_DB_NAME'    AND table_name = 'YOUR_TABLE'

CREATE TABLE #temp([1] VARCHAR(max))

if(@colCoun>1)
BEGIN
DECLARE @cnt INT = 2;
WHILE @cnt <= @colCoun
 BEGIN
 Exec ('ALTER TABLE #temp ADD ['+ @cnt +'] varchar(max)')
 SET @cnt = @cnt + 1;
 END
END

insert into #temp
select * from YOUR_TABLE

select [1],[2] from #temp -- select your own column number in range of table
</code>```

Title: sql server select column by number

Body:
Can I select specific columns by the number of the columns in SQL?
Something like

SELECT columns(0), columns(3), columns(5), columns(8) FROM TABLE

Body:
i did with this query

declare @colCoun int
SELECT  @colCoun =COUNT(*)   -- get column count in your table
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_catalog = 'YOUR_DB_NAME'    AND table_name = 'YOUR_TABLE'

CREATE TABLE #temp([1] VARCHAR(max))

if(@colCoun>1)
BEGIN
DECLARE @cnt INT = 2;
WHILE @cnt <= @colCoun
 BEGIN
 Exec ('ALTER TABLE #temp ADD ['+ @cnt +'] varchar(max)')
 SET @cnt = @cnt + 1;
 END
END

insert into #temp
select * from YOUR_TABLE

select [1],[2] from #temp -- select your own column number in range of table


来源: stackexchange

问:
Installing Ubuntu on windows
I have partitioned my drive and now I want to install ubuntu into my drive c:. Would it erase my files in drive D:?

I was currently running windows 10

答:
Since you are installing Ubuntu in your C: drive, it should not affect your D: drive in any way. While installing Ubuntu, you would be prompted to choosing the location of Installation. At that time, you have to select the C: drive partition and not the D: drive one or else it will format the D: drive instead.
Hope this helps!
Have a nice day!!</p>

ContentLicense: CC BY-SA 4.0

Title: Installing Ubuntu on windows


问:
Error-I can't open a new Qt project in VS2019
I've installed Qt 5.12.6 and VS2019, as well as VS Qt tools.
after I created a new Qt empty application,
I get the error!

== Qt Visual Studio Tools version 2.4.3

Initialized in: 3164.53 msecs
   Main (UI) thread: 116.9 msecs

QtApplication5.vcxproj: background build FAILED!
QtApplication5.vcxproj: background build FAILED!

It'd be appreciated if u could solve my prob:)

答: I think this problem came from Qt version. Try to install older Qt versions then 5.12.6 and check whether it works</p>


问:
Pandas remove the row index from the pandas dataframe
i have a dataframe with the data as follows

```<code>  id  Name   Age
0  1  XXX    30
</code>```

and i have to remove the 0(the row index value) from the dataframe.

I have tried the folowing

```<code>df.reset_index(inplace=True) # Resets the index, makes factor a column
df.drop("Factor",axis=1,inplace=True)
</code>```

but it is not removing the 0.

i want output like:

```<code>id  Name   Age
 1  XXX    30
</code>```

答:
You can use the pandas function set_index

```<code>df.set_index('id', inplace=True, drop=True)
</code>```

Body:
i have a dataframe with the data as follows

  id  Name   Age
0  1  XXX    30

and i have to remove the 0(the row index value) from the dataframe.

I have tried the folowing

df.reset_index(inplace=True) # Resets the index, makes factor a column
df.drop("Factor",axis=1,inplace=True)

but it is not removing the 0.

i want output like:

id  Name   Age
 1  XXX    30

Body:
You can use the pandas function set_index

df.set_index('id', inplace=True, drop=True)


问:
Facing problem while integrating voice assistant in rasa chatbot
I was following this tutorial to integrate voice assistant in my chatbot. When I was in the Implementing the text-to-speech component stage, I have downloaded deepspeech_test_prediction.py file and kept it inside deepspeech_test_prediction.py file and ran this command.

```<code>python deepspeech_test_prediction.py
</code>```

After this, I am facing this error.

How can I solve this problem?

I had my headphone plugged in my device.

答: It seems like your input/output audio device isn't being recognised properly by pyaudio. There's steps described here on how to check the config of pyaudio, and potential steps on how to resolve it here

Body:
I was following this tutorial to integrate voice assistant in my chatbot. When I was in the Implementing the text-to-speech component stage, I have downloaded deepspeech_test_prediction.py file and kept it inside deepspeech_test_prediction.py file and ran this command.

python deepspeech_test_prediction.py

After this, I am facing this error.

How can I solve this problem?

I had my headphone plugged in my device.


问:
Access headers in AWS API Gateway using HTTP Proxy?
I'm using AWS API Gateway and it's HTTP Proxy,

I need to pass Authorization header to my endpoint through AWS API Gateway

Things I've tried:

Setting Method Request like so,

Integration Request setup

This doesn't work, my app doesn't receive the Authorization header,

Also I've tried using mapping template

```<code>{
  "method": "$context.httpMethod",
  "body" : $input.json('$'),
  "headers": {
    #foreach($param in $input.params().header.keySet())
    "$param": "$util.escapeJavaScript($input.params().header.get($param))" #if($foreach.hasNext),#end

    #end
  },
  "queryParams": {
    #foreach($param in $input.params().querystring.keySet())
    "$param": "$util.escapeJavaScript($input.params().querystring.get($param))" #if($foreach.hasNext),#end

    #end
  },
  "pathParams": {
    #foreach($param in $input.params().path.keySet())
    "$param": "$util.escapeJavaScript($input.params().path.get($param))" #if($foreach.hasNext),#end

    #end
  }
}
</code>```

This also doesn't work.

How can this be accomplished?

答:
Recently I had to try using an API Gateway HTTP proxy to pass an AWS SigV4 HTTP request to an endpoint.
After testing and debugging found that the Authorization is being consumed and not passed!
So while sending the request to the API Gateway - I sent Authorization and a copy of the Authorization as another header "myauth". (I was able to do this since the request is coming from my own client.)

In the method request I added Authorization and myauth as HTTP Headers
Method Request - HTTP Headers

In the Integration Request - HTTP Headers I mapped myauth to Authorization before it was forwarded to the endpoint

Integration Request - HTTP Headers

Dont know if this is the best way to do this or if there could be any potential issues but this worked! Hope this helps someone or gives some ideas.

Body:
I'm using AWS API Gateway and it's HTTP Proxy,

I need to pass Authorization header to my endpoint through AWS API Gateway

Things I've tried:

Setting Method Request like so,

Integration Request setup

This doesn't work, my app doesn't receive the Authorization header,

Also I've tried using mapping template

{
  "method": "$context.httpMethod",
  "body" : $input.json('$'),
  "headers": {
    #foreach($param in $input.params().header.keySet())
    "$param": "$util.escapeJavaScript($input.params().header.get($param))" #if($foreach.hasNext),#end

    #end
  },
  "queryParams": {
    #foreach($param in $input.params().querystring.keySet())
    "$param": "$util.escapeJavaScript($input.params().querystring.get($param))" #if($foreach.hasNext),#end

    #end
  },
  "pathParams": {
    #foreach($param in $input.params().path.keySet())
    "$param": "$util.escapeJavaScript($input.params().path.get($param))" #if($foreach.hasNext),#end

    #end
  }
}

This also doesn't work.

How can this be accomplished?


问:
Laravel exception throwing
How to throw an exception in Laravel 5.1. I want to simply throw a custom exception with 400 response code. I don't want to do try and catch. I simply want to throw the exception. Should I first create a class based on the Exception class and then throw it? How do I add a custom message and a response code?</p>

答:
You can create a custom .php class in your app/Exceptions folder, that would look like something like this:

```<code>class CustomException extends \Exception
{
    public function report(CustomException $exception)
    {
        parent::report($exception);
    }
}
</code>```

And then, you can use it like this:

```<code>throw new CustomException('Your custom message!', 400);
</code>```

You can read more on official documentation.

Title: Laravel exception throwing

Body:
You can create a custom .php class in your app/Exceptions folder, that would look like something like this:

class CustomException extends \Exception
{
    public function report(CustomException $exception)
    {
        parent::report($exception);
    }
}

And then, you can use it like this:

throw new CustomException('Your custom message!', 400);

You can read more on official documentation.


问:
trying to debug npapi plugin in Chrome and Firefox , without success what is the right way?
i build working npapi pluging using firebreath framework , and its working just fine.

i compiled in debug mode . did regsvr32 myddl.dll and restart the Chrome browser.

now in visual studio 2008 express and did attached to process attached to Chrome process

but when i try to set breakpoint in the dll source code it gives me the error:

The breakpoint will not currently be
  hit. No symbols have been loaded for
  this document.

why this is the source of the plugin and its in debug mode .

this is also happen when i try with firefox browser , so i guess its something with my visual studio configuration

答:
This is something I have noticed recently...

Please check your settings in the configuration manager. Make sure you have set this up for your project in debug mode so it know where to look for your symbols.

ContentLicense: CC BY-SA 3.0


问:
Serializing message with protobuf for akka actor which contains serializable data
I have a persistent actor which can receive one type of command Persist(event) where event is a type of trait Event (there are numerous implementations of it). And on success, this reponds with Persisted(event) to the sender.

The event itself is serializable since this is the data we store in persistence storage and the serialization is implemented with a custom serializer which internally uses classes generated from google protobuf .proto files. And this custom serializer is configured in application.conf and bound to the base trait Event. This is already working fine.

Note: The implementations of Event are not classes generated by protobuf. They are normal scala classes and they have a protobuf equivalent of them too, but that's mapped through the custom serializer that's bound to the base Event type. This was done by my predecessors for versioning (which probably isn't required because this can be handled with plain protobuf classes + custom serialization combi too, but that's a different matter) and I don't wish to change that atm.

We're now trying to implement cluster sharding for this actor which also means that my commands (viz. Persist and Persisted) also need to be serializable since they may be forwarded to other nodes.

This is the domain model :

```<code>sealed trait PersistenceCommand {
  def event: Event
}

final case class Persisted(event: Event) extends PersistenceCommand
final case class Persist(event: Event) extends PersistenceCommand
</code>```

Problem is, I do not see an elegent way to make it serializable. Following are the options I have considered

Approach 1. Define a new proto file for Persist and Persisted, but what do I use as the datatype for event? I didn't find a way to define something like this :

```<code>  message Persist {
   "com.example.Event" event = 1 // this doesn't work
   }
</code>```

Such that I can use existing Scala trait Event as a data type. If this works, I guess (it's far fetched though) I could bind the generated code (After compiling this proto file) to akka's inbuilt serializer for google protobuf and it may work. The note above explains why I cannot use oneof construct in my proto file.

Approach 2. This is what I've implemented and it works (but I don't like it)

Basically, I wrote a new serializer for the commands and delegated seraizalition and de-serialization of event part of the command to the existing serializer.

```<code>class PersistenceCommandSerializer extends SerializerWithStringManifest {
  val eventSerializer: ManifestAwareEventSerializer = new ManifestAwareEventSerializer()

  val PersistManifest   = Persist.getClass.getName
  val PersistedManifest = Persisted.getClass.getName
  val Separator         = "~"

  override def identifier: Int = 808653986

  override def manifest(o: AnyRef): String = o match {
    case Persist(event)   => s"$PersistManifest$Separator${eventSerializer.manifest(event)}"
    case Persisted(event) => s"$PersistedManifest$Separator${eventSerializer.manifest(event)}"
  }

  override def toBinary(o: AnyRef): Array[Byte] = o match {
    case command: PersistenceCommand => eventSerializer.toBinary(command.event)
  }

  override def fromBinary(bytes: Array[Byte], manifest: String): AnyRef = {
    val (commandManifest, dataManifest) = splitIntoCommandAndDataManifests(manifest)
    val event                           = eventSerializer.fromBinary(bytes, dataManifest).asInstanceOf[Event]
    commandManifest match {
      case PersistManifest =>
        Persist(event)
      case PersistedManifest =>
        Persisted(event)
    }
  }

  private def splitIntoCommandAndDataManifests(manifest: String) = {
    val commandAndDataManifests = manifest.split(Separator)
    (commandAndDataManifests(0), commandAndDataManifests(1))
  }
}
</code>```

Problem with this approach is the thing I'm doing in def manifest and in def fromBinary. I had to make sure that I have the command's manifest as well as the event's manifest while serializing and de-serializing. Hence, I had to use ~ as a separator - sort of, my custom serialization technique for the manifest information.

Is there a better or perhaps, a right way, to implement this?

For context: I'm using ScalaPB for generating scala classes from .proto files and classic akka actors.

Any kind of guidance is hugely appreciated!

答:
If you delegate serialization of the nested object to whichever serializer you have configured the nested field should have bytes for the serialized data but also an int32 with the id of the used serializer and bytes for the message manifest. This ensures that you will be able to version/replace the nested serializers which is important for data that will be stored for a longer time period.

You can see how this is done internally in Akka for our own wire formats here: https://github.com/akka/akka/blob/6bf20f4117a8c27f8bd412228424caafe76a89eb/akka-remote/src/main/protobuf/WireFormats.proto#L48 and here https://github.com/akka/akka/blob/6bf20f4117a8c27f8bd412228424caafe76a89eb/akka-remote/src/main/scala/akka/remote/MessageSerializer.scala#L45

Body:
I have a persistent actor which can receive one type of command Persist(event) where event is a type of trait Event (there are numerous implementations of it). And on success, this reponds with Persisted(event) to the sender.

The event itself is serializable since this is the data we store in persistence storage and the serialization is implemented with a custom serializer which internally uses classes generated from google protobuf .proto files. And this custom serializer is configured in application.conf and bound to the base trait Event. This is already working fine.

Note: The implementations of Event are not classes generated by protobuf. They are normal scala classes and they have a protobuf equivalent of them too, but that's mapped through the custom serializer that's bound to the base Event type. This was done by my predecessors for versioning (which probably isn't required because this can be handled with plain protobuf classes + custom serialization combi too, but that's a different matter) and I don't wish to change that atm.

We're now trying to implement cluster sharding for this actor which also means that my commands (viz. Persist and Persisted) also need to be serializable since they may be forwarded to other nodes.

This is the domain model :

sealed trait PersistenceCommand {
  def event: Event
}

final case class Persisted(event: Event) extends PersistenceCommand
final case class Persist(event: Event) extends PersistenceCommand

Problem is, I do not see an elegent way to make it serializable. Following are the options I have considered

Approach 1. Define a new proto file for Persist and Persisted, but what do I use as the datatype for event? I didn't find a way to define something like this :

  message Persist {
   "com.example.Event" event = 1 // this doesn't work
   }

Such that I can use existing Scala trait Event as a data type. If this works, I guess (it's far fetched though) I could bind the generated code (After compiling this proto file) to akka's inbuilt serializer for google protobuf and it may work. The note above explains why I cannot use oneof construct in my proto file.

Approach 2. This is what I've implemented and it works (but I don't like it)

Basically, I wrote a new serializer for the commands and delegated seraizalition and de-serialization of event part of the command to the existing serializer.

class PersistenceCommandSerializer extends SerializerWithStringManifest {
  val eventSerializer: ManifestAwareEventSerializer = new ManifestAwareEventSerializer()

  val PersistManifest   = Persist.getClass.getName
  val PersistedManifest = Persisted.getClass.getName
  val Separator         = "~"

  override def identifier: Int = 808653986

  override def manifest(o: AnyRef): String = o match {
    case Persist(event)   => s"$PersistManifest$Separator${eventSerializer.manifest(event)}"
    case Persisted(event) => s"$PersistedManifest$Separator${eventSerializer.manifest(event)}"
  }

  override def toBinary(o: AnyRef): Array[Byte] = o match {
    case command: PersistenceCommand => eventSerializer.toBinary(command.event)
  }

  override def fromBinary(bytes: Array[Byte], manifest: String): AnyRef = {
    val (commandManifest, dataManifest) = splitIntoCommandAndDataManifests(manifest)
    val event                           = eventSerializer.fromBinary(bytes, dataManifest).asInstanceOf[Event]
    commandManifest match {
      case PersistManifest =>
        Persist(event)
      case PersistedManifest =>
        Persisted(event)
    }
  }

  private def splitIntoCommandAndDataManifests(manifest: String) = {
    val commandAndDataManifests = manifest.split(Separator)
    (commandAndDataManifests(0), commandAndDataManifests(1))
  }
}

Problem with this approach is the thing I'm doing in def manifest and in def fromBinary. I had to make sure that I have the command's manifest as well as the event's manifest while serializing and de-serializing. Hence, I had to use ~ as a separator - sort of, my custom serialization technique for the manifest information.

Is there a better or perhaps, a right way, to implement this?

For context: I'm using ScalaPB for generating scala classes from .proto files and classic akka actors.

Any kind of guidance is hugely appreciated!


问:
Get cookie value in java
I've initialized cooke like this in my JSP,

```<code>String timeStamp = new SimpleDateFormat("dd:MM:yyyy_HH:mm:ss:SSS").format(Calendar.getInstance().getTime());
timeStamp = timeStamp + ":" + System.nanoTime();
String loc = "/u/poolla/workspace/FirstServlet/WebContent/WEB-INF/"+timeStamp;
Cookie thecookie = new Cookie("thecookie", loc);
thecookie.setMaxAge(60*60*24);
response.addCookie(thecookie);
</code>```

So, all the cookies created will have the same name, but different value for different user access time.

At the ending of java servlet I want to deactivate/kill the cookie that has been passed at the beginning of java servlet and say if they are 5 users using the system in parallel how will I know which cookie to deactivate for which user in the last of my.java?

for example, consider

```<code>User 1 : cookie name `thecookie` value `AAA`
User 2 : cookie name `thecookie` value `BBB`
User 3 : cookie name `thecookie` value `CCC`
User 4 : cookie name `thecookie` value `DDD`
User 5 : cookie name `thecookie` value `EEE`
</code>```

Now, at the end of my.java servlet I want to deactivate the cookie with value CCC that has been assigned at the beginning of my.java without disturbing other cookie values, how to do this?

答:
In kotlin it will be much shorter:</p>

```<code>fun HttpServletRequest.getCookie( name: String) = cookies.firstOrNull { it.name == name }

</code>```

Title: Get cookie value in java

Body:
I've initialized cooke like this in my JSP,

String timeStamp = new SimpleDateFormat("dd:MM:yyyy_HH:mm:ss:SSS").format(Calendar.getInstance().getTime());
timeStamp = timeStamp + ":" + System.nanoTime();
String loc = "/u/poolla/workspace/FirstServlet/WebContent/WEB-INF/"+timeStamp;
Cookie thecookie = new Cookie("thecookie", loc);
thecookie.setMaxAge(60*60*24);
response.addCookie(thecookie);

So, all the cookies created will have the same name, but different value for different user access time.

At the ending of java servlet I want to deactivate/kill the cookie that has been passed at the beginning of java servlet and say if they are 5 users using the system in parallel how will I know which cookie to deactivate for which user in the last of my.java?

for example, consider

User 1 : cookie name `thecookie` value `AAA`
User 2 : cookie name `thecookie` value `BBB`
User 3 : cookie name `thecookie` value `CCC`
User 4 : cookie name `thecookie` value `DDD`
User 5 : cookie name `thecookie` value `EEE`

Now, at the end of my.java servlet I want to deactivate the cookie with value CCC that has been assigned at the beginning of my.java without disturbing other cookie values, how to do this?

Body:
In kotlin it will be much shorter:

fun HttpServletRequest.getCookie( name: String) = cookies.firstOrNull { it.name == name }


问:
java.lang.IllegalArgumentException: secret key byte array cannot be null or empty
I am using spring-boot with JWT.

Application.properties

```<code>jwt.secret=xyz
</code>```

Controller.java

```<code>@PostMapping(path = "/authenticate")
    public ResponseEntity<?> createAuthenticationToken(@RequestBody JwtRequest authenticationRequest) throws Exception {

        authenticate(authenticationRequest.getUsername(), authenticationRequest.getPassword());

        final UserDetails userDetails = userDetailsService.loadUserByUsername(authenticationRequest.getUsername());

        final String token = jwtTokenUtil.generateToken(userDetails);

        return ResponseEntity.ok(new JwtResponse(token));
    }
</code>```

JwtTokenUtil.java

```<code>    @Value("${jwt.secret}")
    private String secret;
    public String generateToken(UserDetails userDetails) {
            Map<String, Object> claims = new HashMap<>();
            return doGenerateToken(claims, userDetails.getUsername());
        }

        private String doGenerateToken(Map<String, Object> claims, String subject) {

            return Jwts.builder().setClaims(claims).setSubject(subject).setIssuedAt(new Date(System.currentTimeMillis()))
                    .setExpiration(new Date(System.currentTimeMillis() + JWT_TOKEN_VALIDITY*1000)).signWith(SignatureAlgorithm.HS512, secret).compact();
        }
</code>```

in the jwtTokenUtil.generateToken code I am getting the following error

```<code>ERROR o.a.c.c.C.[.[.[.[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.IllegalArgumentException: secret key byte array cannot be null or empty.] with root cause
java.lang.IllegalArgumentException: secret key byte array cannot be null or empty.
    at io.jsonwebtoken.lang.Assert.notEmpty(Assert.java:204)
    at io.jsonwebtoken.impl.DefaultJwtBuilder.signWith(DefaultJwtBuilder.java:88)
    at io.jsonwebtoken.impl.DefaultJwtBuilder.signWith(DefaultJwtBuilder.java:100)
    at net.javaguides.springboot.helloworldapp.config.JwtTokenUtil.doGenerateToken(JwtTokenUtil.java:66)
    at net.javaguides.springboot.helloworldapp.config.JwtTokenUtil.generateToken(JwtTokenUtil.java:60)
    at net.javaguides.springboot.helloworldapp.controller.BasicAuthController.createAuthenticationToken(BasicAuthController.java:75)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:189)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:800)
</code>```

When I have given my credentials I am getting this error. the application is already validated my credentials, but while generating the token I am getting this error.

UPDATE:-

While debugging I have seen the internal code like below

```<code> @Override
    public JwtBuilder signWith(SignatureAlgorithm alg, String base64EncodedSecretKey) {
        Assert.hasText(base64EncodedSecretKey, "base64-encoded secret key cannot be null or empty.");
        Assert.isTrue(alg.isHmac(), "Base64-encoded key bytes may only be specified for HMAC signatures.  If using RSA or Elliptic Curve, use the signWith(SignatureAlgorithm, Key) method instead.");
        byte[] bytes = TextCodec.BASE64.decode(base64EncodedSecretKey);
        return signWith(alg, bytes);
    }
</code>```

In this bytes I am getting null

答:
I think your key need to be base64 encoded
See Source:
https://github.com/jwtk/jjwt/blob/master/impl/src/main/java/io/jsonwebtoken/impl/DefaultJwtBuilder.java#L138

Try following:

```<code>    private String doGenerateToken(Map<String, Object> claims, String subject) {

String encodedString = Base64.getEncoder().encodeToString(secret.getBytes())
        return Jwts.builder().setClaims(claims).setSubject(subject).setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis() + JWT_TOKEN_VALIDITY*1000)).signWith(SignatureAlgorithm.HS512, encodedString ).compact();
    }
</code>```

Body:
I am using spring-boot with JWT.

Application.properties

jwt.secret=xyz

Controller.java

@PostMapping(path = "/authenticate")
    public ResponseEntity<?> createAuthenticationToken(@RequestBody JwtRequest authenticationRequest) throws Exception {

        authenticate(authenticationRequest.getUsername(), authenticationRequest.getPassword());

        final UserDetails userDetails = userDetailsService.loadUserByUsername(authenticationRequest.getUsername());

        final String token = jwtTokenUtil.generateToken(userDetails);

        return ResponseEntity.ok(new JwtResponse(token));
    }

JwtTokenUtil.java

    @Value("${jwt.secret}")
    private String secret;
    public String generateToken(UserDetails userDetails) {
            Map<String, Object> claims = new HashMap<>();
            return doGenerateToken(claims, userDetails.getUsername());
        }

        private String doGenerateToken(Map<String, Object> claims, String subject) {

            return Jwts.builder().setClaims(claims).setSubject(subject).setIssuedAt(new Date(System.currentTimeMillis()))
                    .setExpiration(new Date(System.currentTimeMillis() + JWT_TOKEN_VALIDITY*1000)).signWith(SignatureAlgorithm.HS512, secret).compact();
        }

in the jwtTokenUtil.generateToken code I am getting the following error

ERROR o.a.c.c.C.[.[.[.[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.IllegalArgumentException: secret key byte array cannot be null or empty.] with root cause
java.lang.IllegalArgumentException: secret key byte array cannot be null or empty.
    at io.jsonwebtoken.lang.Assert.notEmpty(Assert.java:204)
    at io.jsonwebtoken.impl.DefaultJwtBuilder.signWith(DefaultJwtBuilder.java:88)
    at io.jsonwebtoken.impl.DefaultJwtBuilder.signWith(DefaultJwtBuilder.java:100)
    at net.javaguides.springboot.helloworldapp.config.JwtTokenUtil.doGenerateToken(JwtTokenUtil.java:66)
    at net.javaguides.springboot.helloworldapp.config.JwtTokenUtil.generateToken(JwtTokenUtil.java:60)
    at net.javaguides.springboot.helloworldapp.controller.BasicAuthController.createAuthenticationToken(BasicAuthController.java:75)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:189)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:800)

When I have given my credentials I am getting this error. the application is already validated my credentials, but while generating the token I am getting this error.

UPDATE:-

While debugging I have seen the internal code like below

 @Override
    public JwtBuilder signWith(SignatureAlgorithm alg, String base64EncodedSecretKey) {
        Assert.hasText(base64EncodedSecretKey, "base64-encoded secret key cannot be null or empty.");
        Assert.isTrue(alg.isHmac(), "Base64-encoded key bytes may only be specified for HMAC signatures.  If using RSA or Elliptic Curve, use the signWith(SignatureAlgorithm, Key) method instead.");
        byte[] bytes = TextCodec.BASE64.decode(base64EncodedSecretKey);
        return signWith(alg, bytes);
    }

In this bytes I am getting null

Body:
I think your key need to be base64 encoded
See Source:
https://github.com/jwtk/jjwt/blob/master/impl/src/main/java/io/jsonwebtoken/impl/DefaultJwtBuilder.java#L138

Try following:

    private String doGenerateToken(Map<String, Object> claims, String subject) {

String encodedString = Base64.getEncoder().encodeToString(secret.getBytes())
        return Jwts.builder().setClaims(claims).setSubject(subject).setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis() + JWT_TOKEN_VALIDITY*1000)).signWith(SignatureAlgorithm.HS512, encodedString ).compact();
    }


问:
How to Compare two files using AWK or GREP
So I have two questions, I have two files where I am trying to sort and filter. In these two files they each have two columns wherein file1 there is IP and Port and in file2 there is domain and IP.

```<code>file1:

Address,Port
1.2.3.4,8080
4.5.6.7,80
6.7.8.9,443

file2:

Domain,IP
google.com,1.2.3.4
google.fe,6.7.8.9
admin.ko,3.2.4.5
</code>```

So the first question: I want to find IPs in file1 that don't match any IP's located in file2.

I have tried using awk, and here is what I used:

```<code>awk -F',' FNR==NR{ a[$2]; next } !($1 in a)' file2 file1
</code>```

So I really don't understand awk really well, so could someone also assist me in understanding each section of that awk command you provide :)

```<code>Desired output:

Address,Port,Status
1.2.3.4,8080,Present
4.5.6.7,80,Not-Present
6.7.8.9,443,Present
</code>```

The next question, I have no idea how to do it so kindly assist.

Second question: so I want to list the same desired Output as the first one but this time I want to add the domain column.

```<code>Desired output:

Address,Port,Domain,Status
1.2.3.4,8080,google.com,Present
4.5.6.7,80,NULL,Not-Present
6.7.8.9,443,google.fe,Present
</code>```

Thank you in advance.

答:
Following is the complete explanation of your mentioned code, please go through it.

```<code>awk -F',' '    ##Setting awk program here and setting comma as field separator for all lines here.
FNR==NR{       ##Checking condition if FNR==NR which will be TRUE when first Input_file named file2 is being read.
  a[$2]        ##Creating an array named a with index $2 of current line here.
  next         ##next will skip all further statements from here.
}
!($1 in a)     ##Checking condition if $1 is NOT present from Input_file1 then print that line from Input_file1.
' file2 file1  ##Mentioning Input_file names here.
</code>```

For your 2nd question you could try following code.

```<code>awk '
BEGIN{
  FS=OFS=","
}
FNR==1{
  if(++count==1){
    val=$0
  }
  if(++count==2){
    print val,$1,"Status"
  }
  next
}
FNR==NR{
  a[$2]=$1
  next
}
{
  print $0,$1 in a?"Present":"Not-Present"
}
' file2  file1
</code>```

Body:
So I have two questions, I have two files where I am trying to sort and filter. In these two files they each have two columns wherein file1 there is IP and Port and in file2 there is domain and IP.

file1:

Address,Port
1.2.3.4,8080
4.5.6.7,80
6.7.8.9,443

file2:

Domain,IP
google.com,1.2.3.4
google.fe,6.7.8.9
admin.ko,3.2.4.5

So the first question: I want to find IPs in file1 that don't match any IP's located in file2.

I have tried using awk, and here is what I used:

awk -F',' FNR==NR{ a[$2]; next } !($1 in a)' file2 file1

So I really don't understand awk really well, so could someone also assist me in understanding each section of that awk command you provide :)

Desired output:

Address,Port,Status
1.2.3.4,8080,Present
4.5.6.7,80,Not-Present
6.7.8.9,443,Present

The next question, I have no idea how to do it so kindly assist.

Second question: so I want to list the same desired Output as the first one but this time I want to add the domain column.

Desired output:

Address,Port,Domain,Status
1.2.3.4,8080,google.com,Present
4.5.6.7,80,NULL,Not-Present
6.7.8.9,443,google.fe,Present

Thank you in advance.

Body:
Following is the complete explanation of your mentioned code, please go through it.

awk -F',' '    ##Setting awk program here and setting comma as field separator for all lines here.
FNR==NR{       ##Checking condition if FNR==NR which will be TRUE when first Input_file named file2 is being read.
  a[$2]        ##Creating an array named a with index $2 of current line here.
  next         ##next will skip all further statements from here.
}
!($1 in a)     ##Checking condition if $1 is NOT present from Input_file1 then print that line from Input_file1.
' file2 file1  ##Mentioning Input_file names here.

For your 2nd question you could try following code.

awk '
BEGIN{
  FS=OFS=","
}
FNR==1{
  if(++count==1){
    val=$0
  }
  if(++count==2){
    print val,$1,"Status"
  }
  next
}
FNR==NR{
  a[$2]=$1
  next
}
{
  print $0,$1 in a?"Present":"Not-Present"
}
' file2  file1


问:
Serilog in Windows-Service not writing to logfile
I am using Serilog within an TopShelf Service, logging to the console and a rolling file. When running the service in a console my messages are written to the logfile, but when I install the service and run it no logging occurs. Is there anything special I need to configure? The file is written to the binaries folder under ".\logs\log-{date}.txt".</p>

答:
You can also use something like this (When you want to create a Windows Service and Serilog):</p>

```<code>var builder = new ConfigurationBuilder()
           .AddJsonFile($@"{Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)}\appsettings.json", optional: true, reloadOnChange: true)
           .AddEnvironmentVariables();
</code>```

Body:
You can also use something like this (When you want to create a Windows Service and Serilog):

var builder = new ConfigurationBuilder()
           .AddJsonFile($@"{Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)}\appsettings.json", optional: true, reloadOnChange: true)
           .AddEnvironmentVariables();


问:
Flatten nested dictionaries, compressing keys
Suppose you have a dictionary like:

```<code>{'a': 1,
 'c': {'a': 2,
       'b': {'x': 5,
             'y' : 10}},
 'd': [1, 2, 3]}
</code>```

How would you go about flattening that into something like:

```<code>{'a': 1,
 'c_a': 2,
 'c_b_x': 5,
 'c_b_y': 10,
 'd': [1, 2, 3]}
</code>```

答:
Code:

```<code>test = {'a': 1, 'c': {'a': 2, 'b': {'x': 5, 'y' : 10}}, 'd': [1, 2, 3]}

def parse_dict(init, lkey=''):
    ret = {}
    for rkey,val in init.items():
        key = lkey+rkey
        if isinstance(val, dict):
            ret.update(parse_dict(val, key+'_'))
        else:
            ret[key] = val
    return ret

print(parse_dict(test,''))
</code>```

Results:

```<code>$ python test.py
{'a': 1, 'c_a': 2, 'c_b_x': 5, 'd': [1, 2, 3], 'c_b_y': 10}
</code>```

I am using python3.2, update for your version of python.

Body:
Suppose you have a dictionary like:

{'a': 1,
 'c': {'a': 2,
       'b': {'x': 5,
             'y' : 10}},
 'd': [1, 2, 3]}

How would you go about flattening that into something like:

{'a': 1,
 'c_a': 2,
 'c_b_x': 5,
 'c_b_y': 10,
 'd': [1, 2, 3]}

Body:
Code:

test = {'a': 1, 'c': {'a': 2, 'b': {'x': 5, 'y' : 10}}, 'd': [1, 2, 3]}

def parse_dict(init, lkey=''):
    ret = {}
    for rkey,val in init.items():
        key = lkey+rkey
        if isinstance(val, dict):
            ret.update(parse_dict(val, key+'_'))
        else:
            ret[key] = val
    return ret

print(parse_dict(test,''))

Results:

$ python test.py
{'a': 1, 'c_a': 2, 'c_b_x': 5, 'd': [1, 2, 3], 'c_b_y': 10}

I am using python3.2, update for your version of python.


问:
DJANGORESTAPI: how to add products with csv file
models.py

```<code>
class Product(models.Model):
    title = models.CharField(max_length=150)
    slug = models.SlugField(unique=True)
    description = models.CharField(max_length=350)
    image = models.ImageField(upload_to='images/')

    def __str__(self):
        return self.title

</code>```

i have '500' numbers of products in my csv file, now i want to upload all the products with csv file and store these name in my database.my concern is how to define my 'views.py' in restapi ?

i just tried with server side rendering, but it failed. it would be great if anyone can help me figure out what I am trying to do.

views.py

```<code>import csv, io
from .models import Product

def profile_upload(request):
    template = "profile_upload.html"
    data = Product.objects.all()
    prompt = {
        'order': 'Order of the CSV should be product_title, sku, slug, image_path, price',
        'profiles': data
              }
    # GET request returns the value of the data with the specified key.
    if request.method == "GET":
        return render(request, template, prompt)
        csv_file = request.FILES['file']    # let's check if it is a csv file
    if not csv_file.name.endswith('.csv'):
        messages.error(request, 'THIS IS NOT A CSV FILE')
        data_set = csv_file.read().decode('UTF-8')    # setup a stream which is when we loop through each line we are able to handle a data in a stream
        io_string = io.StringIO(data_set)
        next(io_string)
        for column in csv.reader(io_string, delimiter=',', quotechar="|"):
            _, created = Product.objects.update_or_create(
                title=column[0],
                slug=column[1],
                description=column[2],
                image=column[3],
            )
        context = {}
        return render(request, template, context)

</code>```

答:
views.py

```<code>import csv, io
from .models import Product

def profile_upload(request):
    template = "profile_upload.html"
    data = Profile.objects.all()
    prompt = {
        'order': 'Order of the CSV should be product_title, sku, slug, image_path, price',
        'profiles': data
              }
    csv_file = ''
    # GET request returns the value of the data with the specified key.
    if request.method == "GET":
        csv_file = request.FILES['file']
        if not csv_file.name.endswith('.csv'):
            messages.error(request, 'THIS IS NOT A CSV FILE')
            data_set = csv_file.read().decode('UTF-8')    # setup a stream which is when we loop through each line we are able to handle a data in a stream
            io_string = io.StringIO(data_set)
            next(io_string)
            for column in csv.reader(io_string, delimiter=',', quotechar="|"):
                _, created = Product.objects.update_or_create(
                    title=column[0],
                    slug=column[1],
                    description=column[2],
                    image=column[3],
                )
            context = {}
        return render(request, template, context)
</code>```

https://medium.com/@simathapa111/how-to-upload-a-csv-file-in-django-3a0d6295f624

try format your csv to this blog or use separator you have on the csv

Body:
models.py

class Product(models.Model):
    title = models.CharField(max_length=150)
    slug = models.SlugField(unique=True)
    description = models.CharField(max_length=350)
    image = models.ImageField(upload_to='images/')

    def __str__(self):
        return self.title

i have '500' numbers of products in my csv file, now i want to upload all the products with csv file and store these name in my database.my concern is how to define my 'views.py' in restapi ?

i just tried with server side rendering, but it failed. it would be great if anyone can help me figure out what I am trying to do.

views.py

import csv, io
from .models import Product

def profile_upload(request):
    template = "profile_upload.html"
    data = Product.objects.all()
    prompt = {
        'order': 'Order of the CSV should be product_title, sku, slug, image_path, price',
        'profiles': data
              }
    # GET request returns the value of the data with the specified key.
    if request.method == "GET":
        return render(request, template, prompt)
        csv_file = request.FILES['file']    # let's check if it is a csv file
    if not csv_file.name.endswith('.csv'):
        messages.error(request, 'THIS IS NOT A CSV FILE')
        data_set = csv_file.read().decode('UTF-8')    # setup a stream which is when we loop through each line we are able to handle a data in a stream
        io_string = io.StringIO(data_set)
        next(io_string)
        for column in csv.reader(io_string, delimiter=',', quotechar="|"):
            _, created = Product.objects.update_or_create(
                title=column[0],
                slug=column[1],
                description=column[2],
                image=column[3],
            )
        context = {}
        return render(request, template, context)

Body:
views.py

import csv, io
from .models import Product

def profile_upload(request):
    template = "profile_upload.html"
    data = Profile.objects.all()
    prompt = {
        'order': 'Order of the CSV should be product_title, sku, slug, image_path, price',
        'profiles': data
              }
    csv_file = ''
    # GET request returns the value of the data with the specified key.
    if request.method == "GET":
        csv_file = request.FILES['file']
        if not csv_file.name.endswith('.csv'):
            messages.error(request, 'THIS IS NOT A CSV FILE')
            data_set = csv_file.read().decode('UTF-8')    # setup a stream which is when we loop through each line we are able to handle a data in a stream
            io_string = io.StringIO(data_set)
            next(io_string)
            for column in csv.reader(io_string, delimiter=',', quotechar="|"):
                _, created = Product.objects.update_or_create(
                    title=column[0],
                    slug=column[1],
                    description=column[2],
                    image=column[3],
                )
            context = {}
        return render(request, template, context)

https://medium.com/@simathapa111/how-to-upload-a-csv-file-in-django-3a0d6295f624

try format your csv to this blog or use separator you have on the csv


问:
Chrome devtools inspector showing blank white screen while debugging with Samsung TV Tizen Web application
I'm debugging Samsung TV Tizen Web Application with Tizen Studio 3.6 and Google Chrome Version 80.0.3987.100 (Official Build) (64-bit). But Chrome Inspector showing black screen.

Chrome path config :

Chrome blank screen :

Please help me out from this issue.

答:
This is compatibility issue due to upstream change in chrome 80 version.
https://groups.google.com/a/chromium.org/forum/#!msg/blink-dev/h-JwMiPUnuU/sl79aLoLBQAJ
https://bugs.chromium.org/p/chromium/issues/detail?id=685385

It will be resolved in the next release of Tizen Studio.
Until then, if you use the options below, inspector will be launched properly.

Go to Window > Preferences > Tizen Studio > Web > Chrome -> Extra parameters :
add "--enable-blink-features=ShadowDOMV0 --enable-blink-features=CustomElementsV0 --user-data-dir=c:\Temp"


问:
instead of click event function can you please change into mouse hover event
<pre class="lang-js prettyprint-override"><code>$(window).ready(i),
$(window).on("resize", i),
$(".sidebartoggler").on("click", function() {
  $("body").hasClass("mini-sidebar")
    ? ($("body").trigger("resize"),
      $(".scroll-sidebar, .slimScrollDiv").css("overflow", "hidden").parent().css("overflow", "visible"),
      $("body").removeClass("mini-sidebar"),
      $(".navbar-brand span").show())
    : ($("body").trigger("resize"),
      $(".scroll-sidebar, .slimScrollDiv").css("overflow-x",  "visible").parent().css("overflow", "visible"),
      $("body").addClass("mini-sidebar"),
      $(".navbar-brand span").hide())
})
</code>```

答:
Something like this? It is in any case easier to change

function toggle() {
  const hasSideBar = $("body").hasClass("mini-sidebar");
  $("body").trigger("resize");
  $(".scroll-sidebar, .slimScrollDiv").css("overflow", hasSideBar?"hidden":"visible").parent().css("overflow", "visible");
  $("body").toggleClass("mini-sidebar",!hasSideBar);  // or just $("body").toggleClass("mini-sidebar");
  $(".navbar-brand span").toggle(hasSideBar);
}

$(function() {
  $(window).on("resize", toggle);
  $(".sidebartoggler").on("hover", toggle);
  toggle();
});
```


问:
DynamoDB access in Lambda@Edge
Need your help in understanding some concepts. I have a web application that uses Lambda@Edge on the CloudFront. This lambda function accesses the DynamoDB - making around 10 independent queries. This generates occasional errors, though it works perfectly when I test the lambda function stand alone. I am not able to make much sense out of the cloudfront logs, and Lambda@Edge does not show up in the CloudWatch.

I have a feeling that the DynamoDB queries are the culprit. (because that is all I am doing in the Lambda function) To make sure, I replicated the data over all regions. But that has not solved the problem. I increased the timeout and memory allocated to the lambda function. But that has not helped in any way. But, reducing the number of DB queries seems to help.

Can you please help me understand this? Is it wrong to make DB queries in the Lambda@Edge? Is there a way to get detailed logs of the Lambda@Edge?

答:
Lambda@Edge logs show up in CloudWatch under the region in which the Lambda was called. I suspect you simply need to go into CloudWatch and change to the correct region to see the logs. If you are calling CloudWatch yourself, this will be the region you are in, not the region you created the Lambda.

Once you have the log you should have much more information to go on.

Title: DynamoDB access in Lambda@Edge


问:
Laravel: Undefined offset 0 in symfony/http-foundation when requiring SimpleSAMLphp
I'm attempting to upgrade dependancies on a simple Laravel 5.7 application that authenticates the user via SimpleSAMLphp, then displays some information it gets from an external API.

It looks like something changed between version 4.3.8 and version 4.4.0 of the symfony/http-foundation library included with Laravel, because when I upgrade this dependency I get the following error:

```<code>ErrorException (E_NOTICE): Undefined offset: 0 …/vendor/symfony/http-foundation/HeaderBag.php 126
</code>```

It looks like this is being triggered by requiring the SimpleSAMLphp service provider autoload file, even if I don't call any methods.

Since this is an extremely simple single page application, I'm just using middleware to handle the SimpleSAMLphp integration:

namespace App\Http\Middleware;

use Closure;

class SimpleSAMLphp
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        /**
         * Load SimpleSAMLphp library
         */
        require_once('redacted/path/simplesaml/lib/_autoload.php');
        $ssphp = new \SimpleSAML\Auth\Simple('service-provider-name');
        $ssphp->requireAuth();

        return $next($request);
    }
}
```

It looks like Symfony HTTP Foundation changed how they are checking for header information in this version (I see extensive changes here: https://github.com/symfony/http-foundation/compare/v4.3.8...v4.4.0), but I don't understand why it is blowing up when SimpleSAMLphp is in the mix.

I'm deep down the rabbit hole on this one - any guidance would be much appreciated!

答:
Duplicate the HeaderBag.php file and override it using composer. Change the get function of the duplicated file to the code below. The only changes here is the isset checker. Then http://shyammakwana.me/php/laravel-override-vendor-classes.html will show you how to override the Headerbag.php file of any vendor using composer. Tested working with SimpleSamlPHP and Laravel. Enjoy!</p>

```<code>public function get($key, $default = null)
{
    $headers = $this->all((string) $key);
    if (2 < \func_num_args()) {
        @trigger_error(sprintf('Passing a third argument to "%s()" is deprecated since Symfony 4.4, use method "all()" instead', __METHOD__), E_USER_DEPRECATED);

        if (!func_get_arg(2)) {
            return $headers;
        }
    }

    if (!$headers || !isset($headers[0])) {
        return $default;
    }

    if (null === $headers[0]) {
        return null;
    }

    return (string) $headers[0];
}
</code>```

Body:
I'm attempting to upgrade dependancies on a simple Laravel 5.7 application that authenticates the user via SimpleSAMLphp, then displays some information it gets from an external API.

It looks like something changed between version 4.3.8 and version 4.4.0 of the symfony/http-foundation library included with Laravel, because when I upgrade this dependency I get the following error:

ErrorException (E_NOTICE): Undefined offset: 0 …/vendor/symfony/http-foundation/HeaderBag.php 126

It looks like this is being triggered by requiring the SimpleSAMLphp service provider autoload file, even if I don't call any methods.

Since this is an extremely simple single page application, I'm just using middleware to handle the SimpleSAMLphp integration:

namespace App\Http\Middleware;

use Closure;

class SimpleSAMLphp
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        /**
         * Load SimpleSAMLphp library
         */
        require_once('redacted/path/simplesaml/lib/_autoload.php');
        $ssphp = new \SimpleSAML\Auth\Simple('service-provider-name');
        $ssphp->requireAuth();

        return $next($request);
    }
}

It looks like Symfony HTTP Foundation changed how they are checking for header information in this version (I see extensive changes here: https://github.com/symfony/http-foundation/compare/v4.3.8...v4.4.0), but I don't understand why it is blowing up when SimpleSAMLphp is in the mix.

I'm deep down the rabbit hole on this one - any guidance would be much appreciated!

Body:
Duplicate the HeaderBag.php file and override it using composer. Change the get function of the duplicated file to the code below. The only changes here is the isset checker. Then http://shyammakwana.me/php/laravel-override-vendor-classes.html will show you how to override the Headerbag.php file of any vendor using composer. Tested working with SimpleSamlPHP and Laravel. Enjoy!

public function get($key, $default = null)
{
    $headers = $this->all((string) $key);
    if (2 < \func_num_args()) {
        @trigger_error(sprintf('Passing a third argument to "%s()" is deprecated since Symfony 4.4, use method "all()" instead', __METHOD__), E_USER_DEPRECATED);

        if (!func_get_arg(2)) {
            return $headers;
        }
    }

    if (!$headers || !isset($headers[0])) {
        return $default;
    }

    if (null === $headers[0]) {
        return null;
    }

    return (string) $headers[0];
}


问:
How to set local notifications once every 28 days starting from a particular date in Swift?
I'm trying to create a local notification in swift every 28 days starting from a given date. For example, if the user enters the date 2020/01/31, I need to create a local notification on 2020/02/28 and so on. How do I do it using Swift 4 in Xcode 11? </p>

答:
Once, you can calculate the date which is 28 days after :

```<code>let formatter = DateFormatter()
    formatter.dateFormat = "dd.MM.yyyy"
    let calculatedDate = formatter.date(from: yourDate)
    let notificationTime = Calendar.current.date(byAdding: .day,value: 28,to: calculatedDate)!
</code>```

And compare it to date which you want. If equals set notification.

Hope it helps...

Body:
Once, you can calculate the date which is 28 days after :

let formatter = DateFormatter()
    formatter.dateFormat = "dd.MM.yyyy"
    let calculatedDate = formatter.date(from: yourDate)
    let notificationTime = Calendar.current.date(byAdding: .day,value: 28,to: calculatedDate)!

And compare it to date which you want. If equals set notification.

Hope it helps...


问:
Why is psycopg2 failing to install correctly on Mac OS Catalina Version 10.15.3
This is the error message I get:

```<code>  Building wheel for psycopg2 (setup.py) ... error
  ERROR: Command errored out with exit status 1:
   command: /Users/macbookpro/Documents/brck/subscription_env/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/b1/wfq4dcls5dbdjq9zl49z_6t40000gp/T/pip-install-6btertcf/psycopg2/setup.py'"'"'; __file__='"'"'/private/var/folders/b1/wfq4dcls5dbdjq9zl49z_6t40000gp/T/pip-install-6btertcf/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /private/var/folders/b1/wfq4dcls5dbdjq9zl49z_6t40000gp/T/pip-wheel-zfvo13ls
       cwd: /private/var/folders/b1/wfq4dcls5dbdjq9zl49z_6t40000gp/T/pip-install-6btertcf/psycopg2/

</code>```

If anyone has a solution please reach out

答:
I answered this by installing psycopg2-binary instead of psycopg2
I referred to this issue: https://github.com/psycopg/psycopg2/issues/674
And this (Python) psycopg2 installation

Body:
This is the error message I get:

  Building wheel for psycopg2 (setup.py) ... error
  ERROR: Command errored out with exit status 1:
   command: /Users/macbookpro/Documents/brck/subscription_env/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/b1/wfq4dcls5dbdjq9zl49z_6t40000gp/T/pip-install-6btertcf/psycopg2/setup.py'"'"'; __file__='"'"'/private/var/folders/b1/wfq4dcls5dbdjq9zl49z_6t40000gp/T/pip-install-6btertcf/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /private/var/folders/b1/wfq4dcls5dbdjq9zl49z_6t40000gp/T/pip-wheel-zfvo13ls
       cwd: /private/var/folders/b1/wfq4dcls5dbdjq9zl49z_6t40000gp/T/pip-install-6btertcf/psycopg2/

If anyone has a solution please reach out


问:
Prometheus-net : callback to update a gauge when /metrics endpoint is called?
I'm not sure I got correctly how prometheus-net should be used but having a gauge that is time related I'd need to be able to update its value when data is being requested via the /metrics endpoint. I thought I might use a timer to updated the gauge but the ideal thing would be to have a callback exposed by prometheus-net to update what need updating just before data is returned.</p>

答:
If anyone needs it, prometheus-net provides the AddBeforeCollectCallback callback for collecting or updating your metrics, gauges, etc. just before Prometheus collects data from you.

From prometheus-net documentation

In some scenarios you may want to only collect data when it is requested by Prometheus. To easily implement this scenario prometheus-net enables you to register a callback before every collection occurs. Register your callback using Metrics.DefaultRegistry.AddBeforeCollectCallback().


问:
How to get date time from UTC date time fromat?
I am getting date time from rest api as like this  "2020-02-13T16:57:13.04 . How can i convert in java for android? So that i can use only date or time separately?

I have tried by this way

```<code>String dateStr = rowsArrayList.get(position).getDisplayDate();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ENGLISH);
df.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = null;
try {
    date = df.parse(dateStr);
    df.setTimeZone(TimeZone.getDefault());
    String formattedDate = df.format(date);
    Log.d("testDate",formattedDate);

} catch (ParseException e) {
    e.printStackTrace();
    Log.d("testDate",e.toString());
}
</code>```

But getting the error

java.text.ParseException: Unparseable date: "2020-02-13T16:57:13.04"

答:
Take out the 'Z' on your format string

This should work:

```<code>SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ENGLISH);
</code>```

Or if you want to keep the milliseconds then use SS:

```<code>SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SS", Locale.ENGLISH);
</code>```

Body:
I am getting date time from rest api as like this  "2020-02-13T16:57:13.04 . How can i convert in java for android? So that i can use only date or time separately?

I have tried by this way

String dateStr = rowsArrayList.get(position).getDisplayDate();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ENGLISH);
df.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = null;
try {
    date = df.parse(dateStr);
    df.setTimeZone(TimeZone.getDefault());
    String formattedDate = df.format(date);
    Log.d("testDate",formattedDate);

} catch (ParseException e) {
    e.printStackTrace();
    Log.d("testDate",e.toString());
}

But getting the error

java.text.ParseException: Unparseable date: "2020-02-13T16:57:13.04"

Body:
Take out the 'Z' on your format string

This should work:

SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ENGLISH);

Or if you want to keep the milliseconds then use SS:

SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SS", Locale.ENGLISH);


Title: Merge List of nested dictionaries

Body:
I have 3 lists as below, which are extracted from a PDF file,

adID = ['9940542', '9940542', '10315065', '10315065', '11211744', '11211744', '11309685', '11309685', '12103490', '12103490', '12103490', '12103490', '12103490', '12103490', '12160150', '12160150']

description = ['Invalid Adjust(Platform Fee)', 'Invalid Adjust(Media Fee)', 'Invalid Adjust(Platform Fee)', 'Invalid Adjust(Media Fee)', 'Invalid Adjust(Platform Fee)', 'Invalid Adjust(Media Fee)', 'Invalid Adjust(Platform Fee)', 'Invalid Adjust(Media Fee)', 'Media Fee', 'Platform Fee', 'Invalid Adjust(Platform Fee)', 'TrueView Budget Adjust (Platofrm Fee)', 'Invalid Adjust(Media Fee)', 'TrueView Budget Adjust (Media Fee)', 'Media Fee', 'Platform Fee']

spendItem = ['-1.00', '-2.00', '-1.00', '-3.00', '-290.00', '-3403.00', '-57.00', '-670.00', '709472.00', '22703.00', '-30.00', '-301.00', '-348.00', '-9376.00', '549173.00', '17573.00']

And I've converted these lists into a list of dictionaries as below

total= [{'9940542': {'Invalid Adjust(Platform Fee)': '-1.00'}},
        {'9940542': {'Invalid Adjust(Media Fee)': '-2.00'}},
        {'10315065': {'Invalid Adjust(Platform Fee)': '-1.00'}},
        {'10315065': {'Invalid Adjust(Media Fee)': '-3.00'}},
        {'11211744': {'Invalid Adjust(Platform Fee)': '-290.00'}},
        {'11211744': {'Invalid Adjust(Media Fee)': '-3403.00'}},
        {'11309685': {'Invalid Adjust(Platform Fee)': '-57.00'}},
        {'11309685': {'Invalid Adjust(Media Fee)': '-670.00'}},
        {'12103490': {'Media Fee': '709472.00'}},
        {'12103490': {'Platform Fee': '22703.00'}},
        {'12103490': {'Invalid Adjust(Platform Fee)': '-30.00'}},
        {'12103490': {'TrueView Budget Adjust (Platofrm Fee)': '-301.00'}},
        {'12103490': {'Invalid Adjust(Media Fee)': '-348.00'}},
        {'12103490': {'TrueView Budget Adjust (Media Fee)': '-9376.00'}},
        {'12160150': {'Media Fee': '549173.00'}},
        {'12160150': {'Platform Fee': '17573.00'}}]

Is there any way to iterate over this list to merge keys and values based on adID. Such as

Expected_result= {'12103490': {'Invalid Adjust(Platform Fee)': '-30.00',TrueView Budget Adjust (Platofrm Fee)': '-301.00','Invalid Adjust(Media Fee)': '-348.00','TrueView Budget Adjust (Media Fee)': '-9376.00'}}

Or is there any better way to merge such data?

Body:
Using dict.setdefault and a simple iteration. You can also use collection.defaultdict

Ex:

total= [{'9940542': {'Invalid Adjust(Platform Fee)': '-1.00'}},
        {'9940542': {'Invalid Adjust(Media Fee)': '-2.00'}},
        {'10315065': {'Invalid Adjust(Platform Fee)': '-1.00'}},
        {'10315065': {'Invalid Adjust(Media Fee)': '-3.00'}},
        {'11211744': {'Invalid Adjust(Platform Fee)': '-290.00'}},
        {'11211744': {'Invalid Adjust(Media Fee)': '-3403.00'}},
        {'11309685': {'Invalid Adjust(Platform Fee)': '-57.00'}},
        {'11309685': {'Invalid Adjust(Media Fee)': '-670.00'}},
        {'12103490': {'Media Fee': '709472.00'}},
        {'12103490': {'Platform Fee': '22703.00'}},
        {'12103490': {'Invalid Adjust(Platform Fee)': '-30.00'}},
        {'12103490': {'TrueView Budget Adjust (Platofrm Fee)': '-301.00'}},
        {'12103490': {'Invalid Adjust(Media Fee)': '-348.00'}},
        {'12103490': {'TrueView Budget Adjust (Media Fee)': '-9376.00'}},
        {'12160150': {'Media Fee': '549173.00'}},
        {'12160150': {'Platform Fee': '17573.00'}}]

rsult = {}
for i in total:
    for k, v in i.items():
        rsult.setdefault(k, {}).update(v)

print(rsult)

Output:

{'10315065': {'Invalid Adjust(Media Fee)': '-3.00',
              'Invalid Adjust(Platform Fee)': '-1.00'},
 '11211744': {'Invalid Adjust(Media Fee)': '-3403.00',
              'Invalid Adjust(Platform Fee)': '-290.00'},
 '11309685': {'Invalid Adjust(Media Fee)': '-670.00',
              'Invalid Adjust(Platform Fee)': '-57.00'},
 '12103490': {'Invalid Adjust(Media Fee)': '-348.00',
              'Invalid Adjust(Platform Fee)': '-30.00',
              'Media Fee': '709472.00',
              'Platform Fee': '22703.00',
              'TrueView Budget Adjust (Media Fee)': '-9376.00',
              'TrueView Budget Adjust (Platofrm Fee)': '-301.00'},
 '12160150': {'Media Fee': '549173.00', 'Platform Fee': '17573.00'},
 '9940542': {'Invalid Adjust(Media Fee)': '-2.00',
             'Invalid Adjust(Platform Fee)': '-1.00'}}


问:
VIEWS with SELECT inside conditions delaying the query
In one of my SQL views I am using an inline select statement with a where clause.

The outline of my view is like

```<code>ALTER VIEW [dbo].[vw_autumn]
AS
    SELECT
        BookNumber, Title, shopNo
    FROM
        (SELECT
             BookNumber, Title, shopNO
         FROM
             (SELECT DISTINCT
                  (sum_vnr) AS BookNumber,
                  navn1 AS Title,
                  tik AS ShopNO,
                  ROW_NUMBER() OVER (PARTITION BY sum_vnr, tik ORDER BY sum_vnr DESC) AS rownumber
              FROM
                  sum s
              INNER JOIN
                  hod h ON s.tik = h.tik
              WHERE
                  s.aar = (SELECT currentyear
                           FROM SemesterInfo
                           WHERE SemName = 'Autumn')
                  AND CAST(s.sum_vnr AS BIGINT) > 10000
                  AND (s.id LIKE 'h%' OR s.id LIKE 'H%' OR s.id LIKE 'j%'
                       OR s.id LIKE 'J%')) a
    WHERE rownumber = 1
    ) b
LEFT JOIN (
    ------
    ) p ON b.ShopNO = p.tikk
    AND b.ISBN = p.vnr
LEFT JOIN table_k k ON p.aar = k.aar

GO
</code>```

And if I remove the WHERE clause of

```<code> WHERE
     s.aar = (SELECT currentyear
              FROM SemesterInfo
              WHERE SemName = 'Autumn')
</code>```

and shorten it to

```<code>WHERE s.aar =19
</code>```

I am getting the result of view very quickly. But I am trying to add some dynamic nature to this query and selecting this constant from a settings table

Any thoughts on this? Why is the query taking an indefinite time to load with an inline Where clause?

答:
:try with IN insted of =</p>

```<code> WHERE
     s.aar in (SELECT currentyear
              FROM SemesterInfo
              WHERE SemName = 'Autumn')
</code>```

Body:
In one of my SQL views I am using an inline select statement with a where clause.

The outline of my view is like

ALTER VIEW [dbo].[vw_autumn]
AS
    SELECT
        BookNumber, Title, shopNo
    FROM
        (SELECT
             BookNumber, Title, shopNO
         FROM
             (SELECT DISTINCT
                  (sum_vnr) AS BookNumber,
                  navn1 AS Title,
                  tik AS ShopNO,
                  ROW_NUMBER() OVER (PARTITION BY sum_vnr, tik ORDER BY sum_vnr DESC) AS rownumber
              FROM
                  sum s
              INNER JOIN
                  hod h ON s.tik = h.tik
              WHERE
                  s.aar = (SELECT currentyear
                           FROM SemesterInfo
                           WHERE SemName = 'Autumn')
                  AND CAST(s.sum_vnr AS BIGINT) > 10000
                  AND (s.id LIKE 'h%' OR s.id LIKE 'H%' OR s.id LIKE 'j%'
                       OR s.id LIKE 'J%')) a
    WHERE rownumber = 1
    ) b
LEFT JOIN (
    ------
    ) p ON b.ShopNO = p.tikk
    AND b.ISBN = p.vnr
LEFT JOIN table_k k ON p.aar = k.aar

GO

And if I remove the WHERE clause of

 WHERE
     s.aar = (SELECT currentyear
              FROM SemesterInfo
              WHERE SemName = 'Autumn')

and shorten it to

WHERE s.aar =19

I am getting the result of view very quickly. But I am trying to add some dynamic nature to this query and selecting this constant from a settings table

Any thoughts on this? Why is the query taking an indefinite time to load with an inline Where clause?

Body:
:try with IN insted of =

 WHERE
     s.aar in (SELECT currentyear
              FROM SemesterInfo
              WHERE SemName = 'Autumn')


问:
How to use bottom navigator 'OnTap' in flutter
I have an app where i have a list(for eg news).And in the bottom toolbar i have a previous and next button.what i want to do is if i am on **third news and i clicked on the previous button it should go on second news.**I have made the toolbar and will attach the code below.I have added full code for better understanding.Thank you.</p>

```<code>class Newsdetail extends StatefulWidget {
 String  value_image, value_description, value_title;
  int index;

  Newsdetail(
      {Key key,
      @required this.value_image,
      this.value_description,
      this.value_title,
      this.index})
      : super(key: key);

  @override
  _newsdetail createState() => _newsdetail();
}

class _newsdetail extends State<Newsdetail> {
  int _currentindex=0;
  _newsdetail();
  var tabs =[];

    loadyourNews() async {

setState(() {

  tabs = [
  Container(
    child: SingleChildScrollView(
      scrollDirection: Axis.vertical,
      child: Column(
        children: <Widget>[
          Padding(padding: const EdgeInsets.fromLTRB(5.0, 5.0, 5.0, 10.0),
            child: Row(
              children: <Widget>[
                Expanded(child:
                Image.network(widget.value_image))
              ],
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: Row(
              children: <Widget>[
                Expanded(
                  child: Row(
                    children: <Widget>[
                      IconButton(
                          icon: Image.asset('images/facebook.png',),
                          padding: EdgeInsets.all(0.0),
                          onPressed: () {
                            _openFacebook();
                          }),
                      IconButton(
                        icon: Image.asset('images/twitter.png',),
                        padding: EdgeInsets.all(0.0),
                        onPressed: () {
                          _openTwitter();
                        },
                      ),
                      IconButton(
                        icon: Image.asset(
                          'images/whatsappicon.png', width: 180.0,
                          height: 180.0,),
                        padding: EdgeInsets.all(4.0),
                        onPressed: () {
                          _openWhatsapp();
                        },
                      )
                    ],
                  ),
                ),
              ],
            ),
          ),
          Padding(
            padding: const EdgeInsets.fromLTRB(15.0, 5.0, 10.0, 10.0),
            child: Row(
              children: <Widget>[
                Expanded(
                  child: Text(
                    widget.value_title,
                    style: TextStyle(
                        fontSize: 22.0, fontWeight: FontWeight.bold),
                  ),
                ),

              ],
            ),
          ),
          Padding(
            padding: const EdgeInsets.fromLTRB(15.0, 5.0, 10.0, 10.0),
            child: Row(
              children: <Widget>[
                Expanded(
                    child: Text(
                      widget.value_description,
                      style: TextStyle(fontSize: 20.0),
                    )),
              ],
            ),
          ),
        ],
      ),
    ),
  )
];
});

  }

  @override
  void initState() {
    super.initState();
    loadyourNews();
  }
@override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: Text(''),
        backgroundColor: Color(0xFF125688),
        actions: <Widget>[
          Padding(
            padding: const EdgeInsets.fromLTRB(0,0,5.0,0),
            child: SizedBox(
                width: 30,
                child: FlatButton(
                    padding: EdgeInsets.all(0),
                    onPressed: (){},
                    child: Text('A+',style: TextStyle(
                        fontSize: 22.0,color: Colors.white
                    ),))),
          ),

          Padding(
            padding: EdgeInsets.fromLTRB(0,0,38.0,0),
            child: SizedBox(
                width: 30,
                child:FlatButton(
                  padding: EdgeInsets.all(0),
                  onPressed: (){},
                  child: Text('A-',style: TextStyle(
                      fontSize: 15.0,color: Colors.white
                  ),),

                )),
          )

        ],
      ),
      body: tabs[_currentindex],

      bottomNavigationBar:BottomNavigationBar(
        currentIndex: _currentindex,
        backgroundColor: Color(0xFF125688),
        items: [
          BottomNavigationBarItem(
            icon: Icon(Icons.arrow_back),
            title: Text('Previous',style: TextStyle(
                color: Colors.white
            ),),
            backgroundColor: Colors.white,

          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.arrow_forward),
            title: Text('Next',style: TextStyle(
                color: Colors.white
            ),),
            backgroundColor: Colors.white,

          ),
        ],
        onTap: (index){
          setState(() {
            if (index == 0) {
              _currentindex = (_currentindex - 1) % tabs.length;
              if (_currentindex < 0) _currentindex += _currentindex;
            } else
              _currentindex = (_currentindex + 1) % tabs.length;
          });

        },
      ),

    );
  }
</code>```

答:
Here's an example of what you want to do with a PageView:

```<code>class PageViewScaffoldIssue extends StatefulWidget {
  @override
  _PageViewScaffoldIssueState createState() => _PageViewScaffoldIssueState();
}

class _PageViewScaffoldIssueState extends State<PageViewScaffoldIssue> {
  PageController _pageController = PageController();
  List<String> _stringList = [
    'Page 1',
    'Page 2',
    'Page 3',
  ];

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        Expanded(
          child: PageView(
            controller: _pageController,
            children: _stringList.map((item) => NewsArticle(article: item,)).toList(),
          ),
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            RaisedButton.icon(
              onPressed: () => _pageController.previousPage(duration: Duration(milliseconds: 400), curve: Curves.easeInOut),
              icon: Icon(Icons.arrow_back),
              label: Text('Previous'),
            ),
            RaisedButton.icon(
              onPressed: () => addArticle(),
              icon: Icon(Icons.add),
              label: Text('Add'),
            ),
            RaisedButton.icon(
              onPressed: () => _pageController.nextPage(duration: Duration(milliseconds: 400), curve: Curves.easeInOut),
              icon: Icon(Icons.arrow_forward),
              label: Text('Next'),
            ),
          ],
        )
      ],
    );
  }

  void addArticle(){
    setState(() {
      _stringList.add('Page ${_stringList.length+1}');
    });
  }
}

class NewsArticle extends StatelessWidget {
  final String article;

  NewsArticle({
    @required this.article,
  });

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Text(this.article),
    );
  }
}
</code>```

Body:
I have an app where i have a list(for eg news).And in the bottom toolbar i have a previous and next button.what i want to do is if i am on **third news and i clicked on the previous button it should go on second news.**I have made the toolbar and will attach the code below.I have added full code for better understanding.Thank you.

class Newsdetail extends StatefulWidget {
 String  value_image, value_description, value_title;
  int index;

  Newsdetail(
      {Key key,
      @required this.value_image,
      this.value_description,
      this.value_title,
      this.index})
      : super(key: key);

  @override
  _newsdetail createState() => _newsdetail();
}

class _newsdetail extends State<Newsdetail> {
  int _currentindex=0;
  _newsdetail();
  var tabs =[];

    loadyourNews() async {

setState(() {

  tabs = [
  Container(
    child: SingleChildScrollView(
      scrollDirection: Axis.vertical,
      child: Column(
        children: <Widget>[
          Padding(padding: const EdgeInsets.fromLTRB(5.0, 5.0, 5.0, 10.0),
            child: Row(
              children: <Widget>[
                Expanded(child:
                Image.network(widget.value_image))
              ],
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: Row(
              children: <Widget>[
                Expanded(
                  child: Row(
                    children: <Widget>[
                      IconButton(
                          icon: Image.asset('images/facebook.png',),
                          padding: EdgeInsets.all(0.0),
                          onPressed: () {
                            _openFacebook();
                          }),
                      IconButton(
                        icon: Image.asset('images/twitter.png',),
                        padding: EdgeInsets.all(0.0),
                        onPressed: () {
                          _openTwitter();
                        },
                      ),
                      IconButton(
                        icon: Image.asset(
                          'images/whatsappicon.png', width: 180.0,
                          height: 180.0,),
                        padding: EdgeInsets.all(4.0),
                        onPressed: () {
                          _openWhatsapp();
                        },
                      )
                    ],
                  ),
                ),
              ],
            ),
          ),
          Padding(
            padding: const EdgeInsets.fromLTRB(15.0, 5.0, 10.0, 10.0),
            child: Row(
              children: <Widget>[
                Expanded(
                  child: Text(
                    widget.value_title,
                    style: TextStyle(
                        fontSize: 22.0, fontWeight: FontWeight.bold),
                  ),
                ),

              ],
            ),
          ),
          Padding(
            padding: const EdgeInsets.fromLTRB(15.0, 5.0, 10.0, 10.0),
            child: Row(
              children: <Widget>[
                Expanded(
                    child: Text(
                      widget.value_description,
                      style: TextStyle(fontSize: 20.0),
                    )),
              ],
            ),
          ),
        ],
      ),
    ),
  )
];
});

  }

  @override
  void initState() {
    super.initState();
    loadyourNews();
  }
@override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: Text(''),
        backgroundColor: Color(0xFF125688),
        actions: <Widget>[
          Padding(
            padding: const EdgeInsets.fromLTRB(0,0,5.0,0),
            child: SizedBox(
                width: 30,
                child: FlatButton(
                    padding: EdgeInsets.all(0),
                    onPressed: (){},
                    child: Text('A+',style: TextStyle(
                        fontSize: 22.0,color: Colors.white
                    ),))),
          ),

          Padding(
            padding: EdgeInsets.fromLTRB(0,0,38.0,0),
            child: SizedBox(
                width: 30,
                child:FlatButton(
                  padding: EdgeInsets.all(0),
                  onPressed: (){},
                  child: Text('A-',style: TextStyle(
                      fontSize: 15.0,color: Colors.white
                  ),),

                )),
          )

        ],
      ),
      body: tabs[_currentindex],

      bottomNavigationBar:BottomNavigationBar(
        currentIndex: _currentindex,
        backgroundColor: Color(0xFF125688),
        items: [
          BottomNavigationBarItem(
            icon: Icon(Icons.arrow_back),
            title: Text('Previous',style: TextStyle(
                color: Colors.white
            ),),
            backgroundColor: Colors.white,

          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.arrow_forward),
            title: Text('Next',style: TextStyle(
                color: Colors.white
            ),),
            backgroundColor: Colors.white,

          ),
        ],
        onTap: (index){
          setState(() {
            if (index == 0) {
              _currentindex = (_currentindex - 1) % tabs.length;
              if (_currentindex < 0) _currentindex += _currentindex;
            } else
              _currentindex = (_currentindex + 1) % tabs.length;
          });

        },
      ),

    );
  }

Body:
Here's an example of what you want to do with a PageView:

class PageViewScaffoldIssue extends StatefulWidget {
  @override
  _PageViewScaffoldIssueState createState() => _PageViewScaffoldIssueState();
}

class _PageViewScaffoldIssueState extends State<PageViewScaffoldIssue> {
  PageController _pageController = PageController();
  List<String> _stringList = [
    'Page 1',
    'Page 2',
    'Page 3',
  ];

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        Expanded(
          child: PageView(
            controller: _pageController,
            children: _stringList.map((item) => NewsArticle(article: item,)).toList(),
          ),
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            RaisedButton.icon(
              onPressed: () => _pageController.previousPage(duration: Duration(milliseconds: 400), curve: Curves.easeInOut),
              icon: Icon(Icons.arrow_back),
              label: Text('Previous'),
            ),
            RaisedButton.icon(
              onPressed: () => addArticle(),
              icon: Icon(Icons.add),
              label: Text('Add'),
            ),
            RaisedButton.icon(
              onPressed: () => _pageController.nextPage(duration: Duration(milliseconds: 400), curve: Curves.easeInOut),
              icon: Icon(Icons.arrow_forward),
              label: Text('Next'),
            ),
          ],
        )
      ],
    );
  }

  void addArticle(){
    setState(() {
      _stringList.add('Page ${_stringList.length+1}');
    });
  }
}

class NewsArticle extends StatelessWidget {
  final String article;

  NewsArticle({
    @required this.article,
  });

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Text(this.article),
    );
  }
}


问:
Azure Storage blob container assign RBAC using ARM
We currently have ARM templates that create storage accounts and containers in a solution however I can't seem to manage to assign the RBAC access to the container in the ARM template. I have tried using Erik's solution here

```<code>"type": "Microsoft.Storage/storageAccounts/blobServices/containers/providers/roleAssignments",
  "apiVersion": "2017-09-01",
  "name": "[concat(parameters('storageAccountName'),'/default/filedrop/Microsoft.Authorization/{NEW GUID}')]",
  "properties": {
    "roleDefinitionId": "ba92f5b4-2d11-453d-a403-e96b0029c9fe",
    "principalId": "[parameters('ServicePrincipalId')]"
}
</code>```

The error I get is "error": {
    "code": "BadRequestFormat",
    "message": "The request was incorrectly formatted."
  }
Anyone see where I'm going wrong?

答:
Here is what I used: https://github.com/juunas11/managedidentity-filesharing/blob/8410ed3f3d4061de7d40531c025bf6e474489135/Joonasw.ManagedIdentityFileSharingDemo.ARM/azuredeploy.json#L223-L236

```<code>    {
      "type": "Microsoft.Storage/storageAccounts/blobServices/containers/providers/roleAssignments",
      "apiVersion": "2018-01-01-preview",
      "name": "[concat(parameters('storageAccountName'), '/default/', parameters('storageContainerName'), '/Microsoft.Authorization/', guid(resourceGroup().id, 'webAppFilesAccess'))]",
      "dependsOn": [
        "[resourceId('Microsoft.Storage/storageAccounts', parameters('storageAccountName'))]",
        "[resourceId('Microsoft.Storage/storageAccounts/blobServices/containers', parameters('storageAccountName'), 'default', parameters('storageContainerName'))]",
        "[resourceId('Microsoft.Web/sites', parameters('webAppName'))]"
      ],
      "properties": {
        "principalId": "[reference(resourceId('Microsoft.Web/sites', parameters('webAppName')), '2016-08-01', 'Full').identity.principalId]",
        "roleDefinitionId": "[variables('storageBlobContributorRoleId')]"
      }
    }
</code>```

The main difference I can see is that I have a higher API version + I use parameters for a lot of things.

The guid() function is pretty handy since you can give it some text, and if the text is same, it'll give the same GUID every time.

Body:
We currently have ARM templates that create storage accounts and containers in a solution however I can't seem to manage to assign the RBAC access to the container in the ARM template. I have tried using Erik's solution here

"type": "Microsoft.Storage/storageAccounts/blobServices/containers/providers/roleAssignments",
  "apiVersion": "2017-09-01",
  "name": "[concat(parameters('storageAccountName'),'/default/filedrop/Microsoft.Authorization/{NEW GUID}')]",
  "properties": {
    "roleDefinitionId": "ba92f5b4-2d11-453d-a403-e96b0029c9fe",
    "principalId": "[parameters('ServicePrincipalId')]"
}

The error I get is "error": {
    "code": "BadRequestFormat",
    "message": "The request was incorrectly formatted."
  }
Anyone see where I'm going wrong?

Body:
Here is what I used: https://github.com/juunas11/managedidentity-filesharing/blob/8410ed3f3d4061de7d40531c025bf6e474489135/Joonasw.ManagedIdentityFileSharingDemo.ARM/azuredeploy.json#L223-L236

    {
      "type": "Microsoft.Storage/storageAccounts/blobServices/containers/providers/roleAssignments",
      "apiVersion": "2018-01-01-preview",
      "name": "[concat(parameters('storageAccountName'), '/default/', parameters('storageContainerName'), '/Microsoft.Authorization/', guid(resourceGroup().id, 'webAppFilesAccess'))]",
      "dependsOn": [
        "[resourceId('Microsoft.Storage/storageAccounts', parameters('storageAccountName'))]",
        "[resourceId('Microsoft.Storage/storageAccounts/blobServices/containers', parameters('storageAccountName'), 'default', parameters('storageContainerName'))]",
        "[resourceId('Microsoft.Web/sites', parameters('webAppName'))]"
      ],
      "properties": {
        "principalId": "[reference(resourceId('Microsoft.Web/sites', parameters('webAppName')), '2016-08-01', 'Full').identity.principalId]",
        "roleDefinitionId": "[variables('storageBlobContributorRoleId')]"
      }
    }

The main difference I can see is that I have a higher API version + I use parameters for a lot of things.

The guid() function is pretty handy since you can give it some text, and if the text is same, it'll give the same GUID every time.


问:
Create Jmeter Aggregate report with the thread group name
I need to create an Aggregate report under a thread group with the thread group name. For Ex: If my thread group name is LoginThreadgroup I need to create an Aggregate report file, View Result Tree file name with LoginThreadgroup.jtl LoginThreadgroup_VRT.jtl

I tried to use -${__BeanShell(ctx.getThreadGroup().getName())}.jtl
and
${__threadGroupName}_ViewResultsTree_Failure_report.jtl

ETC but both dint work out well in my case.

I have many thread groups under test tree, for each, I would like to create jtl files with the respective thread group name.
Can anyone help me in this

答:
I don't think you can use JMeter Functions and/or Variables in "Filename" field of a Listener

In general using Listeners is not the best idea as they don't add any value and simply consume CPU, RAM and Disk resources.

I would rather suggest

Adding __threadGroupName() function as a prefix/postfix to your Samplers labels

If you want separate results for different Thread Groups you can use Filter Results Tool to extract Thread-Group-specific entries from the .jtl results file

Aggregate Report can be generated using JMeterPluginsCMD Command Line Tool