问:
How to keep a condition for null value in jolt?
INPUT:

```<code> {
   "itemName": null,
   "itemNumber": 22
 }
</code>```

OUTPUT:

```<code> {
   "isItemNameNull": true,
   "itemNumber": 22
 }
</code>```

I should not map the value if its null but map 'isItemNameNull' to true,

SPEC:

```<code>[
 {
"operation": "shift",
"spec": {
  "itemName": {
    "null": {
      "true": "isItemNameNull"
    },
    "": {
      "#TRASH": "TRASH"
    },
    "*": {
      "@(2,itemName)": "itemName"
    }
  },
  "itemNumber": {
    "null": {
      "#TRASH": "TRASH"
    },
    "": {
      "#TRASH": "TRASH"
    },
    "*": {
      "@(2,itemNumber)": "itemNumber"
    }
  }
  }
 }
]
</code>```

I mapped the flag but it did'nt took it from null condition.Can any one please suggest me a help.Thanks.

答:
I tried this case. I edited a little in your input json also.

```<code>Input Json
----------
{
  "itemName": "null",
  "itemNumber": 22
}

SPEC:
----
    [
      {
        "operation": "shift",
        "spec": {
          "itemName": {
            "null": {
              "#true": "isItemNameNull"
            }
          },
          "itemNumber": "itemNumber"
        }
       }
    ]

Output Json
-----------

{
  "isItemNameNull" : "true",
  "itemNumber" : 22
}
</code>```

Try yourself please

Body:
INPUT:

 {
   "itemName": null,
   "itemNumber": 22
 }

OUTPUT:

 {
   "isItemNameNull": true,
   "itemNumber": 22
 }

I should not map the value if its null but map 'isItemNameNull' to true,

SPEC:

[
 {
"operation": "shift",
"spec": {
  "itemName": {
    "null": {
      "true": "isItemNameNull"
    },
    "": {
      "#TRASH": "TRASH"
    },
    "*": {
      "@(2,itemName)": "itemName"
    }
  },
  "itemNumber": {
    "null": {
      "#TRASH": "TRASH"
    },
    "": {
      "#TRASH": "TRASH"
    },
    "*": {
      "@(2,itemNumber)": "itemNumber"
    }
  }
  }
 }
]

I mapped the flag but it did'nt took it from null condition.Can any one please suggest me a help.Thanks.

Body:
I tried this case. I edited a little in your input json also.

Input Json
----------
{
  "itemName": "null",
  "itemNumber": 22
}

SPEC:
----
    [
      {
        "operation": "shift",
        "spec": {
          "itemName": {
            "null": {
              "#true": "isItemNameNull"
            }
          },
          "itemNumber": "itemNumber"
        }
       }
    ]

Output Json
-----------

{
  "isItemNameNull" : "true",
  "itemNumber" : 22
}

Try yourself please


来源: stackexchange

问:
POST http://localhost:8000/broadcasting/auth 403 (Forbidden) / for customer service chat where i only need auth for admins
How can I use broadcasting/auth for the admin but not for the normal user, and still both can chat with each other?

// BroadcastServiceProvider

```<code>public function boot()
{

    Broadcast::routes();

    require base_path('routes/channels.php');
}
</code>```

// Channels.php

```<code>Broadcast::channel('App.User.{id}', function ($user, $id) {
return (int) $user->id === (int) $id; });

Broadcast::channel('chat', function ($user) {
return $user;  });
</code>```

// MessageSent Event

```<code>public function broadcastOn()
{
    return new PresenceChannel('chat');
}
</code>```

I'm getting this error: POST http://localhost:8000/broadcasting/auth 403 (Forbidden), but when i remove from laravel echo (Echo.join('chat')) the error goes.

答:
You can achieve such thing using Middleware in laravel.

This quote is from laravel's official website:

Middleware provide a convenient mechanism for filtering HTTP requests
  entering your application. For example, Laravel includes a middleware
  that verifies the user of your application is authenticated. If the
  user is not authenticated, the middleware will redirect the user to
  the login screen. However, if the user is authenticated, the
  middleware will allow the request to proceed further into the
  application.

Complete reading from this website

ContentLicense: CC BY-SA 4.0

Body:
How can I use broadcasting/auth for the admin but not for the normal user, and still both can chat with each other?

// BroadcastServiceProvider

public function boot()
{

    Broadcast::routes();

    require base_path('routes/channels.php');
}

// Channels.php

Broadcast::channel('App.User.{id}', function ($user, $id) {
return (int) $user->id === (int) $id; });

Broadcast::channel('chat', function ($user) {
return $user;  });

// MessageSent Event

public function broadcastOn()
{
    return new PresenceChannel('chat');
}

I'm getting this error: POST http://localhost:8000/broadcasting/auth 403 (Forbidden), but when i remove from laravel echo (Echo.join('chat')) the error goes.


问:
Alert about bounced emails using Spring Boot
I have a Spring Boot application that sends emails. For any action that requires notification, a Mail instance is created with status PENDING in the database and a job is run to send the pending emails every minute. The status of the Mail instances are set as PENDING, SENT or FAILED.

```<code>try {
    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", port);
    props.put("mail.smtp.from", myEmailAddress);
    props.put("mail.smtp.timeout", 2000);

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
    });

    MimeMessage message = new MimeMessage(session);
    MimeMultipart content = getContent(mail, message, username);
    message.setContent(content);
    Transport.send(message);
    mail.setStatus(MailStatus.SENT);
    mailService.save(mail);
} catch (MailConnectException mce) {
    mail.setStatus(MailStatus.FAILED);
    mailService.save(mail);
} catch (Exception e) {
    // other actions
}
</code>```

Now, this works fine if a valid email id is provided. But when the receiving email address is a non-existent one like somerandomname@gmail.com, there are no exceptions thrown. From what I read from similar questions in SO and elsewhere, I understand that mail sending is an asynchronous process and hence there is no way to determine that a given email is existing or not (or other issues like Inbox full). That is why after the Transport.send(message); statement, the mail.setStatus(MailStatus.SENT); statement will always be executed irrespective of the email address being present. Later the mail will actually be attempted to be sent and I get an email in myEmailAddress with content like the following:

The response from the remote server was: 550 5.1.1
  somerandomname@gmail.com User unknown

Okay, accepted until this point. But now I need a way to alert the user that the email couldn't be sent because they entered an invalid email so that they can update their email. More specifically, I need to set the status of the Mail instance to FAILED. What is the best way to achieve this?

答:
Your Spring Boot application would have to retrieve the notifications (an email itself) from your inbox corresponding to the sender address of the initial email. There are various options how to achieve this:

Use a service with provides callbacks (triggers) for incoming messages as mentioned by Benjamin

Poll your inbox using a standard protocol like POP or IMAP

Hint for the second option: https://docs.spring.io/spring-integration/reference/html/mail.html#mail-inbound

Body:
I have a Spring Boot application that sends emails. For any action that requires notification, a Mail instance is created with status PENDING in the database and a job is run to send the pending emails every minute. The status of the Mail instances are set as PENDING, SENT or FAILED.

try {
    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", port);
    props.put("mail.smtp.from", myEmailAddress);
    props.put("mail.smtp.timeout", 2000);

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
    });

    MimeMessage message = new MimeMessage(session);
    MimeMultipart content = getContent(mail, message, username);
    message.setContent(content);
    Transport.send(message);
    mail.setStatus(MailStatus.SENT);
    mailService.save(mail);
} catch (MailConnectException mce) {
    mail.setStatus(MailStatus.FAILED);
    mailService.save(mail);
} catch (Exception e) {
    // other actions
}

Now, this works fine if a valid email id is provided. But when the receiving email address is a non-existent one like somerandomname@gmail.com, there are no exceptions thrown. From what I read from similar questions in SO and elsewhere, I understand that mail sending is an asynchronous process and hence there is no way to determine that a given email is existing or not (or other issues like Inbox full). That is why after the Transport.send(message); statement, the mail.setStatus(MailStatus.SENT); statement will always be executed irrespective of the email address being present. Later the mail will actually be attempted to be sent and I get an email in myEmailAddress with content like the following:

The response from the remote server was: 550 5.1.1
  somerandomname@gmail.com User unknown

Okay, accepted until this point. But now I need a way to alert the user that the email couldn't be sent because they entered an invalid email so that they can update their email. More specifically, I need to set the status of the Mail instance to FAILED. What is the best way to achieve this?


问:
How does Java resolve a relative path in new File()?
I am trying to understand the way Java resolves relative path in while creating a File object.

OS used: Windows

For the below snippet, I am getting an IOException as it cannot find the path:

```<code>@Test
public void testPathConversion() {
        File f = new File("test/test.txt");
        try {
            f.createNewFile();
            System.out.println(f.getPath());
            System.out.println(f.getAbsolutePath());
            System.out.println(f.getCanonicalPath());
        } catch (Exception e) {
            e.printStackTrace();
        }
}
</code>```

My understanding here is, Java treats the path provided as absolute and returns an error when the path does not exist. So it makes sense.

When I update the above code to use relative path:

```<code>@Test
    public void testPathConversion() {
        File f = new File("test/../test.txt");
        try {
            f.createNewFile();
            System.out.println(f.getPath());
            System.out.println(f.getAbsolutePath());
            System.out.println(f.getCanonicalPath());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
</code>```

It creates a new file and provides the below output:

```<code>test\..\test.txt
C:\JavaForTesters\test\..\test.txt
C:\JavaForTesters\test.txt
</code>```

In this case, my assumption is, even though the path provided doesn't exist, because the path contains "/../", java treats this as a relative path and creates the file in the user.dir.  So this also makes sense.

But if I update the relative path as below:

```<code>   @Test
    public void testPathConversion() {
        File f = new File("test/../../test.txt");
        try {
            f.createNewFile();
            System.out.println(f.getPath());
            System.out.println(f.getAbsolutePath());
            System.out.println(f.getCanonicalPath());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
</code>```

Then I get IOException: Access is denied.

My questions are:

why "test/../test.txt" is treated as a relative path and creates the file in "user.dir" but"test/../../test.txt" returns an error? Where does it attempt to create the file for the path "test/../../test.txt"?

When the specified relative path is not found, the file seems to be created in the user.dir. So, it appears to me that the below two scenarios does the same thing:

```<code>//scenario 1
File f = new File("test/../test.txt");
f.createNewFile();

//scenario 2
File f = new File("test.txt");
f.createNewFile();
</code>```

So is there a real world case where one would use scenario 1 instead of scenario 2?

I suppose I am missing something obvious here or have fundamentally misunderstood relative paths. I went through the Java docs for File and I am not able to find an explanation for this. There are quite a few questions posted in Stack Overflow regarding relative paths, but the ones I looked up were for specific scenarios and not exactly about how relative paths are resolved.

It will be great if someone could please explain me how this works or point to some related links?

答:
I went off of peter.petrov's answer but let me explain where you make the file edits to change it to a relative path.

Simply edit "AXLAPIService.java" and change

url = new URL("file:C:users..../schema/current/AXLAPI.wsdl");

to

url = new URL("file:./schema/current/AXLAPI.wsdl");

or where ever you want to store it.

You can still work on packaging the wsdl file into the meta-inf folder in the jar but this was the simplest way to get it working for me.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to understand the way Java resolves relative path in while creating a File object.

OS used: Windows

For the below snippet, I am getting an IOException as it cannot find the path:

@Test
public void testPathConversion() {
        File f = new File("test/test.txt");
        try {
            f.createNewFile();
            System.out.println(f.getPath());
            System.out.println(f.getAbsolutePath());
            System.out.println(f.getCanonicalPath());
        } catch (Exception e) {
            e.printStackTrace();
        }
}

My understanding here is, Java treats the path provided as absolute and returns an error when the path does not exist. So it makes sense.

When I update the above code to use relative path:

@Test
    public void testPathConversion() {
        File f = new File("test/../test.txt");
        try {
            f.createNewFile();
            System.out.println(f.getPath());
            System.out.println(f.getAbsolutePath());
            System.out.println(f.getCanonicalPath());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

It creates a new file and provides the below output:

test\..\test.txt
C:\JavaForTesters\test\..\test.txt
C:\JavaForTesters\test.txt

In this case, my assumption is, even though the path provided doesn't exist, because the path contains "/../", java treats this as a relative path and creates the file in the user.dir.  So this also makes sense.

But if I update the relative path as below:

   @Test
    public void testPathConversion() {
        File f = new File("test/../../test.txt");
        try {
            f.createNewFile();
            System.out.println(f.getPath());
            System.out.println(f.getAbsolutePath());
            System.out.println(f.getCanonicalPath());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

Then I get IOException: Access is denied.

My questions are:

why "test/../test.txt" is treated as a relative path and creates the file in "user.dir" but"test/../../test.txt" returns an error? Where does it attempt to create the file for the path "test/../../test.txt"?

When the specified relative path is not found, the file seems to be created in the user.dir. So, it appears to me that the below two scenarios does the same thing:

//scenario 1
File f = new File("test/../test.txt");
f.createNewFile();

//scenario 2
File f = new File("test.txt");
f.createNewFile();

So is there a real world case where one would use scenario 1 instead of scenario 2?

I suppose I am missing something obvious here or have fundamentally misunderstood relative paths. I went through the Java docs for File and I am not able to find an explanation for this. There are quite a few questions posted in Stack Overflow regarding relative paths, but the ones I looked up were for specific scenarios and not exactly about how relative paths are resolved.

It will be great if someone could please explain me how this works or point to some related links?


问:
Image throws 404 Error when using app on server
Hi I checked several answers around the web but none of these worked yet, I located the image where it supposed to be by the most answers. The problem is that I have a loader component which contains a loader that pops up when doing something in my application and it needs some time to load. In local it works perfectly but when I use it on server it throws GET 404 error for the image that needs to be shown inside the loader circle. I'm using Angular 7.

Currently I have the image here: src/assets/image/logo.jpg

And this is how it looks in the component:

my workspace is like this: src --> app --> loader --> loadingComponent

What can cause the problem that it works good in local but doesn't work when I run the app on Tomcat server

答: So what worked for me is using the source like this:  I removed the / sign before assets. Now its working fine on server as well.

Body: So what worked for me is using the source like this: <img src="assets/image/logo.jpg"> I removed the / sign before assets. Now its working fine on server as well.


问:
Invalid arguments
i am expanding on the XNA game studio 2D tutorial and adding menus from the microsoft XNA Game studio website. i thought it would be just plug in and run, but is much more complicated than i thought. here is one error, i will post more as i get them.
Here is the debug window:

C:\Users\Ian\Desktop\GameStateManagementSample - Copy\GameStateManagement\Screens\GameplayScreen.cs(81,24): error CS1502: The best overloaded method match for 'Microsoft.Xna.Framework.GraphicsDeviceManager.GraphicsDeviceManager(Microsoft.Xna.Framework.Game)' has some invalid arguments
  C:\Users\Ian\Desktop\GameStateManagementSample - Copy\GameStateManagement\Screens\GameplayScreen.cs(81,50): error CS1503: Argument '1': cannot convert from 'GameStateManagement.GameplayScreen' to 'Microsoft.Xna.Framework.Game'

Compile complete -- 2 errors, 0 warnings
  ========== Build: 0 succeeded or up-to-date, 1 failed, 0 skipped ==========

And here is the code:

```<code>public GameplayScreen()

        {
            //new GraphicsDeviceManager(this) has the error line under it!!!
            graphics = new GraphicsDeviceManager(this);
            content.RootDirectory = "Content";
        }
</code>```

答:
You need to pass the constructor for GraphicsDeviceManager a valid Microsoft.Xna.Framework.Game object instead of the current class using this

Also, a walkthrough that may be helpful to create your first game

OwnerDisplayName: Ian

Title: Invalid arguments

Body:
i am expanding on the XNA game studio 2D tutorial and adding menus from the microsoft XNA Game studio website. i thought it would be just plug in and run, but is much more complicated than i thought. here is one error, i will post more as i get them.
Here is the debug window:

C:\Users\Ian\Desktop\GameStateManagementSample - Copy\GameStateManagement\Screens\GameplayScreen.cs(81,24): error CS1502: The best overloaded method match for 'Microsoft.Xna.Framework.GraphicsDeviceManager.GraphicsDeviceManager(Microsoft.Xna.Framework.Game)' has some invalid arguments
  C:\Users\Ian\Desktop\GameStateManagementSample - Copy\GameStateManagement\Screens\GameplayScreen.cs(81,50): error CS1503: Argument '1': cannot convert from 'GameStateManagement.GameplayScreen' to 'Microsoft.Xna.Framework.Game'

Compile complete -- 2 errors, 0 warnings
  ========== Build: 0 succeeded or up-to-date, 1 failed, 0 skipped ==========

And here is the code:

public GameplayScreen()

        {
            //new GraphicsDeviceManager(this) has the error line under it!!!
            graphics = new GraphicsDeviceManager(this);
            content.RootDirectory = "Content";
        }

OwnerDisplayName: Chris Ballance

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Chris Ballance


问:
C loop, beginner stuff
I have a task to make a program in which you have to input a given number on a given position in another given number. Example: input:12345, 2, 3 output 123245. I tried to make a loop but it is apparently an infinite loop. The code is here:</p>

```<code>int c, x, p, broj, i = 0, brcifara = 0, k, broj2, k2, broj3, ind;
printf("Unesite redom x, p i c: ");
scanf("%d%d%d", &x, &p, &c);
broj2 = x;
while(broj2 >= 1)
{
    broj2/= 10;
    brcifara += 1;
}
while(i < brcifara)
{
    k2 = pow(10, i + 1);
    k = broj3%k2;
    broj3 -= k*pow(10, i+ 1);

    if(i<p)
    {
        broj += k*pow(10, i+1);
    }
    if(i=p)
    {
        broj += c*pow(10, p);
    }
    if(i>p)
    {
        broj += k*pow(10, i+2);
    }
    i = i + 1;
}
printf("Broj je sada %d", broj);
</code>```

<p>}
C represents the number for putting in, X is the number in which we are putting C, P represents the postion(starting from 0). Brcifara is the number of digits. The problem is only in the second loop. </p>

答:
Why not trying something like that :

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>

#define MAX_STR_SIZE (100U)

int main()
{
  char x[MAX_STR_SIZE] = {'\0'};
  unsigned int p;
  char c;
  int x_int;
  printf("input x, p, c\n");
  scanf("%s %d %c", x, &p, &c);

  if(strlen(x) > p) // check string upper boundary
  {
    x[p] = c;
  }

  x_int = atoi(x);
  printf("%d\n", x_int);
}
</code>```

X is a string in which you replace your C character at the given P position.
Thus :

X is a string.

C a character.

P an index (unsigned char).

Then convert the X string to an integer using the atoi() function.

Title: C loop, beginner stuff

Body:
I have a task to make a program in which you have to input a given number on a given position in another given number. Example: input:12345, 2, 3 output 123245. I tried to make a loop but it is apparently an infinite loop. The code is here:

int c, x, p, broj, i = 0, brcifara = 0, k, broj2, k2, broj3, ind;
printf("Unesite redom x, p i c: ");
scanf("%d%d%d", &x, &p, &c);
broj2 = x;
while(broj2 >= 1)
{
    broj2/= 10;
    brcifara += 1;
}
while(i < brcifara)
{
    k2 = pow(10, i + 1);
    k = broj3%k2;
    broj3 -= k*pow(10, i+ 1);

    if(i
p)
    {
        broj += k*pow(10, i+2);
    }
    i = i + 1;
}
printf("Broj je sada %d", broj);

}
C represents the number for putting in, X is the number in which we are putting C, P represents the postion(starting from 0). Brcifara is the number of digits. The problem is only in the second loop.

Body:
Why not trying something like that :

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>

#define MAX_STR_SIZE (100U)

int main()
{
  char x[MAX_STR_SIZE] = {'\0'};
  unsigned int p;
  char c;
  int x_int;
  printf("input x, p, c\n");
  scanf("%s %d %c", x, &p, &c);

  if(strlen(x) > p) // check string upper boundary
  {
    x[p] = c;
  }

  x_int = atoi(x);
  printf("%d\n", x_int);
}

X is a string in which you replace your C character at the given P position.
Thus :

X is a string.

C a character.

P an index (unsigned char).

Then convert the X string to an integer using the atoi() function.


问:
Kaltura Chromecast problems
We have a kaltura CE server and want to send a LIVE stream to Chromecast. We created a styled receiver app.
When we open the player and try to connect to a Chromecast device, we get this error:

Unsafe attempt to load URL https://dev.yyyyy.com/p/102/sp/10200/playManifest/entryId/0_f4wphewh/format/applehttp/protocol/https/uiConfId/23448172/a.m3u8?referrer=aHR0cHM6Ly9kZXYuY2xvdWR2aWRlby5jb20uY28=&playSessionId=eca13709-002a-256e-b1b2-dd83510aa455 from frame with URL https://www.gstatic.com/cast/sdk/default_receiver/1.0/app.html?skin 1. Domains, protocols and ports must match

Chromecast refuses to load the manifest from dev.yyyy.com despite the fact that all the headers have been set.

Any help will be appreciated,

David Eusse

答:
welcome to stackoverflow :-)
try adding CORS headers to the m3u8 following this document:
https://developers.google.com/cast/v2/mpl_player#cors</p>

Title: Kaltura Chromecast problems


问:
Python multilevel inheritence
```<code>class A:
    def foo(self):
        print("original")
class B(A):
    def foo(self):
        super().foo()
        print("override")
class C(B):
    def foo(self):
      super().foo()
       print("override")

o = c()
</code>```

<p>Now after defining this object, I want to, access the foo of class A through same object, how do I do that??? </p>

答:
If you actually want to bypass all the child class implementations, just name the base class explicitly, e.g. replace:

```<code>self.method_name()  # Calls own class (or first parent with implementation if own class lacks it)
super().method_name()  # Call first parent class with implementation of the method
</code>```

with:

```<code>GrandparentClass.method_name(self)  # Explicitly calls specific class's version of the method with self
</code>```

To be clear, GrandparentClass is a placeholder for the actual name of the top-level class you want to call, it's not a special name/function like super().

Note: If you're doing this, you likely have an XY problem that should probably be solved instead.

Title: Python multilevel inheritence

Body:
class A:
    def foo(self):
        print("original")
class B(A):
    def foo(self):
        super().foo()
        print("override")
class C(B):
    def foo(self):
      super().foo()
       print("override")

o = c()

Now after defining this object, I want to, access the foo of class A through same object, how do I do that???

Body:
If you actually want to bypass all the child class implementations, just name the base class explicitly, e.g. replace:

self.method_name()  # Calls own class (or first parent with implementation if own class lacks it)
super().method_name()  # Call first parent class with implementation of the method

with:

GrandparentClass.method_name(self)  # Explicitly calls specific class's version of the method with self

To be clear, GrandparentClass is a placeholder for the actual name of the top-level class you want to call, it's not a special name/function like super().

Note: If you're doing this, you likely have an XY problem that should probably be solved instead.


问:
Mariadb 10.4 minor version review
i am thinking about upgrading my mariadb production servers to 10.4 and i would like to ask you if you have any troubles with specific minor versions on 10.4.

So have you troubles with any version? Or what version are you running without any problems?

答:
I would suggest using the latest stable release of MariaDB, that is version 10.4.12, which was released on January 2020.

You will benefit the cumulative fixes of all previous subversions of 10.4 - the first stable subversion of 10.4 was 10.4.6 (released in June 2019), so lot of work has been put into stabilizing it already.

Please note that version 10.5 is on its way too: alpha released 10.5.0 happened in December 2019; but as of today there is still no stable version available (10.5.1 - Beta, was released this month), so if you want something bullet-proof it is too early.

Of course, as always, you should install and test this in QA environment before moving to Production so you can ensure that everything works smoothly in your ecosystem.

Title: Mariadb 10.4 minor version review


问:
Comparing doubles to double literals?

Possible Duplicate:

  How should I do floating point comparison?

Is it not recommended to compare for equality a double and a double literal in C++, because I guess it is compiler dependent?

To be more precise it is not OK to compare a double which is hard-coded (a literal in the source code) and a double which should be computed, as the last number of the resultant of the calculation can vary from one compiler to another. Is this not standardized?

I heard this is mentioned in Knuth's TeXbook, is that right?

If this is all true, what is the solution?

答:
if you do floating point calculations and you need to do comparisons with certain fixed values it is always safer to use an epsilon value to take into account precision errors .

Example:

```<code>double calcSomeStuf();

if ( calcSomeStuf() == 0.1 ) { ...}
</code>```

is a bad idea

however:

```<code>const double epsilon = 0.005

double calcSomeStuf();

if ( abs(calcSomeStuf() - 0.1) < epsilon ) { ...}
</code>```

is a lot safer (especially considering the fact that 0.1 cannot be represented exactly as a double)

This is necessary because when accumulating floating point operations rounding errors occur, and due to the nature of floating point not all numbers can be represented exactly

Title: Comparing doubles to double literals?

Body:
if you do floating point calculations and you need to do comparisons with certain fixed values it is always safer to use an epsilon value to take into account precision errors .

Example:

double calcSomeStuf();

if ( calcSomeStuf() == 0.1 ) { ...}

is a bad idea

however:

const double epsilon = 0.005

double calcSomeStuf();

if ( abs(calcSomeStuf() - 0.1) < epsilon ) { ...}

is a lot safer (especially considering the fact that 0.1 cannot be represented exactly as a double)

This is necessary because when accumulating floating point operations rounding errors occur, and due to the nature of floating point not all numbers can be represented exactly


问:
How to not change Bottom Navigation View Item Color on click
I have three items in my bottomNavigationView

When I click on the profile item the code checks whether the person is logged in or not. If the person is not logged in then I need to start a new Activity else I need to load a fragment in my frameLayout.

Now the problem is that when I click on the profile item and the person is not logged in then the activity starts but when I click back then the profile item is highlighted but the home fragment is loaded in the frame layout.

I have tried the following ways to solve this

1) I used setSelectedItemId to set the item color when profile item is clicked but it didn't work

Is there any other way to do this ?

答: return false thats it because for launching activity we need not to higlight menu item


问:
Navigation Bar Items with @EnvironmentObject
I would like to create a Settings view using SwiftUI. I mainly took the official example from Apple about SwiftUI to realize my code. The settings view should have a toggle to whether display or not my favorites items.

For now I have a landmarks list and a settings view.

```<code>struct Landmark: Hashable, Codable, Identifiable {
    var id: Int
    var imageName: String
    var title: String
    var isFavorite: Bool
    var description: String

    enum CodingKeys: String, CodingKey {
        case id, imageName, title, description
    }
}
</code>```

```<code>final class UserData: ObservableObject {
    @Published var showFavoriteOnly: Bool = false
    @Published var items: [Landmark] = landmarkData
    @Published var showProfile: Bool = false
}
</code>```

```<code>struct ItemList: View {
    @EnvironmentObject var userData: UserData
    @State var trailing: Bool = false

    init() {
        UITableView.appearance().separatorStyle = .none
    }

    var body: some View {
        NavigationView {
            List {
                VStack {
                    CircleBadgeView(text: String(landmarkData.count), thickness: 2)
                    Text("Tutorials available")
                }.frame(minWidth:0, maxWidth: .infinity)

                ForEach(userData.items) { landmark in
                    if !self.userData.showFavoriteOnly || landmark.isFavorite {
                        ZStack {
                            Image(landmark.imageName)
                                .resizable()
                                .frame(minWidth: 0, maxWidth: .infinity)
                                .cornerRadius(10)
                                .overlay(ImageOverlay(text: landmark.title), alignment: .bottomTrailing)
                            Text(String(landmark.isFavorite))

                            NavigationLink(destination: TutorialDetailView(landmark: landmark)) {
                                EmptyView()
                            }.buttonStyle(PlainButtonStyle())
                        }
                    }
                }
            }.navigationBarTitle("Tutorials")
                .navigationBarItems(trailing: trailingItem())
        }
    }
}

extension ItemList {
    func trailingItem () -> some View {
        return HStack {

            if userData.showProfile {
                NavigationLink(destination: ProfileView()) {
                    Image(systemName: "person.circle")
                        .imageScale(.large)
                        .accessibility(label: Text("Profile"))
                }
            }

            NavigationLink(destination: SettingsView().environmentObject(userData)) {
                Image(systemName: "gear")
                    .imageScale(.large)
                    .accessibility(label: Text("Settings"))
            }
        }
    }
}
</code>```

As you can see my SettingsView is accessible from navigationBarItems of my NavigationView. I don't know if it's the problem or not but when I put the Toggle inside the ListView it works as expected. But now when I trigger the toggle to enable only favorite my application crash instantly.

I've tried to trigger the Show profile toggle from SettingsView and it works.

```<code>struct SettingsView: View {
    @EnvironmentObject var userData: UserData

    var body: some View {
        Form {
            Section(header: Text("General")) {
                Toggle(isOn: $userData.showProfile) {
                    Text("Show profile")
                }
                Toggle(isOn: $userData.showFavoriteOnly) {
                    Text("Favorites only")
                }
            }

            Section(header: Text("UI")) {
                Toggle(isOn: .constant(false)) {
                    Text("Dark mode")
                }

                NavigationLink(destination: Text("third")) {
                    Text("Third navigation")
                }
            }

        }.navigationBarTitle(Text("Settings"), displayMode: .inline)
    }
}
</code>```

In brief, the crash appears in my SettingsView when I trigger the Show only favorite Toggle and then I try to go back to the previous view which is ItemListView

The only information I can get about the error is Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

You can find the whole project on my GitHub : https://github.com/Hurobaki/swiftui-tutorial

Some help would be really appreciated :)

答:
Here is a minimal version of your example code, that works:

struct Landmark: Hashable, Codable, Identifiable {
  var id: Int
  var imageName: String
  var title: String
  var isFavorite: Bool
  var description: String
}

final class UserData: ObservableObject {
  @Published var showFavoriteOnly: Bool = false
  @Published var items: [Landmark] = [
    Landmark(id: 1, imageName: "a", title: "a", isFavorite: true, description: "A"),
    Landmark(id: 2, imageName: "b", title: "b", isFavorite: false, description: "B")
  ]
}

struct ContentView: View {
  @EnvironmentObject var userData: UserData

  var body: some View {
    NavigationView {
      List(userData.items.filter { !userData.showFavoriteOnly || $0.isFavorite }) { landmark in
        Text(String(landmark.isFavorite))
      }
      .navigationBarTitle("Tutorials")
      .navigationBarItems(trailing: trailingItem())
    }
  }

  func trailingItem () -> some View {
    return HStack {
      NavigationLink(destination: SettingsView()) {
        Text("Settings")
      }
    }
  }
}

struct SettingsView: View {
  @EnvironmentObject var userData: UserData

  var body: some View {
    Form {
      Section(header: Text("General")) {
        Toggle(isOn: $userData.showFavoriteOnly) {
          Text("Favorites only")
        }
      }
    }.navigationBarTitle(Text("Settings"), displayMode: .inline)
  }
}
```

Body:
I would like to create a Settings view using SwiftUI. I mainly took the official example from Apple about SwiftUI to realize my code. The settings view should have a toggle to whether display or not my favorites items.

For now I have a landmarks list and a settings view.

struct Landmark: Hashable, Codable, Identifiable {
    var id: Int
    var imageName: String
    var title: String
    var isFavorite: Bool
    var description: String

    enum CodingKeys: String, CodingKey {
        case id, imageName, title, description
    }
}

final class UserData: ObservableObject {
    @Published var showFavoriteOnly: Bool = false
    @Published var items: [Landmark] = landmarkData
    @Published var showProfile: Bool = false
}

struct ItemList: View {
    @EnvironmentObject var userData: UserData
    @State var trailing: Bool = false

    init() {
        UITableView.appearance().separatorStyle = .none
    }

    var body: some View {
        NavigationView {
            List {
                VStack {
                    CircleBadgeView(text: String(landmarkData.count), thickness: 2)
                    Text("Tutorials available")
                }.frame(minWidth:0, maxWidth: .infinity)

                ForEach(userData.items) { landmark in
                    if !self.userData.showFavoriteOnly || landmark.isFavorite {
                        ZStack {
                            Image(landmark.imageName)
                                .resizable()
                                .frame(minWidth: 0, maxWidth: .infinity)
                                .cornerRadius(10)
                                .overlay(ImageOverlay(text: landmark.title), alignment: .bottomTrailing)
                            Text(String(landmark.isFavorite))

                            NavigationLink(destination: TutorialDetailView(landmark: landmark)) {
                                EmptyView()
                            }.buttonStyle(PlainButtonStyle())
                        }
                    }
                }
            }.navigationBarTitle("Tutorials")
                .navigationBarItems(trailing: trailingItem())
        }
    }
}

extension ItemList {
    func trailingItem () -> some View {
        return HStack {

            if userData.showProfile {
                NavigationLink(destination: ProfileView()) {
                    Image(systemName: "person.circle")
                        .imageScale(.large)
                        .accessibility(label: Text("Profile"))
                }
            }

            NavigationLink(destination: SettingsView().environmentObject(userData)) {
                Image(systemName: "gear")
                    .imageScale(.large)
                    .accessibility(label: Text("Settings"))
            }
        }
    }
}

As you can see my SettingsView is accessible from navigationBarItems of my NavigationView. I don't know if it's the problem or not but when I put the Toggle inside the ListView it works as expected. But now when I trigger the toggle to enable only favorite my application crash instantly.

I've tried to trigger the Show profile toggle from SettingsView and it works.

struct SettingsView: View {
    @EnvironmentObject var userData: UserData

    var body: some View {
        Form {
            Section(header: Text("General")) {
                Toggle(isOn: $userData.showProfile) {
                    Text("Show profile")
                }
                Toggle(isOn: $userData.showFavoriteOnly) {
                    Text("Favorites only")
                }
            }

            Section(header: Text("UI")) {
                Toggle(isOn: .constant(false)) {
                    Text("Dark mode")
                }

                NavigationLink(destination: Text("third")) {
                    Text("Third navigation")
                }
            }

        }.navigationBarTitle(Text("Settings"), displayMode: .inline)
    }
}

In brief, the crash appears in my SettingsView when I trigger the Show only favorite Toggle and then I try to go back to the previous view which is ItemListView

The only information I can get about the error is Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

You can find the whole project on my GitHub : https://github.com/Hurobaki/swiftui-tutorial

Some help would be really appreciated :)


问:
Comparing all the characters beetween two strings(even if they contain numbers)in java
Ok so I currently have a String array which contains keycodes, and i want to check if the first element shares common specifications with the second , e.g. [012] has similar elements with [123]. I currently loop through the length of the first element, and then loop through the length of the second element, and compare those two like this:
If(A[1].charAt(j) == A[2].charAt[i]) c++; c is a counter to show how many
common elements the keycodes have. Here is the method i created

```<code>   static boolean hasSimilarity(String[] A, int K, int i){
        int c = 0;
        for(int j = 0;j<K;j++){
            for(int m = j;m<K;m++){
                if(A[i].charAt(j) == A[i+1].charAt(m)) c++;
            }
        }
        return c != 0;
    }
</code>```

And here is the execution of it in the Main class:

```<code> int max = -1;
 findSimilar FS = new findSimilar();
 for (int i = 0; i < sum.length -1; i++) {
    boolean hasSimilar = FS.hasSimilarity(key,K,i);
    if (!hasSimilar) {
       int summ = sum[i] + sum[i + 1];
       System.out.println(summ);
       if (summ > max) {
          max = summ;
       }
    }
 }
</code>```

When i run this, i get a java.lang.StringIndexOutOfBoundsException out of range: 0 . What am I doing wrong? Is there any better way to compare two keycodes in order to find similarities beetween them?

答:
This error:

java.lang.StringIndexOutOfBoundsException out of range: 0

Can only occur if one of your strings is the blank string "".

You are attempting to get charAt(0) when there is no char 0 (ie first char).

——-

You would avoid this problem, and have a far more efficient algorithm, if you first collected the counts of each character then compared those, which would have time complexity O(n), whereas your algorithm is O(n2) (albeit that it seems your n - the length of your inputs - is small).

Body:
Ok so I currently have a String array which contains keycodes, and i want to check if the first element shares common specifications with the second , e.g. [012] has similar elements with [123]. I currently loop through the length of the first element, and then loop through the length of the second element, and compare those two like this:
If(A[1].charAt(j) == A[2].charAt[i]) c++; c is a counter to show how many
common elements the keycodes have. Here is the method i created

   static boolean hasSimilarity(String[] A, int K, int i){
        int c = 0;
        for(int j = 0;j<K;j++){
            for(int m = j;m<K;m++){
                if(A[i].charAt(j) == A[i+1].charAt(m)) c++;
            }
        }
        return c != 0;
    }

And here is the execution of it in the Main class:

 int max = -1;
 findSimilar FS = new findSimilar();
 for (int i = 0; i < sum.length -1; i++) {
    boolean hasSimilar = FS.hasSimilarity(key,K,i);
    if (!hasSimilar) {
       int summ = sum[i] + sum[i + 1];
       System.out.println(summ);
       if (summ > max) {
          max = summ;
       }
    }
 }

When i run this, i get a java.lang.StringIndexOutOfBoundsException out of range: 0 . What am I doing wrong? Is there any better way to compare two keycodes in order to find similarities beetween them?


问:
Typescript error after updating from version 2.9.2 to 3.7.5
I have an angular (version 6) project that is using typescript version 2.9.2.

I'm migrating to the latest version of angular, version 9.

One step of the migration is to update the typescript version, to 3.7.5.

After updating typescript I get a compilation error on one of the libs - https://github.com/jf3096/json-typescript-mapper - This lib is not active anymore.

187             instance[key] =  decoratorMetaData.customConverter.fromJson(json[decoratorMetaData.name || key]);
                  ~~~~~~~~~~~~~
  node_modules/json-typescript-mapper/index.ts:189:13 - error TS2536: Type 'string' cannot be used to index type 'T'.

Anyone had a similar problem after updating typescript?
Any ideas on how I can fix this?

Thanks

答:
As you've mentioned in the comments that you've followed everything as per guide, you may try the steps given below by manually upgrading TypeScript version.

Modify tsconfig.json file add:

```<code>{
  "compileOnSave": false,
  "compilerOptions": {
    // some props
  },
  "angularCompilerOptions": {
    "disableTypeScriptVersionCheck": true // <- ADD
  }
}
</code>```

(Optional) Delete package-lock.json and node-modules folder.

Do npm i again

Add npm i -D typescript@3.7.5 if not already done.

In src/polyfills.ts, at the very end add:

```<code>// @ts-ignore
window.__importDefault = function (mod) {
    return mod && mod.__esModule ? mod : { default: mod };
};
</code>```

Now continue testing your application by creating a build

Body:
As you've mentioned in the comments that you've followed everything as per guide, you may try the steps given below by manually upgrading TypeScript version.

Modify tsconfig.json file add:

{
  "compileOnSave": false,
  "compilerOptions": {
    // some props
  },
  "angularCompilerOptions": {
    "disableTypeScriptVersionCheck": true // <- ADD
  }
}

(Optional) Delete package-lock.json and node-modules folder.

Do npm i again

Add npm i -D typescript@3.7.5 if not already done.

In src/polyfills.ts, at the very end add:

// @ts-ignore
window.__importDefault = function (mod) {
    return mod && mod.__esModule ? mod : { default: mod };
};

Now continue testing your application by creating a build


问:
Invalid Signature in Auth 1.0a implementing in PHP
```<code>public function garminAction(){
    $url  =   'http://connectapitest.garmin.com/oauth-service-1.0/oauth/request_token';
    $oauth_consumer_key =   'XXXXXXXXX';
    $consumerSecret = 'XXXXXXXXX';
    $oauth_signature_method =   'HMAC-SHA1';
    $oauth_timestamp    =   time();
    $oauth_nonce    =   md5(mt_rand());
    $oauth_version  =   "1.0";
    $sig_string = urlencode($consumerSecret) . '&' . urlencode($oauth_consumer_key);
    $base_string1 =
    "POST&" .urlencode($url) . "&" .
    urlencode(
       "oauth_consumer_key=". $oauth_consumer_key
      . "&oauth_nonce=" . $oauth_nonce
      . "&oauth_signature_method=" . $oauth_signature_method
      . "&oauth_timestamp=" .$oauth_timestamp
      . "&oauth_version=" . $oauth_version
            );

    $oauthSig = base64_encode(hash_hmac("sha1", $base_string1, $sig_string, true));
    echo $oauthSig;
    $base_string =

    urlencode(
        "oauth_consumer_key=" . $oauth_consumer_key
        . "&oauth_signature_method=" . $oauth_signature_method
        . "&oauth_signature=" . $oauthSig
        . "&oauth_timestamp=" . $oauth_timestamp
        ."&oauth_version=" . $oauth_version
        . "&oauth_nonce=" . $oauth_nonce

    );

     $auth_header = "OAuth "
    . 'oauth_signature="' . rawurlencode($oauthSig) . '", '
    . 'oauth_version="' . rawurlencode($oauth_version) . '", '
    . 'oauth_nonce="' . rawurlencode($oauth_nonce) . '", '
    . 'oauth_signature_method="' . rawurlencode($oauth_signature_method) . '", '
    . 'oauth_consumer_key="' . rawurlencode($oauth_consumer_key) . '", '
    . 'oauth_timestamp="' . rawurlencode($oauth_timestamp) .'"';
    $ch = curl_init($url);

     curl_setopt($ch, CURLOPT_HTTPHEADER, [
         'Authorization: ' . $auth_header,
         'Content-Type: text/html'
     ]);
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $base_string);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $response = curl_exec($ch);
    echo $error = curl_errno ($ch);
    $error = curl_error($ch);
    echo $response;
    curl_close($ch);
    exit;

}
</code>```

Its reponse is:
HTTP Status 401 - Invalid signature for signature method HMAC-SHA1

Can you please help where the issue is in generating Signatures?

答:
Here is a sample that works for me (after a lot of trial & error and help from Garmin):</p>

```<code><?php
session_start();

$oauth_consumer_key = "XXXXXXXXX";
$oauth_consumer_secret = "XXXXXXXXX";
$oauth_signature_method = "HMAC-SHA1";
$oauth_token = "XXXXXXXXX";
$oauth_token_secret = "XXXXXXXXX";

$oauth_timestamp = time();
$oauth_version = "1.0";
$oauth_nonce = time();
$url = "https://connectapi.garmin.com/oauth-service/oauth/request_token";

$base_string = "POST&" . rawurlencode($url) ."&" .
    rawurlencode("oauth_consumer_key=$oauth_consumer_key"
        . "&oauth_nonce=$oauth_nonce"
        . "&oauth_signature_method=$oauth_signature_method"
        . "&oauth_timestamp=$oauth_timestamp"
        . "&oauth_version=$oauth_version");

$oauth_signature = hash_hmac("SHA1", $base_string, $oauth_consumer_secret . "&", false);
$oauth_signature = rawurlencode(base64_encode(pack('H*', $oauth_signature)));

$authorization_HTTP_header = "$url?oauth_consumer_key=". rawurlencode($oauth_consumer_key).
    "&oauth_signature_method=".$oauth_signature_method.
    "&oauth_timestamp=".$oauth_timestamp.
    "&oauth_nonce=". $oauth_nonce .
    "&oauth_version=1.0".
    "&oauth_signature=" . $oauth_signature;

$curl = curl_init();
curl_setopt_array($curl, array(
  CURLOPT_URL => $authorization_HTTP_header,
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",

));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}

?>
</code>```

Body:
public function garminAction(){
    $url  =   'http://connectapitest.garmin.com/oauth-service-1.0/oauth/request_token';
    $oauth_consumer_key =   'XXXXXXXXX';
    $consumerSecret = 'XXXXXXXXX';
    $oauth_signature_method =   'HMAC-SHA1';
    $oauth_timestamp    =   time();
    $oauth_nonce    =   md5(mt_rand());
    $oauth_version  =   "1.0";
    $sig_string = urlencode($consumerSecret) . '&' . urlencode($oauth_consumer_key);
    $base_string1 =
    "POST&" .urlencode($url) . "&" .
    urlencode(
       "oauth_consumer_key=". $oauth_consumer_key
      . "&oauth_nonce=" . $oauth_nonce
      . "&oauth_signature_method=" . $oauth_signature_method
      . "&oauth_timestamp=" .$oauth_timestamp
      . "&oauth_version=" . $oauth_version
            );

    $oauthSig = base64_encode(hash_hmac("sha1", $base_string1, $sig_string, true));
    echo $oauthSig;
    $base_string =

    urlencode(
        "oauth_consumer_key=" . $oauth_consumer_key
        . "&oauth_signature_method=" . $oauth_signature_method
        . "&oauth_signature=" . $oauthSig
        . "&oauth_timestamp=" . $oauth_timestamp
        ."&oauth_version=" . $oauth_version
        . "&oauth_nonce=" . $oauth_nonce

    );

     $auth_header = "OAuth "
    . 'oauth_signature="' . rawurlencode($oauthSig) . '", '
    . 'oauth_version="' . rawurlencode($oauth_version) . '", '
    . 'oauth_nonce="' . rawurlencode($oauth_nonce) . '", '
    . 'oauth_signature_method="' . rawurlencode($oauth_signature_method) . '", '
    . 'oauth_consumer_key="' . rawurlencode($oauth_consumer_key) . '", '
    . 'oauth_timestamp="' . rawurlencode($oauth_timestamp) .'"';
    $ch = curl_init($url);

     curl_setopt($ch, CURLOPT_HTTPHEADER, [
         'Authorization: ' . $auth_header,
         'Content-Type: text/html'
     ]);
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $base_string);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $response = curl_exec($ch);
    echo $error = curl_errno ($ch);
    $error = curl_error($ch);
    echo $response;
    curl_close($ch);
    exit;

}

Its reponse is:
HTTP Status 401 - Invalid signature for signature method HMAC-SHA1

Can you please help where the issue is in generating Signatures?

Body:
Here is a sample that works for me (after a lot of trial & error and help from Garmin):

<?php
session_start();

$oauth_consumer_key = "XXXXXXXXX";
$oauth_consumer_secret = "XXXXXXXXX";
$oauth_signature_method = "HMAC-SHA1";
$oauth_token = "XXXXXXXXX";
$oauth_token_secret = "XXXXXXXXX";

$oauth_timestamp = time();
$oauth_version = "1.0";
$oauth_nonce = time();
$url = "https://connectapi.garmin.com/oauth-service/oauth/request_token";

$base_string = "POST&" . rawurlencode($url) ."&" .
    rawurlencode("oauth_consumer_key=$oauth_consumer_key"
        . "&oauth_nonce=$oauth_nonce"
        . "&oauth_signature_method=$oauth_signature_method"
        . "&oauth_timestamp=$oauth_timestamp"
        . "&oauth_version=$oauth_version");

$oauth_signature = hash_hmac("SHA1", $base_string, $oauth_consumer_secret . "&", false);
$oauth_signature = rawurlencode(base64_encode(pack('H*', $oauth_signature)));

$authorization_HTTP_header = "$url?oauth_consumer_key=". rawurlencode($oauth_consumer_key).
    "&oauth_signature_method=".$oauth_signature_method.
    "&oauth_timestamp=".$oauth_timestamp.
    "&oauth_nonce=". $oauth_nonce .
    "&oauth_version=1.0".
    "&oauth_signature=" . $oauth_signature;

$curl = curl_init();
curl_setopt_array($curl, array(
  CURLOPT_URL => $authorization_HTTP_header,
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",

));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}

?>


问:
an error occur when running a c++ script in cygwin
I tryed to run the following code in my cygwin

#include<iostream>
#include<cstdio>
using namespace std;
const int NR=2005;
int n,m;
bool arr[NR][NR];
int mx_jx(int x){
    int up[NR][NR],lf[NR][NR],rt[NR][NR];
    for(int i=1;i<=n;i++)
        for(int j=1;j<=m;j++)
            up[i][j]=1,lf[i][j]=rt[i][j]=j;
    for(int i=1;i<=n;i++)
        for(int j=2;j<=m;j++)
            if(arr[i][j-1]==x)lf[i][j]=lf[i][j-1];
    for(int i=1;i<=n;i++)
        for(int j=m-1;j>=1;j--)
            if(arr[i][j+1]==x)rt[i][j]=rt[i][j+1];
    int ans=0;
    for(int i=1;i<=n;i++)
        for(int j=1;j<=m;j++){
            if(arr[i][j]!=x)continue;
            if(i>1 && arr[i-1][j]==x){
                up[i][j]=arr[i][j-1]+1;
                lf[i][j]=max(lf[i][j],lf[i-1][j]);
                rt[i][j]=min(rt[i][j],rt[i-1][j]);
            }
            ans=max(ans,(rt[i][j]-lf[i][j]+1)*up[i][j]);
        }
    return ans;
}
int main(){
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++)
        for(int j=1;j<=m;j++){
            int tmp;
            scanf("%d",&tmp);
            arr[i][j]=(int)tmp;
            if((i+j)&1)arr[i][j]=!arr[i][j];
        }

    printf("%d",max(mx_jx(0),mx_jx(1)));
    return 0;
}
```

<p>It passed the compile(0 warning,0 error), but when I tried to run it with the following input</p>

```4 4
0 1 1 1
1 1 1 0
0 1 1 0
1 1 0 1
```

It says "Command terminated"

these code could run correctly on other platform, how can I solve this problem on cygwin? thanks a lot

答:
While the answer from user3684240 is valid and it is definitely an issue with your code, more likely you have Stack Overflow due to allocating numerous huge arrays on stack and in global memory area.

You should use std::vector<std::vector<int> instead of plain C arrays.

```<code>std::vector<std::vector<int>> up(NR, std::vector<int>(NR, 0));
std::vector<std::vector<int>> lf(NR, std::vector<int>(NR, 0));
std::vector<std::vector<int>> rt(NR, std::vector<int>(NR, 0));
</code>```

It is not very well optimized, but it's simplest solution I can provide.

For that bool array though, std::vector might behave... strange. I cannot give 100% guarantee that it will work if you simply substitute bool[][] with std::vector<std::vector<bool>> without testing it properly, because std::vector<bool> is optimized for memory and it has certain quirks that one should be aware of when using it.

You can try and see if that array of bools in global memory works (after changing arrays in mx_jx to vectors), maybe it does and you don't have to change it. If it doesn't, you can try to change to vector of vectors, then it should work.

Body:
I tryed to run the following code in my cygwin

#include<iostream>
#include<cstdio>
using namespace std;
const int NR=2005;
int n,m;
bool arr[NR][NR];
int mx_jx(int x){
    int up[NR][NR],lf[NR][NR],rt[NR][NR];
    for(int i=1;i<=n;i++)
        for(int j=1;j<=m;j++)
            up[i][j]=1,lf[i][j]=rt[i][j]=j;
    for(int i=1;i<=n;i++)
        for(int j=2;j<=m;j++)
            if(arr[i][j-1]==x)lf[i][j]=lf[i][j-1];
    for(int i=1;i<=n;i++)
        for(int j=m-1;j>=1;j--)
            if(arr[i][j+1]==x)rt[i][j]=rt[i][j+1];
    int ans=0;
    for(int i=1;i<=n;i++)
        for(int j=1;j<=m;j++){
            if(arr[i][j]!=x)continue;
            if(i>1 && arr[i-1][j]==x){
                up[i][j]=arr[i][j-1]+1;
                lf[i][j]=max(lf[i][j],lf[i-1][j]);
                rt[i][j]=min(rt[i][j],rt[i-1][j]);
            }
            ans=max(ans,(rt[i][j]-lf[i][j]+1)*up[i][j]);
        }
    return ans;
}
int main(){
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++)
        for(int j=1;j<=m;j++){
            int tmp;
            scanf("%d",&tmp);
            arr[i][j]=(int)tmp;
            if((i+j)&1)arr[i][j]=!arr[i][j];
        }

    printf("%d",max(mx_jx(0),mx_jx(1)));
    return 0;
}

It passed the compile(0 warning,0 error), but when I tried to run it with the following input

4 4
0 1 1 1
1 1 1 0
0 1 1 0
1 1 0 1

It says "Command terminated"

these code could run correctly on other platform, how can I solve this problem on cygwin? thanks a lot

Body:
While the answer from user3684240 is valid and it is definitely an issue with your code, more likely you have Stack Overflow due to allocating numerous huge arrays on stack and in global memory area.

You should use std::vector<std::vector<int> instead of plain C arrays.

std::vector<std::vector<int>> up(NR, std::vector<int>(NR, 0));
std::vector<std::vector<int>> lf(NR, std::vector<int>(NR, 0));
std::vector<std::vector<int>> rt(NR, std::vector<int>(NR, 0));

It is not very well optimized, but it's simplest solution I can provide.

For that bool array though, std::vector might behave... strange. I cannot give 100% guarantee that it will work if you simply substitute bool[][] with std::vector<std::vector<bool>> without testing it properly, because std::vector<bool> is optimized for memory and it has certain quirks that one should be aware of when using it.

You can try and see if that array of bools in global memory works (after changing arrays in mx_jx to vectors), maybe it does and you don't have to change it. If it doesn't, you can try to change to vector of vectors, then it should work.


问:
Spring Boot: Type cannot be null; nested exception is java.lang.IllegalArgumentException: Type cannot be null when running Stored Procedue
Good morning, I am new to Spring Boot, and I am performing a rest service that must invoke a procedure stored in the database, the question is that you receive the mobile and must return a code and result, as shown below:

This is my code:

Main Class

```<code>package com.app.validacion;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App {

    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}
</code>```

Controller

```<code>package com.app.validacion.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import com.app.validacion.dao.DriverBonificadosRepository;
import com.app.validacion.entity.RespuestaVo;

@RestController
public class DriverBonificadosController {

    @Autowired
    private DriverBonificadosRepository dao;

    @GetMapping("/service/{movil}")
    public RespuestaVo  ConsultarMovil(@PathVariable String movil) {
        return dao.validarClienteBonifiado(movil);

    }
}
</code>```

Repository

```<code>package com.app.validacion.dao;

import org.springframework.data.jpa.repository.query.Procedure;
import org.springframework.data.repository.CrudRepository;

import com.app.validacion.entity.DriverBonificados;
import com.app.validacion.entity.RespuestaVo;

public interface DriverBonificadosRepository extends CrudRepository<DriverBonificados, Integer> {

    @Procedure(procedureName="ValidacionClienteBonificado")
    RespuestaVo validarClienteBonifiado(String pMovil);
}
</code>```

My entity

```<code>import javax.persistence.NamedStoredProcedureQueries;
import javax.persistence.NamedStoredProcedureQuery;
import javax.persistence.ParameterMode;
import javax.persistence.StoredProcedureParameter;
import javax.persistence.Table;

@NamedStoredProcedureQueries({
    @NamedStoredProcedureQuery(
            name="SPValidationClienteBonus4G",
            procedureName="ValidacionClienteBonificado",
            parameters = {
                    @StoredProcedureParameter(mode=ParameterMode.IN, name="p_movil",type=String.class),
                    @StoredProcedureParameter(mode=ParameterMode.OUT, name="code",type=String.class),
                    @StoredProcedureParameter(mode=ParameterMode.OUT, name="result",type=String.class),
            })

})

@Entity
@Table
public class DriverBonificados {

    @Id
    private int id;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getMovil() {
        return movil;
    }
    public void setMovil(String movil) {
        this.movil = movil;
    }
    public String getContador() {
        return contador;
    }
    public void setContador(String contador) {
        this.contador = contador;
    }
    public Date getFecha_driver() {
        return fecha_driver;
    }
    public void setFecha_driver(Date fecha_driver) {
        this.fecha_driver = fecha_driver;
    }
    public Date getFecha_alta() {
        return fecha_alta;
    }
    public void setFecha_alta(Date fecha_alta) {
        this.fecha_alta = fecha_alta;
    }
    public Date getFecha_fin() {
        return fecha_fin;
    }
    public void setFecha_fin(Date fecha_fin) {
        this.fecha_fin = fecha_fin;
    }
    public Date getCodigo_transaccion() {
        return codigo_transaccion;
    }
    public void setCodigo_transaccion(Date codigo_transaccion) {
        this.codigo_transaccion = codigo_transaccion;
    }
    private String movil;
    private String contador;
    private Date fecha_driver;
    private Date fecha_alta;
    private Date fecha_fin;
    private Date codigo_transaccion;
</code>```

My Class RespuestaVo

```<code>package com.app.validacion.entity;

public class RespuestaVo {

    private String code;
    private String result;

    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getResult() {
        return result;
    }
    public void setResult(String result) {
        this.result = result;
    }

}
</code>```

And I get the following error (the mobile parameter must be received as a String, since in the database it is found as Varchar):

Anyone have an idea how this problem could be solved? I need to consult via Stored Procedue if or if

UPDATE

Using @Query and modifying the code as follows:

```<code>package com.app.validacion.dao;

import org.springframework.data.jpa.repository.Query;
import org.springframework.data.jpa.repository.query.Procedure;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;

import com.app.validacion.entity.DriverBonificados;
import com.app.validacion.entity.RespuestaVo;

public interface DriverBonificadosRepository extends CrudRepository<DriverBonificados, Integer> {

    @Query(nativeQuery = true,value = "call ValidacionClienteBonificado(:movil)")
    RespuestaVo validarClienteBonifiado(@Param("movil") String pMovil);
}
</code>```

I get the following error:

org.springframework.core.convert.ConverterNotFoundException: No
  converter found capable of converting from type
  [org.springframework.data.jpa.repository.query.AbstractJpaQuery$TupleConverter$TupleBackedMap]
  to type [com.app.validacion.entity.RespuestaVo]   at
  org.springframework.core.convert.support.GenericConversionService.handleConverterNotFound(GenericConversionService.java:321)
  ~[spring-core-5.2.1.RELEASE.jar:5.2.1.RELEASE]    at
  org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:194)
  ~[spring-core-5.2.1.RELEASE.jar:5.2.1.RELEASE]    at
  org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:174)
  ~[spring-core-5.2.1.RELEASE.jar:5.2.1.RELEASE]    at
  org.springframework.data.repository.query.ResultProcessor$ProjectingConverter.convert(ResultProcessor.java:297)
  ~[spring-data-commons-2.2.1.RELEASE.jar:2.2.1.RELEASE]    at
  org.springframework.data.repository.query.ResultProcessor$ChainingConverter.lambda$and$0(ResultProcessor.java:217)
  ~[spring-data-commons-2.2.1.RELEASE.jar:2.2.1.RELEASE]    at
  org.springframework.data.repository.query.ResultProcessor$ChainingConverter.convert(ResultProcessor.java:228)
  ~[spring-data-commons-2.2.1.RELEASE.jar:2.2.1.RELEASE]    at
  org.springframework.data.repository.query.ResultProcessor.processResult(ResultProcessor.java:170)
  ~[spring-data-commons-2.2.1.RELEASE.jar:2.2.1.RELEASE]    at
  org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:157)
  ~[spring-data-jpa-2.2.1.RELEASE.jar:2.2.1.RELEASE]

答:
Try this -</p>

```<code>@GetMapping("/service/{movil}")
public RespuestaVo  ConsultarMovil(@PathVariable("movil") String movil) {
    return dao.validarClienteBonifiado(movil);

}
</code>```

Body:
Good morning, I am new to Spring Boot, and I am performing a rest service that must invoke a procedure stored in the database, the question is that you receive the mobile and must return a code and result, as shown below:

This is my code:

Main Class

package com.app.validacion;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App {

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

Controller

package com.app.validacion.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import com.app.validacion.dao.DriverBonificadosRepository;
import com.app.validacion.entity.RespuestaVo;

@RestController
public class DriverBonificadosController {

    @Autowired
    private DriverBonificadosRepository dao;

    @GetMapping("/service/{movil}")
    public RespuestaVo  ConsultarMovil(@PathVariable String movil) {
        return dao.validarClienteBonifiado(movil);

    }
}

Repository

package com.app.validacion.dao;

import org.springframework.data.jpa.repository.query.Procedure;
import org.springframework.data.repository.CrudRepository;

import com.app.validacion.entity.DriverBonificados;
import com.app.validacion.entity.RespuestaVo;

public interface DriverBonificadosRepository extends CrudRepository<DriverBonificados, Integer> {

    @Procedure(procedureName="ValidacionClienteBonificado")
    RespuestaVo validarClienteBonifiado(String pMovil);
}

My entity

import javax.persistence.NamedStoredProcedureQueries;
import javax.persistence.NamedStoredProcedureQuery;
import javax.persistence.ParameterMode;
import javax.persistence.StoredProcedureParameter;
import javax.persistence.Table;

@NamedStoredProcedureQueries({
    @NamedStoredProcedureQuery(
            name="SPValidationClienteBonus4G",
            procedureName="ValidacionClienteBonificado",
            parameters = {
                    @StoredProcedureParameter(mode=ParameterMode.IN, name="p_movil",type=String.class),
                    @StoredProcedureParameter(mode=ParameterMode.OUT, name="code",type=String.class),
                    @StoredProcedureParameter(mode=ParameterMode.OUT, name="result",type=String.class),
            })

})

@Entity
@Table
public class DriverBonificados {

    @Id
    private int id;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getMovil() {
        return movil;
    }
    public void setMovil(String movil) {
        this.movil = movil;
    }
    public String getContador() {
        return contador;
    }
    public void setContador(String contador) {
        this.contador = contador;
    }
    public Date getFecha_driver() {
        return fecha_driver;
    }
    public void setFecha_driver(Date fecha_driver) {
        this.fecha_driver = fecha_driver;
    }
    public Date getFecha_alta() {
        return fecha_alta;
    }
    public void setFecha_alta(Date fecha_alta) {
        this.fecha_alta = fecha_alta;
    }
    public Date getFecha_fin() {
        return fecha_fin;
    }
    public void setFecha_fin(Date fecha_fin) {
        this.fecha_fin = fecha_fin;
    }
    public Date getCodigo_transaccion() {
        return codigo_transaccion;
    }
    public void setCodigo_transaccion(Date codigo_transaccion) {
        this.codigo_transaccion = codigo_transaccion;
    }
    private String movil;
    private String contador;
    private Date fecha_driver;
    private Date fecha_alta;
    private Date fecha_fin;
    private Date codigo_transaccion;

My Class RespuestaVo

package com.app.validacion.entity;

public class RespuestaVo {

    private String code;
    private String result;

    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getResult() {
        return result;
    }
    public void setResult(String result) {
        this.result = result;
    }

}

And I get the following error (the mobile parameter must be received as a String, since in the database it is found as Varchar):

Anyone have an idea how this problem could be solved? I need to consult via Stored Procedue if or if

UPDATE

Using @Query and modifying the code as follows:

package com.app.validacion.dao;

import org.springframework.data.jpa.repository.Query;
import org.springframework.data.jpa.repository.query.Procedure;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;

import com.app.validacion.entity.DriverBonificados;
import com.app.validacion.entity.RespuestaVo;

public interface DriverBonificadosRepository extends CrudRepository<DriverBonificados, Integer> {

    @Query(nativeQuery = true,value = "call ValidacionClienteBonificado(:movil)")
    RespuestaVo validarClienteBonifiado(@Param("movil") String pMovil);
}

I get the following error:

org.springframework.core.convert.ConverterNotFoundException: No
  converter found capable of converting from type
  [org.springframework.data.jpa.repository.query.AbstractJpaQuery$TupleConverter$TupleBackedMap]
  to type [com.app.validacion.entity.RespuestaVo]   at
  org.springframework.core.convert.support.GenericConversionService.handleConverterNotFound(GenericConversionService.java:321)
  ~[spring-core-5.2.1.RELEASE.jar:5.2.1.RELEASE]    at
  org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:194)
  ~[spring-core-5.2.1.RELEASE.jar:5.2.1.RELEASE]    at
  org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:174)
  ~[spring-core-5.2.1.RELEASE.jar:5.2.1.RELEASE]    at
  org.springframework.data.repository.query.ResultProcessor$ProjectingConverter.convert(ResultProcessor.java:297)
  ~[spring-data-commons-2.2.1.RELEASE.jar:2.2.1.RELEASE]    at
  org.springframework.data.repository.query.ResultProcessor$ChainingConverter.lambda$and$0(ResultProcessor.java:217)
  ~[spring-data-commons-2.2.1.RELEASE.jar:2.2.1.RELEASE]    at
  org.springframework.data.repository.query.ResultProcessor$ChainingConverter.convert(ResultProcessor.java:228)
  ~[spring-data-commons-2.2.1.RELEASE.jar:2.2.1.RELEASE]    at
  org.springframework.data.repository.query.ResultProcessor.processResult(ResultProcessor.java:170)
  ~[spring-data-commons-2.2.1.RELEASE.jar:2.2.1.RELEASE]    at
  org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:157)
  ~[spring-data-jpa-2.2.1.RELEASE.jar:2.2.1.RELEASE]

Body:
Try this -

@GetMapping("/service/{movil}")
public RespuestaVo  ConsultarMovil(@PathVariable("movil") String movil) {
    return dao.validarClienteBonifiado(movil);

}


问:
how can manipulate the different kind of array (string, int, char) as same format such as string in C#?
I have a collection of objects that each object would contains a different kind of array (string[],int[],char[]) or even single value as different types.

I want to get the values of each array as single format such as string  and convert it to a comma text value.

here is the code that manipulates an object of collection as "UInt16[]"

```<code>UInt16[] arrCapabilities = (UInt16[])(queryObj["Capabilities"]);
foreach (UInt16 arrValue in arrCapabilities)
{
    Console.WriteLine("Capabilities: {0}", arrValue);
}
</code>```

答:
You could try using the following code:</p>

```<code>IEnumerable array = queryObj["Capabilities"] as IEnumerable;
if(array != null)
{
    foreach(var item in array)
    {
        Console.WriteLine(item.ToString());
    }
}
else
{
    Console.WriteLine(queryObj["Capabilities"].ToString());
}
</code>```

Body:
I have a collection of objects that each object would contains a different kind of array (string[],int[],char[]) or even single value as different types.

I want to get the values of each array as single format such as string  and convert it to a comma text value.

here is the code that manipulates an object of collection as "UInt16[]"

UInt16[] arrCapabilities = (UInt16[])(queryObj["Capabilities"]);
foreach (UInt16 arrValue in arrCapabilities)
{
    Console.WriteLine("Capabilities: {0}", arrValue);
}

Body:
You could try using the following code:

IEnumerable array = queryObj["Capabilities"] as IEnumerable;
if(array != null)
{
    foreach(var item in array)
    {
        Console.WriteLine(item.ToString());
    }
}
else
{
    Console.WriteLine(queryObj["Capabilities"].ToString());
}


问:
How to test login with Dusk on a Laravel/Lighthouse/Passport/Nuxt App?
I've setup a Nuxt app with Laravel, and before doing too much I would like to setup Dusk testing. The app/login works great but I can't make it work on automated Dusk tests.

It use lighthouse-graphql-passport-auth with the setup described here. I think the issue is probably with the token generation in the Dusk environment.

Here is the example test which I can't make work:

```<code>public function testWithLoggedIn()
{
    $user = factory(User::class)->create([
        'email' => 'test@dusk.com',
        'password' => bcrypt('test'),
    ]);

    $this->browse(function ($browser) use ($user) {
        $browser->visit('/login')
                ->type('username', $user->email)
                ->type('password', 'test')
                ->press('Login')
                ->assertSee('Hello First User');
    });
}
</code>```

So I already tried a few things. For example if I add this in the setUp() method:

```<code>$this->artisan('passport:install');
$client = Client::findOrFail(2);
config()->set('lighthouse-graphql-passport.client_id', 2);
config()->set('lighthouse-graphql-passport.client_secret', $client->secret);
</code>```

I get this error:

```<code>Error: GraphQL error: Client authentication failed
</code>```

I also tried to add the same informations as I have locally for the oauth_clients. Unfortunately the redirect is different ('http://local.test' for local, and 'http://apache' when testing in dusk).

```<code>DB::table('oauth_clients')->insert([
        'id' => 2,
        'name' => 'Apps Password Grant Client',
        'secret' => 'SWjOP5Y8NzxEx7z3dlaVs08VDUWgrSl96l4V9JO3',
        'redirect' => 'http://apache',
        'personal_access_client' => 0,
        'password_client' => 1,
        'revoked' => 0,
        'created_at' => '2020-02-17 11:02:33',
        'updated_at' => '2020-02-17 11:02:33',
    ]);
</code>```

This returns this kind of error:

```<code>Error: GraphQL error: The provided authorization grant (e.g., authorization code, resource owner credentials) or refresh token is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client.
</code>```

How should I test this application? Everything will be behind this login screen so there is probably a way, and if needed I can change the login method (maybe without using passport).

答:
It turns out the second solution with the DB::table insertion worked.

The missing thing was to wait a little in the test before the assert (with an ->pause(300) or a ->waitFor('.selector', 0.2).

For example this worked:

```<code>$this->browse(function ($browser) use ($user) {
        $browser->visit('/login')
                ->type('username', $user->email)
                ->type('password', 'test')
                ->press('Login')
                ->waitFor('.admin-dashboard', 0.2)
                ->assertSee('Welcome');
    });
</code>```

Body:
I've setup a Nuxt app with Laravel, and before doing too much I would like to setup Dusk testing. The app/login works great but I can't make it work on automated Dusk tests.

It use lighthouse-graphql-passport-auth with the setup described here. I think the issue is probably with the token generation in the Dusk environment.

Here is the example test which I can't make work:

public function testWithLoggedIn()
{
    $user = factory(User::class)->create([
        'email' => 'test@dusk.com',
        'password' => bcrypt('test'),
    ]);

    $this->browse(function ($browser) use ($user) {
        $browser->visit('/login')
                ->type('username', $user->email)
                ->type('password', 'test')
                ->press('Login')
                ->assertSee('Hello First User');
    });
}

So I already tried a few things. For example if I add this in the setUp() method:

$this->artisan('passport:install');
$client = Client::findOrFail(2);
config()->set('lighthouse-graphql-passport.client_id', 2);
config()->set('lighthouse-graphql-passport.client_secret', $client->secret);

I get this error:

Error: GraphQL error: Client authentication failed

I also tried to add the same informations as I have locally for the oauth_clients. Unfortunately the redirect is different ('http://local.test' for local, and 'http://apache' when testing in dusk).

DB::table('oauth_clients')->insert([
        'id' => 2,
        'name' => 'Apps Password Grant Client',
        'secret' => 'SWjOP5Y8NzxEx7z3dlaVs08VDUWgrSl96l4V9JO3',
        'redirect' => 'http://apache',
        'personal_access_client' => 0,
        'password_client' => 1,
        'revoked' => 0,
        'created_at' => '2020-02-17 11:02:33',
        'updated_at' => '2020-02-17 11:02:33',
    ]);

This returns this kind of error:

Error: GraphQL error: The provided authorization grant (e.g., authorization code, resource owner credentials) or refresh token is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client.

How should I test this application? Everything will be behind this login screen so there is probably a way, and if needed I can change the login method (maybe without using passport).

Body:
It turns out the second solution with the DB::table insertion worked.

The missing thing was to wait a little in the test before the assert (with an ->pause(300) or a ->waitFor('.selector', 0.2).

For example this worked:

$this->browse(function ($browser) use ($user) {
        $browser->visit('/login')
                ->type('username', $user->email)
                ->type('password', 'test')
                ->press('Login')
                ->waitFor('.admin-dashboard', 0.2)
                ->assertSee('Welcome');
    });


问:
How to convert an array as follows?
I have an array

```<code>[
    [
        'title' => 'title0',
        'data' => 'data0'
    ],
    [
        'title' => 'title1',
        'data' => 'data1'
    ]
]
</code>```

I need to get the output

```<code>[
    'title' => ['title0','title1'],
    'data' => ['data0', 'data1']
]
</code>```

Please tell me how can I do this?

答:
You can do it like this

```<code><?php
$shortedArray = [
    'title' => [],
    'data' => []
];

$mainArray = [
    [
        'title' => 'test0',
        'data' => 'data0'
    ],
    [
        'title' => 'test1',
        'data' => 'data1'
    ]
];

// Loop thru it
foreach($mainArray as $row){
  $shortedArray['title'][] = $row['title'];
  $shortedArray['data'][] = $row['data'];
}
print_r($shortedArray);
</code>```

Hope this resolves your issue. Any query, let me know

Title: How to convert an array as follows?

Body:
I have an array

[
    [
        'title' => 'title0',
        'data' => 'data0'
    ],
    [
        'title' => 'title1',
        'data' => 'data1'
    ]
]

I need to get the output

[
    'title' => ['title0','title1'],
    'data' => ['data0', 'data1']
]

Please tell me how can I do this?

Body:
You can do it like this

<?php
$shortedArray = [
    'title' => [],
    'data' => []
];

$mainArray = [
    [
        'title' => 'test0',
        'data' => 'data0'
    ],
    [
        'title' => 'test1',
        'data' => 'data1'
    ]
];

// Loop thru it
foreach($mainArray as $row){
  $shortedArray['title'][] = $row['title'];
  $shortedArray['data'][] = $row['data'];
}
print_r($shortedArray);

Hope this resolves your issue. Any query, let me know


问:
Why does my PHP string comparison fail?
I have the following snippet of code

```<code>if ($summary == "CFD funding Interest Paid" ||
    $summary == "Commissions" ||
    $summary == "Closing trades") {
    print $summary.",".$date.",".$reference.",".$description.",".$amount."<br>";
}
else {
    print $summary."*<br>";
}
</code>```

It outputs the following

```
Commissions*
Commissions*
Closing trades*
Commissions*
Closing trades*
```

How come the strings do not appear to be matching?

答:
Add trim() before the if (), it removes unvisible chars like whitespace...

```<code>$summary = trim($summary);
if ($summary == "CF...
</code>```

Title: Why does my PHP string comparison fail?

Body:
I have the following snippet of code

if ($summary == "CFD funding Interest Paid" ||
    $summary == "Commissions" ||
    $summary == "Closing trades") {
    print $summary.",".$date.",".$reference.",".$description.",".$amount."
";
}
else {
    print $summary."*
";
}

It outputs the following

Commissions*
Commissions*
Closing trades*
Commissions*
Closing trades*

How come the strings do not appear to be matching?

Body:
Add trim() before the if (), it removes unvisible chars like whitespace...

$summary = trim($summary);
if ($summary == "CF...


问:
Migration From CRM to cloud 365. Ribbon Workbench export solution
We migrate from CRM desktop version to dynamics 365 cloud version.
I need to import buttons for entity. Can I export them from the old version by solution and import them to new version of CRM as an unmanaged solution? Please explain the flow I should follow. Thank you!
P.S Preferable via XRM toolbox</p>

答:
Do you mean you crm is been moved (migrated) from OnPrem to OnLine(cloud).
If you are migrating, it will contain your custom buttons as well. you do not need to export and import. But if you wish to explicitly move some buttons only you can do so with solution import and unmanaged as well. </p>


问:
How to capitalize first letter razor
I am new to MVC and have not found a solution for this online.

I have the html as :

```<code>@Html.DisplayFor(model => model.Address1) <br />
</code>```

I want all the first letter of address1 to be capital letters e.g. Something Road instead of something road.

Now I have a class client and property Address1 and using EF to get the address as follow:

```<code> public class MyDBContext : DbContext
    {
        public DbSet<Client> Clients { get; set; }
    }
</code>```

Hope it makes sense.

答:
Using Bootstrap 4.x with Razor you use CSS to capitalize the first letter:</p>

```<code><p class="text-capitalize">CapiTaliZed text.</p>
</code>```

Title: How to capitalize first letter razor

Body:
I am new to MVC and have not found a solution for this online.

I have the html as :

@Html.DisplayFor(model => model.Address1)

I want all the first letter of address1 to be capital letters e.g. Something Road instead of something road.

Now I have a class client and property Address1 and using EF to get the address as follow:

 public class MyDBContext : DbContext
    {
        public DbSet<Client> Clients { get; set; }
    }

Hope it makes sense.

Body:
Using Bootstrap 4.x with Razor you use CSS to capitalize the first letter:

<p class="text-capitalize">CapiTaliZed text.</p>


答:
You didn't show any attempt, but I'm bored.  Just loop the keys from the first sub-array and extract that column.  No need to know what the keys are:

```<code>foreach(array_keys(reset($array)) as $key) {
    $result[$key] = array_column($array, $key);
}
</code>```

You could also do it this way:

```<code>foreach(reset($array) as $key => $val) {
    $result[$key] = array_column($array, $key);
}
</code>```

Or if it's as simple as those two known keys:

```<code>$result = ['title' => array_column($array, 'title'),
           'data'  => array_column($array, 'data')
          ];
</code>```

Title: How to convert an array as follows?

Body:
You didn't show any attempt, but I'm bored.  Just loop the keys from the first sub-array and extract that column.  No need to know what the keys are:

foreach(array_keys(reset($array)) as $key) {
    $result[$key] = array_column($array, $key);
}

You could also do it this way:

foreach(reset($array) as $key => $val) {
    $result[$key] = array_column($array, $key);
}

Or if it's as simple as those two known keys:

$result = ['title' => array_column($array, 'title'),
           'data'  => array_column($array, 'data')
          ];


问:
Javascript Binary Search algorithm unable to find number in the list
The following code seems to be unable to find the number in the list. Why might this be?

Trying this with the number to search for as '9' and the array of numbers consisting of numbers between 1-10 inclusively.

array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
count = 0;

function binarySearch(array, number) {
    mid = Math.floor(array.length / 2);
    if (number === array[mid]) {
        return count;
    }

    else if (number < array[mid] && array.length > 1) {
        count++;
        arrayFirst = array.splice(0, array[mid]);
        console.log("Tried: ", array[mid])
        console.log(arrayFirst);
        return binarySearch(arrayFirst, number);
    }

    else if (number > array[mid] && array.length > 1) {
        count++;
        arraySecond = array.splice(array[mid], array.length);
        console.log("Tried: ", array[mid])
        console.log(arraySecond);
        return binarySearch(arraySecond, number);
    }

    else {
        return 'number doesnt exist';
    }

}
console.log(binarySearch(array, 4));```
</div>
</div>

The code is now struggling with finding the number 10
New Edit:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>       array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,13,14,15,16,17,18,19,20];
    count = 0;

    function binarySearch(array, number) {
        mid = Math.floor(array.length/ 2);
        if (number === array[mid]) {
            return count;
        }

        else if (number < array[mid] && array.length > 1) {
            count++;
            arrayFirst = array.splice(0, mid);
            console.log("Tried: ", array[mid])
            console.log(arrayFirst);
            return binarySearch(arrayFirst, number);
        }

        else if (number > array[mid] && array.length > 1) {
            count++;
            arraySecond = array.splice(array[mid], mid);
            console.log("Tried: ", array[mid])
            console.log(arraySecond);
            return binarySearch(arraySecond, number);
        }

        else {
            return 'number doesnt exist';
        }

    }

    console.log(binarySearch(array, 10));</code>```

答:
Few pointers here:

Your condition includes an undefined variable arr. You've  been using array.

Your array must be array = [1,2,3]

I would suggest to instantiate your variables arrayFirst, mid, arraySecond as const const mid = ... so they are block scoped and not global vars

Edit: Looks like you've modified your arr condition. Please avoid edits as it makes answers irrelevant.

Body:
The following code seems to be unable to find the number in the list. Why might this be?

Trying this with the number to search for as '9' and the array of numbers consisting of numbers between 1-10 inclusively.

array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
count = 0;

function binarySearch(array, number) {
    mid = Math.floor(array.length / 2);
    if (number === array[mid]) {
        return count;
    }

    else if (number < array[mid] && array.length > 1) {
        count++;
        arrayFirst = array.splice(0, array[mid]);
        console.log("Tried: ", array[mid])
        console.log(arrayFirst);
        return binarySearch(arrayFirst, number);
    }

    else if (number > array[mid] && array.length > 1) {
        count++;
        arraySecond = array.splice(array[mid], array.length);
        console.log("Tried: ", array[mid])
        console.log(arraySecond);
        return binarySearch(arraySecond, number);
    }

    else {
        return 'number doesnt exist';
    }

}
console.log(binarySearch(array, 4));

The code is now struggling with finding the number 10
New Edit:

       array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,13,14,15,16,17,18,19,20];
    count = 0;

    function binarySearch(array, number) {
        mid = Math.floor(array.length/ 2);
        if (number === array[mid]) {
            return count;
        }

        else if (number < array[mid] && array.length > 1) {
            count++;
            arrayFirst = array.splice(0, mid);
            console.log("Tried: ", array[mid])
            console.log(arrayFirst);
            return binarySearch(arrayFirst, number);
        }

        else if (number > array[mid] && array.length > 1) {
            count++;
            arraySecond = array.splice(array[mid], mid);
            console.log("Tried: ", array[mid])
            console.log(arraySecond);
            return binarySearch(arraySecond, number);
        }

        else {
            return 'number doesnt exist';
        }

    }

    console.log(binarySearch(array, 10));