问:
Fallback Factory not working to handle Custom Exception in Feign Client
My requirement is to access the custom exception thrown from first service along with it's body content in the second service

I have tried 2 things so far, FallbackFactory and ErrorDecoder, out of which only Fallback factory worked for me. Error decoder did not have the message of the exception which was thrown from other service. Here is the sample code that I found in another question:

There will be 2 services: inventory-service and product-service

inventory-service

InventoryController.java

```<code>@RestController
@RequestMapping("/inventories")
public class InventoryController {

    private final ProductServiceClient productService;

    public InventoryController(ProductServiceClient productService) {
        super();
        this.productService = productService;
    }

    @GetMapping
    public ResponseEntity<?> companyInfo() {

        return productService.hello();

    }
}
</code>```

ProductServiceClient.java

```<code>@FeignClient(name = "product-service", url = "http://localhost:9100", fallbackFactory = ProductServiceClientFallback.class)
public interface ProductServiceClient {

    @GetMapping("/products")
    ResponseEntity<?> hello();

}

@Component
class ProductServiceClientFallback implements FallbackFactory<ProductServiceClient> {

    @Override
    public ProductServiceClient create(Throwable cause) {

        return new ProductServiceClient() {

            @Override
            public ResponseEntity<?> hello() {
                System.out.println("hello!! fallback reason was " + cause.getMessage());
                return ResponseEntity.ok().build();
            }

        };
    }

}
</code>```

product-service

ProductController.java

```<code>@RestController
@RequestMapping(value = "/products")
public class ProductController {

    @GetMapping
    public String hello() throws Exception {
        if (true) {
            throw new Exception("Service B Exception...");
        }
        return "Hello World";
    }
}
</code>```

ProductControllerAdvice.java

```<code>@RestControllerAdvice
public class ProductControllerAdvice {
    @ExceptionHandler
    public ResponseEntity<?> handleException(Exception exception) {
        return new ResponseEntity<>("Caused due to : " + exception.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
</code>```

So, when /inventories api is triggered in Inventory controller, it triggers a call to product-service via Feign Client and on product-service side, I throw a custom exception with a message, I have to access that message in my inventory-service.

To get that I have implemented fallback factory and it worked in a test-workspace since I got an output like this in console of inventory-service

```<code>hello!! fallback reason was status 500 reading ProductServiceClient#hello(); content:
Caused due to : Service B Exception...
</code>```

But, my problem is when I try the similar approach with the applications that I'm working on, I did not get the message of exception, instead I got an out put like this:

```<code>reached fallback on workflow side, reason: status 400 reading ProvisioningServiceProxy#executeOrderAction(Long,Long,String)
</code>```

Service-A

TestServiceA.java

```<code>@FeignClient( url = "/executeOrder", fallbackFactory = TestServiceAFallback.class )
public interface TestServiceA extends Serializable{
    @PostMapping( value = "order/{requestId}/order/{orderId}/{command}" )
    public ResponseEntity<ProcessInstanceVariable> executeOrderAction(                                                                            @PathVariable( name = "command" ) String command );
}
</code>```

Service-B from where the custom exception is thrown

TestServiceBController.java

```<code>@PostMapping( value = /executeOrder )
public ResponseEntity<ProcessInstanceVariable> executeOrderAction(                                                                      @PathVariable( value = "command" ) String command )
{  //switch code to check the command value and throw exception for one particular command
          throw new ValidationException("validation exception from service B");
}
</code>```

I have an advice also, which handles Validation Exceptions and there is a method like this in that class

TestServiceBControllerAdvice.java

```<code>@ExceptionHandler( ValidationException.class )
public ResponseEntity<Object> handleValidationException( ValidationException ve )
{
    return new ResponseEntity<>( ve.getMessage(), HttpStatus.BAD_REQUEST );
}
</code>```

So, I was expecting to receive the message on TestServiceA side which I sent from TestServiceB, but I received a generic message showing that  BAD REQUEST while reading the API.

I'm not sure if any extra configuration is required on TestServiceA side apart from below configuration:

testServiceA.properties

```<code>feign.hystrix.enabled=true
</code>```

Let me know if anything is missing from my end, I have gone through this documentation and seems to me I have done the implementation the way it should happen to get the message and body of exception thrown from other service.

答:
For anyone who comes to this question looking for some answers, I did end up implementing ErrorDecoder, which helped me in capturing the errors. The details are a little fade to me, how the message was caught.
But I used the below code:</p>
```<code>public class CustomExceptionDecoder implements feign.codec.ErrorDecoder
{
    @Override
    public Exception decode( String methodKey,
                             Response response )
    {
        final ErrorDecoder defaultErrorDecoder = new Default();
        try
        {
            if( response.body() != null )
            {
                byte[] bodyData = Util.toByteArray( response.body().asInputStream() );
                String responseBody = new String( bodyData );
                LOGGER.error( "Error captured in Custom Exception Decoder: ", responseBody );
                return new CustomValidationException( responseBody );
            }
        }
        catch( IOException e )
        {
            LOGGER.error( "Throwing IOException :: {}", e.getCause() );
        }
        return defaultErrorDecoder.decode( methodKey, response );
    }
}
</code>```

Body:
My requirement is to access the custom exception thrown from first service along with it's body content in the second service

I have tried 2 things so far, FallbackFactory and ErrorDecoder, out of which only Fallback factory worked for me. Error decoder did not have the message of the exception which was thrown from other service. Here is the sample code that I found in another question:

There will be 2 services: inventory-service and product-service

inventory-service

InventoryController.java

@RestController
@RequestMapping("/inventories")
public class InventoryController {

    private final ProductServiceClient productService;

    public InventoryController(ProductServiceClient productService) {
        super();
        this.productService = productService;
    }

    @GetMapping
    public ResponseEntity<?> companyInfo() {

        return productService.hello();

    }
}

ProductServiceClient.java

@FeignClient(name = "product-service", url = "http://localhost:9100", fallbackFactory = ProductServiceClientFallback.class)
public interface ProductServiceClient {

    @GetMapping("/products")
    ResponseEntity<?> hello();

}

@Component
class ProductServiceClientFallback implements FallbackFactory<ProductServiceClient> {

    @Override
    public ProductServiceClient create(Throwable cause) {

        return new ProductServiceClient() {

            @Override
            public ResponseEntity<?> hello() {
                System.out.println("hello!! fallback reason was " + cause.getMessage());
                return ResponseEntity.ok().build();
            }

        };
    }

}

product-service

ProductController.java

@RestController
@RequestMapping(value = "/products")
public class ProductController {

    @GetMapping
    public String hello() throws Exception {
        if (true) {
            throw new Exception("Service B Exception...");
        }
        return "Hello World";
    }
}

ProductControllerAdvice.java

@RestControllerAdvice
public class ProductControllerAdvice {
    @ExceptionHandler
    public ResponseEntity<?> handleException(Exception exception) {
        return new ResponseEntity<>("Caused due to : " + exception.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

So, when /inventories api is triggered in Inventory controller, it triggers a call to product-service via Feign Client and on product-service side, I throw a custom exception with a message, I have to access that message in my inventory-service.

To get that I have implemented fallback factory and it worked in a test-workspace since I got an output like this in console of inventory-service

hello!! fallback reason was status 500 reading ProductServiceClient#hello(); content:
Caused due to : Service B Exception...

But, my problem is when I try the similar approach with the applications that I'm working on, I did not get the message of exception, instead I got an out put like this:

reached fallback on workflow side, reason: status 400 reading ProvisioningServiceProxy#executeOrderAction(Long,Long,String)

Service-A

TestServiceA.java

@FeignClient( url = "/executeOrder", fallbackFactory = TestServiceAFallback.class )
public interface TestServiceA extends Serializable{
    @PostMapping( value = "order/{requestId}/order/{orderId}/{command}" )
    public ResponseEntity<ProcessInstanceVariable> executeOrderAction(                                                                            @PathVariable( name = "command" ) String command );
}

Service-B from where the custom exception is thrown

TestServiceBController.java

@PostMapping( value = /executeOrder )
public ResponseEntity<ProcessInstanceVariable> executeOrderAction(                                                                      @PathVariable( value = "command" ) String command )
{  //switch code to check the command value and throw exception for one particular command
          throw new ValidationException("validation exception from service B");
}

I have an advice also, which handles Validation Exceptions and there is a method like this in that class

TestServiceBControllerAdvice.java

@ExceptionHandler( ValidationException.class )
public ResponseEntity<Object> handleValidationException( ValidationException ve )
{
    return new ResponseEntity<>( ve.getMessage(), HttpStatus.BAD_REQUEST );
}

So, I was expecting to receive the message on TestServiceA side which I sent from TestServiceB, but I received a generic message showing that  BAD REQUEST while reading the API.

I'm not sure if any extra configuration is required on TestServiceA side apart from below configuration:

testServiceA.properties

feign.hystrix.enabled=true

Let me know if anything is missing from my end, I have gone through this documentation and seems to me I have done the implementation the way it should happen to get the message and body of exception thrown from other service.

Body:
For anyone who comes to this question looking for some answers, I did end up implementing ErrorDecoder, which helped me in capturing the errors. The details are a little fade to me, how the message was caught.
But I used the below code:

public class CustomExceptionDecoder implements feign.codec.ErrorDecoder
{
    @Override
    public Exception decode( String methodKey,
                             Response response )
    {
        final ErrorDecoder defaultErrorDecoder = new Default();
        try
        {
            if( response.body() != null )
            {
                byte[] bodyData = Util.toByteArray( response.body().asInputStream() );
                String responseBody = new String( bodyData );
                LOGGER.error( "Error captured in Custom Exception Decoder: ", responseBody );
                return new CustomValidationException( responseBody );
            }
        }
        catch( IOException e )
        {
            LOGGER.error( "Throwing IOException :: {}", e.getCause() );
        }
        return defaultErrorDecoder.decode( methodKey, response );
    }
}


来源: stackexchange

问:
excel sumif multiple columns data
My data is:

I need to calculate a sum of the "col1" and "col2" where "name" is "a": 1+2+5+6 = 14.

Now I am using:

```<code>=SUMIF(A:A,"a",B:B)+SUMIF(A:A,"a",C:C)
</code>```

Is there any better way (eg with arrays)?

答:
Try this, for the sum of values where name is a,

Formula in cell B6 --> Applicable To All Excel Users

```<code>=SUMPRODUCT(($A$2:$A$4=$A6)*($B$2:$C$4))
</code>```

Formula in cell C6 --> Applicable To Only O365 & Excel 2021 Users

```<code>=SUM(FILTER($B$2:$C$4,A6=$A$2:$A$4))
</code>```

ContentLicense: CC BY-SA 4.0

Title: excel sumif multiple columns data

Body:
My data is:

I need to calculate a sum of the "col1" and "col2" where "name" is "a": 1+2+5+6 = 14.

Now I am using:

=SUMIF(A:A,"a",B:B)+SUMIF(A:A,"a",C:C)

Is there any better way (eg with arrays)?

Body:
Try this, for the sum of values where name is a,

Formula in cell B6 --> Applicable To All Excel Users

=SUMPRODUCT(($A$2:$A$4=$A6)*($B$2:$C$4))

Formula in cell C6 --> Applicable To Only O365 & Excel 2021 Users

=SUM(FILTER($B$2:$C$4,A6=$A$2:$A$4))


问:
VBA Merging two strings excluding overlap part
Is it possible to merge two strings but when end of s1 is the same as beginning of s2 do not repeat that part of the string? For example:

```<code>s1 = "The quick "          s2 = "brown fox"       -> "The quick brown fox"
s1 = "The quick brown fox" s2 = "quick brown fox" -> "The quick brown fox"
s1 = "The quick brown "    s2 = "quick brown fox" -> "The quick brown fox"
s1 = "The quick brown fox" s2 = ""                -> "The quick brown fox"
s1 = ""                    s2 = "fox"             -> "fox"
</code>```

答:
Solution

Code

```<code>Sub Exec_StringCheck()
Dim s1 As String, s2 As String
    s1 = "The quick ": s2 = "brown fox"
    Debug.Print Return_TxtMerged(s1, s2, " ")
    s1 = "The quick brown fox": s2 = "quick brown fox"
    Debug.Print Return_TxtMerged(s1, s2, " ")
    s1 = "The quick brown ": s2 = "quick brown fox"
    Debug.Print Return_TxtMerged(s1, s2, " ")
    s1 = "The quick brown fox": s2 = ""
    Debug.Print Return_TxtMerged(s1, s2, " ")
    s1 = "": s2 = "fox"
    Debug.Print Return_TxtMerged(s1, s2, " ")
End Sub
Function Return_TxtMerged(TxtOneToMerge As String, TxtTwoToMerge As String, TxtDelimiter As String)
Dim CounterArrTxtTwoToMerge As Long
Dim ArrVarTxtTwoToMerge As Variant: ArrVarTxtTwoToMerge = Split(TxtTwoToMerge, TxtDelimiter)
Dim TxtDummy As String
    For CounterArrTxtTwoToMerge = 0 To UBound(ArrVarTxtTwoToMerge)
    If InStr(TxtOneToMerge, CStr(ArrVarTxtTwoToMerge(CounterArrTxtTwoToMerge))) = 0 Then ' 1. InStr(TxtOneToMerge, CStr(ArrVarTxtTwoToMerge(CounterArrTxtTwoToMerge))) = 0
    TxtDummy = IIf(TxtDummy = "", CStr(ArrVarTxtTwoToMerge(CounterArrTxtTwoToMerge)), TxtDummy & TxtDelimiter & CStr(ArrVarTxtTwoToMerge(CounterArrTxtTwoToMerge)))
    End If ' 1. InStr(TxtOneToMerge, CStr(ArrVarTxtTwoToMerge(CounterArrTxtTwoToMerge))) = 0
    Next CounterArrTxtTwoToMerge
    Return_TxtMerged = TxtOneToMerge & TxtDummy
End Function
</code>```

Body:
Is it possible to merge two strings but when end of s1 is the same as beginning of s2 do not repeat that part of the string? For example:

s1 = "The quick "          s2 = "brown fox"       -> "The quick brown fox"
s1 = "The quick brown fox" s2 = "quick brown fox" -> "The quick brown fox"
s1 = "The quick brown "    s2 = "quick brown fox" -> "The quick brown fox"
s1 = "The quick brown fox" s2 = ""                -> "The quick brown fox"
s1 = ""                    s2 = "fox"             -> "fox"

Body:
Solution

Code

Sub Exec_StringCheck()
Dim s1 As String, s2 As String
    s1 = "The quick ": s2 = "brown fox"
    Debug.Print Return_TxtMerged(s1, s2, " ")
    s1 = "The quick brown fox": s2 = "quick brown fox"
    Debug.Print Return_TxtMerged(s1, s2, " ")
    s1 = "The quick brown ": s2 = "quick brown fox"
    Debug.Print Return_TxtMerged(s1, s2, " ")
    s1 = "The quick brown fox": s2 = ""
    Debug.Print Return_TxtMerged(s1, s2, " ")
    s1 = "": s2 = "fox"
    Debug.Print Return_TxtMerged(s1, s2, " ")
End Sub
Function Return_TxtMerged(TxtOneToMerge As String, TxtTwoToMerge As String, TxtDelimiter As String)
Dim CounterArrTxtTwoToMerge As Long
Dim ArrVarTxtTwoToMerge As Variant: ArrVarTxtTwoToMerge = Split(TxtTwoToMerge, TxtDelimiter)
Dim TxtDummy As String
    For CounterArrTxtTwoToMerge = 0 To UBound(ArrVarTxtTwoToMerge)
    If InStr(TxtOneToMerge, CStr(ArrVarTxtTwoToMerge(CounterArrTxtTwoToMerge))) = 0 Then ' 1. InStr(TxtOneToMerge, CStr(ArrVarTxtTwoToMerge(CounterArrTxtTwoToMerge))) = 0
    TxtDummy = IIf(TxtDummy = "", CStr(ArrVarTxtTwoToMerge(CounterArrTxtTwoToMerge)), TxtDummy & TxtDelimiter & CStr(ArrVarTxtTwoToMerge(CounterArrTxtTwoToMerge)))
    End If ' 1. InStr(TxtOneToMerge, CStr(ArrVarTxtTwoToMerge(CounterArrTxtTwoToMerge))) = 0
    Next CounterArrTxtTwoToMerge
    Return_TxtMerged = TxtOneToMerge & TxtDummy
End Function


问:
Mongoose Unique index not working!
I'm trying to let MongoDB detect a duplicate value based on its index. I think this is possible in MongoDB, but through the Mongoose wrapper things appear to be broken. So for something like this:

```<code>User = new Schema ({
  email: {type: String, index: {unique: true, dropDups: true}}
})
</code>```

I can save 2 users with the same email. Darn.

The same issue has been expressed here: https://github.com/LearnBoost/mongoose/issues/56, but that thread is old and lead to nowhere.

For now, I'm manually making a call to the db to find the user. That call is not expensive since "email" is indexed. But it would still be nice to let it be handled natively.

Does anyone have a solution to this?

答:
in your connect function do not forget to mention
useCreateIndex: true

```<code>mongoose.connect(url, {
  useNewUrlParser: true,
  useCreateIndex: true,
  useFindAndModify: false,
  useUnifiedTopology: true,
})
</code>```

ContentLicense: CC BY-SA 2.5

Title: Mongoose Unique index not working!

Body:
I'm trying to let MongoDB detect a duplicate value based on its index. I think this is possible in MongoDB, but through the Mongoose wrapper things appear to be broken. So for something like this:

User = new Schema ({
  email: {type: String, index: {unique: true, dropDups: true}}
})

I can save 2 users with the same email. Darn.

The same issue has been expressed here: https://github.com/LearnBoost/mongoose/issues/56, but that thread is old and lead to nowhere.

For now, I'm manually making a call to the db to find the user. That call is not expensive since "email" is indexed. But it would still be nice to let it be handled natively.

Does anyone have a solution to this?

Body:
in your connect function do not forget to mention
useCreateIndex: true

mongoose.connect(url, {
  useNewUrlParser: true,
  useCreateIndex: true,
  useFindAndModify: false,
  useUnifiedTopology: true,
})


问:
Filter case with multiple conditions SPSS
I'm trying to combine different conditions within the same case. To be more specific, I want to include various parties into my filter. So far, I have following code:

RANGE(edate,date.mdy(9,14,14),date.mdy(8,30,20)) AND partyabbrev = "AfD"

However, I do not just want to include "AfD", but also e.g. "FN", "FiDeSz-KDNP", "PVV", among others. So, my question would be, how do I combine them into partyabbrev-filter? I already tried using AND partyabbrev = "FN" AND partyabbrev = "PVV" etc. but that did not work unfortunately.

Would really appreciate it if you could help me -- I already tried various YT tutorials but it was never really case specific.

Thanks!!

答:
This should do it:</p>
```<code>RANGE(edate,date.mdy(9,14,14),date.mdy(8,30,20))
   AND any(partyabbrev, "AfD", "FN", "FiDeSz-KDNP", "PVV").
</code>```

Body:
This should do it:

RANGE(edate,date.mdy(9,14,14),date.mdy(8,30,20))
   AND any(partyabbrev, "AfD", "FN", "FiDeSz-KDNP", "PVV").


问:
TypeError: Cannot read properties of undefined (reading 'login')
My Index.js is having a error. I can't understand why.</p>
```<code>const { Client, Collection } = require("discord.js");
const { readdirSync } = require("fs");
const { join } = require("path");
const { TOKEN, PREFIX } = require("./util/Util");
const i18n = require("./util/i18n");

const { Intents, client } = require('discord.js');

client.login(TOKEN);
client.commands = new Collection();
client.prefix = PREFIX;
client.queue = new Map();
const cooldowns = new Collection();
const escapeRegex = (str) => str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");

client.on("ready", () => {
    console.log(`${client.user.username} ready!`);
    client.user.setActivity(`with ${client.guilds.cache.size} servers`);
  });
  client.on("warn", (info) => console.log(info));
  client.on("error", console.error);

  const commandFiles = readdirSync(join(__dirname, "commands")).filter((file) => file.endsWith(".js"));
  for (const file of commandFiles) {
    const command = require(join(__dirname, "commands", `${file}`));
    client.commands.set(command.name, command);
  }

client.on("message", async (message) => {
    if (message.author.bot) return;
    if (!message.guild) return;

    const prefixRegex = new RegExp(`^(<@!?${client.user.id}>|${escapeRegex(PREFIX)})\\s*`);
    if (!prefixRegex.test(message.content)) return;

    const [, matchedPrefix] = message.content.match(prefixRegex);

    const args = message.content.slice(matchedPrefix.length).trim().split(/ +/);
    const commandName = args.shift().toLowerCase();

    const command =
      client.commands.get(commandName) ||
      client.commands.find((cmd) => cmd.aliases && cmd.aliases.includes(commandName));

    if (!command) return;

    if (!cooldowns.has(command.name)) {
      cooldowns.set(command.name, new Collection());
    }

    const now = Date.now();
    const timestamps = cooldowns.get(command.name);
    const cooldownAmount = (command.cooldown || 1) * 1000;

    if (timestamps.has(message.author.id)) {
      const expirationTime = timestamps.get(message.author.id) + cooldownAmount;

      if (now < expirationTime) {
        const timeLeft = (expirationTime - now) / 1000;
        return message.reply(
          i18n.__mf("common.cooldownMessage", { time: timeLeft.toFixed(1), name: command.name })
        );
      }
    }

    timestamps.set(message.author.id, now);
    setTimeout(() => timestamps.delete(message.author.id), cooldownAmount);

    try {
      command.execute(message, args);
    } catch (error) {
      console.error(error);
      message.reply(i18n.__("common.errorCommand")).catch(console.error);
    }
  });

  client.login(TOKEN);

</code>```

答: You are calling client.login(TOKEN); two times, in the beginning and in the final of the code.

Body:
My Index.js is having a error. I can't understand why.

const { Client, Collection } = require("discord.js");
const { readdirSync } = require("fs");
const { join } = require("path");
const { TOKEN, PREFIX } = require("./util/Util");
const i18n = require("./util/i18n");

const { Intents, client } = require('discord.js');

client.login(TOKEN);
client.commands = new Collection();
client.prefix = PREFIX;
client.queue = new Map();
const cooldowns = new Collection();
const escapeRegex = (str) => str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");

client.on("ready", () => {
    console.log(`${client.user.username} ready!`);
    client.user.setActivity(`with ${client.guilds.cache.size} servers`);
  });
  client.on("warn", (info) => console.log(info));
  client.on("error", console.error);

  const commandFiles = readdirSync(join(__dirname, "commands")).filter((file) => file.endsWith(".js"));
  for (const file of commandFiles) {
    const command = require(join(__dirname, "commands", `${file}`));
    client.commands.set(command.name, command);
  }

client.on("message", async (message) => {
    if (message.author.bot) return;
    if (!message.guild) return;

    const prefixRegex = new RegExp(`^(<@!?${client.user.id}>|${escapeRegex(PREFIX)})\\s*`);
    if (!prefixRegex.test(message.content)) return;

    const [, matchedPrefix] = message.content.match(prefixRegex);

    const args = message.content.slice(matchedPrefix.length).trim().split(/ +/);
    const commandName = args.shift().toLowerCase();

    const command =
      client.commands.get(commandName) ||
      client.commands.find((cmd) => cmd.aliases && cmd.aliases.includes(commandName));

    if (!command) return;

    if (!cooldowns.has(command.name)) {
      cooldowns.set(command.name, new Collection());
    }

    const now = Date.now();
    const timestamps = cooldowns.get(command.name);
    const cooldownAmount = (command.cooldown || 1) * 1000;

    if (timestamps.has(message.author.id)) {
      const expirationTime = timestamps.get(message.author.id) + cooldownAmount;

      if (now < expirationTime) {
        const timeLeft = (expirationTime - now) / 1000;
        return message.reply(
          i18n.__mf("common.cooldownMessage", { time: timeLeft.toFixed(1), name: command.name })
        );
      }
    }

    timestamps.set(message.author.id, now);
    setTimeout(() => timestamps.delete(message.author.id), cooldownAmount);

    try {
      command.execute(message, args);
    } catch (error) {
      console.error(error);
      message.reply(i18n.__("common.errorCommand")).catch(console.error);
    }
  });

  client.login(TOKEN);


答:
I don't think you can do this with a simple formula, but you can write a rather simple function. You could use it in your code or as a UDF in an Excel sheet.

The code loops over the length of the second string and compares if the left part of the second string is equal to to right part of the first string.

```<code>Function mergeString(s1 As String, s2 As String)
    Dim i As Long
    For i = Len(s2) To 1 Step -1
        If Left(s2, i) = Right(s1, i) Then
            mergeString = s1 & Mid(s2, i + 1)
            Exit Function
        End If
    Next i
    ' Nothing matches
    mergeString = s1 & s2
End Function
</code>```

Title: VBA Merging two strings excluding overlap part

Body:
I don't think you can do this with a simple formula, but you can write a rather simple function. You could use it in your code or as a UDF in an Excel sheet.

The code loops over the length of the second string and compares if the left part of the second string is equal to to right part of the first string.

Function mergeString(s1 As String, s2 As String)
    Dim i As Long
    For i = Len(s2) To 1 Step -1
        If Left(s2, i) = Right(s1, i) Then
            mergeString = s1 & Mid(s2, i + 1)
            Exit Function
        End If
    Next i
    ' Nothing matches
    mergeString = s1 & s2
End Function


问:
My Code is not working and I am not getting any error (code Shared)
```<code>import numpy as np
import matplotlib.pyplot as plt
import numdifftools as nd
from numpy import linalg as LA
from numpy import array

# Function definition
#function = ((x2-x1)**4)+(8*x1*x2)-x1+x2+3

def funct(x):
    return ((x[1]-x[0])**4)+(8*x[0]*x[1])-x[0]+x[1]+3

x = np.array([1.5, 1.5])  # initial Value
y=funct(x)
grad=nd.Gradient(funct)(x)
norm_grad_square=np.dot(grad,grad)
p=-grad
N=15000
epsilon = 10^(-6)
alpha_bar=5
c=0.1
rho=0.8
alpha=alpha_bar
curve_x = [x]
curve_y = [y]
i=1
while(i<=N) or (norm_grad_square>=epsilon):
    p= -grad
    misc=np.dot(grad,p)
    j=1
    while (funct(x+alpha*p)>(funct(x)+(c*alpha*misc)) or j<=1000):
        alpha_new=rho*c
        alpha=alpha_new
        j+=1
    x=x+(alpha*p)
    y=funct(x)
    grad=nd.Gradient(funct)(x)
    norm_grad_square=np.dot(grad,grad)
    curve_x.append(x)
    curve_y.append(y)
    i+=1

if i==N:
    print("Maximun iterations reached but convergence did not happen")
    print("x= ", x,"function= ",y,"Gradient= ",grad)
else:
    print("x= ",x,"function= ",y,"Gradient= ",grad)
</code>```

My code is not running and no error is shown.
I am running an algorithm to calculate an array until I reach the minimum of the function
The array contains the independent variables.
I am calculating the gradient of the function using inbuilt function.

答:
You got an endless loop or infinite loop, right?

When symptom "infinite loop", then, as the comments suggest, debug the exit-conditions of your (while-)loops.

Debugging with print

For example:

reduce to the required variables and statements

then add print statements inside the loop to watch the exit-conditions

```<code>import numpy as np
import numdifftools as nd

def funct(x):
    return ((x[1]-x[0])**4)+(8*x[0]*x[1])-x[0]+x[1]+3

x = np.array([1.5, 1.5])  # initial Value
# ..
grad=nd.Gradient(funct)(x)
norm_grad_square=np.dot(grad,grad)   # used in exit-condition of loop
# ..
N=15000     # used in exit-condition of loop
epsilon = 10^(-6)     # used in exit-condition of loop
# ...
i=1  # used in exit-condition of loop
while(i<=N) or (norm_grad_square>=epsilon):
    print(i,N,norm_grad_square,epsilon)  # debug print
    print(f"{(i<=N)} or {(norm_grad_square>=epsilon)}")
    # remainder of your loop body: removed for simplicity
    i+=1
</code>```

Prints an endless loop of:

```<code>1 15000 289.9999999999993 -16
True or True
2 15000 289.9999999999993 -16
True or True
..
15000 15000 289.9999999999993 -16
True or True
15001 15000 289.9999999999993 -16
False or True
..
356977 15000 289.9999999999993 -16
False or True
</code>```

The ellipses shows omitted output and I interrupted the look with CTRL + C after a few seconds.

We can observe how i is exceeding N over 15000.

Logical analysis

Didn't we expect to let the loop-counter variable i increase with each iteration and approximate to the constant maximum N.

Let's isolate the loop and its exit-conditions to inspect only i.

```<code>N=15000
# omitted to focus on: i, N
i=1
while(i<=N):
    # loop body
    i+=1

# end of loop
if i==N:
    print("Maximun iterations reached but convergence did not happen")

print(i, N) # debug final i compared to N
</code>```

Does not print expected maximum-message but:

```<code>15001 15000
</code>```

The good news is, that the loop ended with a finite i.
This is not (i<=N) and not i==N  but i > N or at least i >= N.

Now we could conclude: the other side  of the exit-condition (right-hand of the or) seems unmet or contain a bug.

To do

I left further debugging to you.
I would start setting N much lower, start with N = 3 and slightly increase under close monitoring of the other exit-condition, e.g.

```<code>N = 3
i = 1
while(i<=N) or (norm_grad_square>=epsilon):
    print(i,N,norm_grad_square,epsilon)  # debug print
    # gradually insert loop-body
    i += 1
</code>```

You can even add the statements of the loop-body gradually back to watch their evolution with each iteration and impact on the exit-condition.

Body:
import numpy as np
import matplotlib.pyplot as plt
import numdifftools as nd
from numpy import linalg as LA
from numpy import array

# Function definition
#function = ((x2-x1)**4)+(8*x1*x2)-x1+x2+3

def funct(x):
    return ((x[1]-x[0])**4)+(8*x[0]*x[1])-x[0]+x[1]+3

x = np.array([1.5, 1.5])  # initial Value
y=funct(x)
grad=nd.Gradient(funct)(x)
norm_grad_square=np.dot(grad,grad)
p=-grad
N=15000
epsilon = 10^(-6)
alpha_bar=5
c=0.1
rho=0.8
alpha=alpha_bar
curve_x = [x]
curve_y = [y]
i=1
while(i<=N) or (norm_grad_square>=epsilon):
    p= -grad
    misc=np.dot(grad,p)
    j=1
    while (funct(x+alpha*p)>(funct(x)+(c*alpha*misc)) or j<=1000):
        alpha_new=rho*c
        alpha=alpha_new
        j+=1
    x=x+(alpha*p)
    y=funct(x)
    grad=nd.Gradient(funct)(x)
    norm_grad_square=np.dot(grad,grad)
    curve_x.append(x)
    curve_y.append(y)
    i+=1

if i==N:
    print("Maximun iterations reached but convergence did not happen")
    print("x= ", x,"function= ",y,"Gradient= ",grad)
else:
    print("x= ",x,"function= ",y,"Gradient= ",grad)

My code is not running and no error is shown.
I am running an algorithm to calculate an array until I reach the minimum of the function
The array contains the independent variables.
I am calculating the gradient of the function using inbuilt function.

Body:
You got an endless loop or infinite loop, right?

When symptom "infinite loop", then, as the comments suggest, debug the exit-conditions of your (while-)loops.

Debugging with print

For example:

reduce to the required variables and statements

then add print statements inside the loop to watch the exit-conditions

import numpy as np
import numdifftools as nd

def funct(x):
    return ((x[1]-x[0])**4)+(8*x[0]*x[1])-x[0]+x[1]+3

x = np.array([1.5, 1.5])  # initial Value
# ..
grad=nd.Gradient(funct)(x)
norm_grad_square=np.dot(grad,grad)   # used in exit-condition of loop
# ..
N=15000     # used in exit-condition of loop
epsilon = 10^(-6)     # used in exit-condition of loop
# ...
i=1  # used in exit-condition of loop
while(i<=N) or (norm_grad_square>=epsilon):
    print(i,N,norm_grad_square,epsilon)  # debug print
    print(f"{(i<=N)} or {(norm_grad_square>=epsilon)}")
    # remainder of your loop body: removed for simplicity
    i+=1

Prints an endless loop of:

1 15000 289.9999999999993 -16
True or True
2 15000 289.9999999999993 -16
True or True
..
15000 15000 289.9999999999993 -16
True or True
15001 15000 289.9999999999993 -16
False or True
..
356977 15000 289.9999999999993 -16
False or True

The ellipses shows omitted output and I interrupted the look with CTRL + C after a few seconds.

We can observe how i is exceeding N over 15000.

Logical analysis

Didn't we expect to let the loop-counter variable i increase with each iteration and approximate to the constant maximum N.

Let's isolate the loop and its exit-conditions to inspect only i.

N=15000
# omitted to focus on: i, N
i=1
while(i<=N):
    # loop body
    i+=1

# end of loop
if i==N:
    print("Maximun iterations reached but convergence did not happen")

print(i, N) # debug final i compared to N

Does not print expected maximum-message but:

15001 15000

The good news is, that the loop ended with a finite i.
This is not (i<=N) and not i==N  but i > N or at least i >= N.

Now we could conclude: the other side  of the exit-condition (right-hand of the or) seems unmet or contain a bug.

To do

I left further debugging to you.
I would start setting N much lower, start with N = 3 and slightly increase under close monitoring of the other exit-condition, e.g.

N = 3
i = 1
while(i<=N) or (norm_grad_square>=epsilon):
    print(i,N,norm_grad_square,epsilon)  # debug print
    # gradually insert loop-body
    i += 1

You can even add the statements of the loop-body gradually back to watch their evolution with each iteration and impact on the exit-condition.


问:
How to use typescript declarations with puppeteer exposeFunction and webpack
I am using puppeteer and webpack in combination for a project. I compile my files into one bundle, and then using the addScriptTag method on puppeteer, adding that file to the browser. In addition, I am using the exposeFunction functionality so I can send/receive data from the browser to nodejs, more specifically, so I can make some database calls.
My dilemma is that typescript does not recognize these functions, since they are never actually declared in my bundle, instead on the nodejs side, like so:

```<code>  await page.exposeFunction("getPlayerFromDB", async (options) => {
// Some database call
    return DB.players.get(options);
  });
</code>```

And then in my files I reference it like so:

```<code>const player = await getPlayerFromDB(options)

</code>```

Of course that throws a typescript error of:
"Cannot find name 'getPlayerFromDB'"

At first I just @ts-ignore, but as I have more of these exposedFunctions, and because the props for them are kind of complex, it would be nice to benefit from the autocompletion and typechecking of typescript. Therefore I found about the .d.ts files and declaring functions, however I ran into a whole more problems, which I will explain below.

Problem with .d.ts files: Module not found

```<code>export declare function getPlayerFromDB(
  options: Partial<Pick<Player, "name" | "auth" | "ip">>
): Promise<DBUser> | null;
</code>```

and importing like:

```<code>import { getPlayerFromDB } from "../utils/puppeteer";
</code>```

For reference, ../utilts/puppeteer is the file I am making all my exposeFunction function declarations.

I guess webpack cant find the .d.ts file? Even when I go in the compiler options and add the .d.ts extension, or I reference the import ending it with .d, it still cant find the module.

Removed the .d.ts, extension and just sticking with .ts

Now typescript compiles, but my code doesn't work, I receive the error:
"puppeteer_1.getPlayerFromDB) is not a function"
Im guessing that this is because webpack is converting it to a module, but puppeteer expects just the function name.

So my question is how do I get around this? I can always just @ts-ignore every time I use one of the exposedFunctions OR I can just write the function declaration inside the file every time I use it, but that's not really practical.

答:
I finally found a way to work around this. Not saying this is the final solution, but this allows me to:

Have one file where I declare all my functions, repeating declarations

Keep the modular system

Allows for intellisense and typescript annotations

No ts-ignore

Essentially, I created a module with functions that would act as wrappers around my puppeteer functions. I noticed that webpack doesn't change the function names at all when they are nested in another function. Then I came across the problem that I would have the same function names, since I would have a function like so:

```<code>// Puppeteer exposeFunction
declare function getUser(options): DBUser

export default module DB {
export async function getUser(options): DBUser {
return await getUser(options)
}
}
</code>```

To work around this I renamed all my puppeteer functions to include an underscore, that way I could easily recognize all my native puppeteer functions. Like so:

```<code>// Puppeteer exposeFunction
declare function _getUser(options): DBUser

export default module Database {
export async function getUser(options): DBUser {
return await _getUser(options)
}
}
</code>```

Now anytime I create an exposeFunction my process is

Have it start with an underscore

Declare the function in my Database.ts file

In the module exported in my Database.ts file, export a function with the exposeFunction name minus the underscore

Have that function return my exposeFunction

Body:
I am using puppeteer and webpack in combination for a project. I compile my files into one bundle, and then using the addScriptTag method on puppeteer, adding that file to the browser. In addition, I am using the exposeFunction functionality so I can send/receive data from the browser to nodejs, more specifically, so I can make some database calls.
My dilemma is that typescript does not recognize these functions, since they are never actually declared in my bundle, instead on the nodejs side, like so:

  await page.exposeFunction("getPlayerFromDB", async (options) => {
// Some database call
    return DB.players.get(options);
  });

And then in my files I reference it like so:

const player = await getPlayerFromDB(options)

Of course that throws a typescript error of:
"Cannot find name 'getPlayerFromDB'"

At first I just @ts-ignore, but as I have more of these exposedFunctions, and because the props for them are kind of complex, it would be nice to benefit from the autocompletion and typechecking of typescript. Therefore I found about the .d.ts files and declaring functions, however I ran into a whole more problems, which I will explain below.

Problem with .d.ts files: Module not found

export declare function getPlayerFromDB(
  options: Partial<Pick<Player, "name" | "auth" | "ip">>
): Promise<DBUser> | null;

and importing like:

import { getPlayerFromDB } from "../utils/puppeteer";

For reference, ../utilts/puppeteer is the file I am making all my exposeFunction function declarations.

I guess webpack cant find the .d.ts file? Even when I go in the compiler options and add the .d.ts extension, or I reference the import ending it with .d, it still cant find the module.

Removed the .d.ts, extension and just sticking with .ts

Now typescript compiles, but my code doesn't work, I receive the error:
"puppeteer_1.getPlayerFromDB) is not a function"
Im guessing that this is because webpack is converting it to a module, but puppeteer expects just the function name.

So my question is how do I get around this? I can always just @ts-ignore every time I use one of the exposedFunctions OR I can just write the function declaration inside the file every time I use it, but that's not really practical.

Body:
I finally found a way to work around this. Not saying this is the final solution, but this allows me to:

Have one file where I declare all my functions, repeating declarations

Keep the modular system

Allows for intellisense and typescript annotations

No ts-ignore

Essentially, I created a module with functions that would act as wrappers around my puppeteer functions. I noticed that webpack doesn't change the function names at all when they are nested in another function. Then I came across the problem that I would have the same function names, since I would have a function like so:

// Puppeteer exposeFunction
declare function getUser(options): DBUser

export default module DB {
export async function getUser(options): DBUser {
return await getUser(options)
}
}

To work around this I renamed all my puppeteer functions to include an underscore, that way I could easily recognize all my native puppeteer functions. Like so:

// Puppeteer exposeFunction
declare function _getUser(options): DBUser

export default module Database {
export async function getUser(options): DBUser {
return await _getUser(options)
}
}

Now anytime I create an exposeFunction my process is

Have it start with an underscore

Declare the function in my Database.ts file

In the module exported in my Database.ts file, export a function with the exposeFunction name minus the underscore

Have that function return my exposeFunction


问:
How to optimize a GROUP BY query
I am given a task to optimize the following query (not written by me)

SELECT
  "u"."email" as email,
  r.url as "domain",
  "u"."id" as "requesterId",
  s.total * 100 / count("r"."id") as "rate",
  count(("r"."url", "u"."email", "u"."id", s."total")) OVER () as total
FROM
  (
    SELECT
      url,
      id,
      "requesterId",
      created_at
    FROM
      (
        SELECT
          url,
          id,
          "requesterId",
          created_at,
          row_number() over (partition by main_request_uuid) as row_number
        FROM
          "requests" "request"
        GROUP BY
          main_request_uuid,
          retry_number,
          url,
          id,
          "requesterId",
          created_at
        ORDER BY
          main_request_uuid ASC,
          retry_number DESC
      ) "request_"
    WHERE
      request_.row_number = 1
  ) "r"
  INNER JOIN (
    SELECT
      "requesterId",
      url,
      count(created_at) AS "total"
    FROM
      (
        SELECT
          url,
          status,
          created_at,
          "requesterId"
        FROM
          (
            SELECT
              url,
              status,
              created_at,
              "requesterId",
              row_number() over (partition by main_request_uuid) as row_number
            FROM
              "requests" "request"
            GROUP BY
              main_request_uuid,
              retry_number,
              url,
              status,
              created_at,
              "requesterId"
            ORDER BY
              main_request_uuid ASC,
              retry_number DESC
          ) "request_"
        WHERE
          request_.row_number = 1
      ) "s"
    WHERE
      status IN ('success')
      AND s."created_at" :: date >= '2022-01-07' :: date
      AND s."created_at" :: date <= '2022-02-07' :: date
    GROUP BY
      s.url,
      s."requesterId"
  ) "s" ON s."requesterId" = r."requesterId"
  AND s.url = r.url
  INNER JOIN "users" "u" ON "u"."id" = r."requesterId"
WHERE
  r."created_at" :: date >= '2022-01-07' :: date
  AND r."created_at" :: date <= '2022-02-07' :: date
GROUP BY
  r.url,
  "u"."email",
  "u"."id",
  s.total
LIMIT
  10
```
<p>So there is the <code>requests</code> table, which stores some API requests and there is a mechanism to retry a request if it fails, which is repeated 5 times, while keeping separate rows for each retry. If after 5 times it still fails, it's not continued anymore. This is the reason for the <code>partition by</code> subquery, which selects only the main requests.</p>
<p>What the query should return is the total number of requests and success rate, grouped by the <code>url</code> and <code>requesterId</code>. The query I was given is not only wrong, but also takes huge amounts of time to execute, so I came up with the optimized version below</p>
<pre class="lang-sql prettyprint-override"><code>WITH a AS (SELECT url,
                  id,
                  status,
                  "requesterId",
                  created_at
           FROM (
                    SELECT url,
                           id,
                           status,
                           "requesterId",
                           created_at,
                           row_number() over (partition by main_request_uuid) as row_number
                    FROM "requests" "request"
                    WHERE
                    created_at:: date >= '2022-01-07' :: date
                    AND created_at :: date <= '2022-02-07' :: date
                    GROUP BY main_request_uuid,
                             retry_number,
                             url,
                             id,
                             status,
                             "requesterId",
                             created_at
                    ORDER BY
                             main_request_uuid ASC,
                             retry_number DESC
                ) "request_"
           WHERE request_.row_number = 1),
     b AS (SELECT count(*) total, a2.url as url, a2."requesterId" FROM a a2 GROUP BY a2.url, a2."requesterId"),
     c AS (SELECT count(*) success, a3.url as url, a3."requesterId"
           FROM a a3
           WHERE status IN ('success')
           GROUP BY a3.url, a3."requesterId")
SELECT success * 100 / total as rate, b.url, b."requesterId", total, email
FROM b
         JOIN c ON b.url = c.url AND b."requesterId" = c."requesterId" JOIN users u ON b."requesterId" = u.id
LIMIT 10;
</code>```

What the new version basically does is select all the main requests, and count the successful ones and the total count. The new version still takes a lot of time to execute (around 60s on a table with 4 million requests).

Is there a way to optimize this further?

You can see the table structure below. The table has no relevant indexes, but adding one on (url, requesterId) had no effect

column_name
data_type

id
bigint

requesterId
bigint

proxyId
bigint

url
character varying

status
USER-DEFINED

time_spent
integer

created_at
timestamp with time zone

request_information
jsonb

retry_number
smallint

main_request_uuid
character varying

And here is the execution plan on a backup table with 100k rows. It's taking 1.1s for 100k rows, but it would be more desired to at least cut it down to 200ms for this case

```<code>Limit  (cost=15196.40..15204.56 rows=1 width=77) (actual time=749.664..1095.476 rows=10 loops=1)
  CTE a
    ->  Subquery Scan on request_  (cost=15107.66..15195.96 rows=3 width=159) (actual time=226.805..591.188 rows=49474 loops=1)
          Filter: (request_.row_number = 1)
          Rows Removed by Filter: 70962
          ->  WindowAgg  (cost=15107.66..15188.44 rows=602 width=206) (actual time=226.802..571.185 rows=120436 loops=1)
                ->  Group  (cost=15107.66..15179.41 rows=602 width=198) (actual time=226.797..435.340 rows=120436 loops=1)
"                      Group Key: request.main_request_uuid, request.retry_number, request.url, request.id, request.status, request.""requesterId"", request.created_at"
                      ->  Gather Merge  (cost=15107.66..15170.62 rows=502 width=198) (actual time=226.795..386.198 rows=120436 loops=1)
                            Workers Planned: 2
                            Workers Launched: 2
                            ->  Group  (cost=14107.64..14112.66 rows=251 width=198) (actual time=212.749..269.504 rows=40145 loops=3)
"                                  Group Key: request.main_request_uuid, request.retry_number, request.url, request.id, request.status, request.""requesterId"", request.created_at"
                                  ->  Sort  (cost=14107.64..14108.27 rows=251 width=198) (actual time=212.744..250.031 rows=40145 loops=3)
"                                        Sort Key: request.main_request_uuid, request.retry_number DESC, request.url, request.id, request.status, request.""requesterId"", request.created_at"
                                        Sort Method: external merge  Disk: 7952kB
                                        Worker 0:  Sort Method: external merge  Disk: 8568kB
                                        Worker 1:  Sort Method: external merge  Disk: 9072kB
                                        ->  Parallel Seq Scan on requests request  (cost=0.00..14097.63 rows=251 width=198) (actual time=0.024..44.013 rows=40145 loops=3)
                                              Filter: (((created_at)::date >= '2022-01-07'::date) AND ((created_at)::date <= '2022-02-07'::date))
  ->  Nested Loop  (cost=0.43..8.59 rows=1 width=77) (actual time=749.662..1095.364 rows=10 loops=1)
"        Join Filter: (a2.""requesterId"" = u.id)"
        ->  Nested Loop  (cost=0.16..0.28 rows=1 width=64) (actual time=749.630..1095.163 rows=10 loops=1)
"              Join Filter: (((a2.url)::text = (a3.url)::text) AND (a2.""requesterId"" = a3.""requesterId""))"
              Rows Removed by Join Filter: 69
              ->  HashAggregate  (cost=0.08..0.09 rows=1 width=48) (actual time=703.128..703.139 rows=10 loops=1)
"                    Group Key: a3.url, a3.""requesterId"""
                    Batches: 5  Memory Usage: 4297kB  Disk Usage: 7040kB
                    ->  CTE Scan on a a3  (cost=0.00..0.07 rows=1 width=40) (actual time=226.808..648.251 rows=41278 loops=1)
                          Filter: (status = 'success'::requests_status_enum)
                          Rows Removed by Filter: 8196
              ->  HashAggregate  (cost=0.08..0.11 rows=3 width=48) (actual time=38.103..38.105 rows=8 loops=10)
"                    Group Key: a2.url, a2.""requesterId"""
                    Batches: 41  Memory Usage: 4297kB  Disk Usage: 7328kB
                    ->  CTE Scan on a a2  (cost=0.00..0.06 rows=3 width=40) (actual time=0.005..7.419 rows=49474 loops=10)
"        ->  Index Scan using ""PK_a3ffb1c0c8416b9fc6f907b7433"" on users u  (cost=0.28..8.29 rows=1 width=29) (actual time=0.015..0.015 rows=1 loops=10)"
"              Index Cond: (id = a3.""requesterId"")"
Planning Time: 1.494 ms
Execution Time: 1102.488 ms
</code>```

答:
These lines of your plan point to a possible optimization.

```<code>->  Parallel Seq Scan on requests request  (cost=0.00..14097.63 rows=251 width=198) (actual time=0.024..44.013 rows=40145 loops=3)
    Filter: (((created_at)::date >= '2022-01-07'::date) AND ((created_at)::date <= '2022-02-07'::date))
</code>```

Sequential scans, parallel or not, are somewhat costly.

So, try changing these WHERE conditions to make them sargable and useful for a range scan.

    created_at:: date >= '2022-01-07' :: date
AND created_at :: date <= '2022-02-07' :: date
```
<p>Change these to</p>
<pre class="lang-sql prettyprint-override"><code>    created_at >= '2022-01-07' :: date
AND created_at < '2022-01-07' :: date + INTERVAL '1' DAY
</code>```

And, put a BTREE index on the created_at column.

CREATE INDEX ON requests (created_at);
```

Your query is complex, so I'm not totally sure this will work. But try it. The index should pull out only the rows for the dates you need.

And, your LIMIT clause without an accompanying ORDER BY clause gives postgreSQL permission to give you back whatever ten rows it wants from the result set. Don't use LIMIT without ORDER BY. Don't do it at all unless you need it.

Title: How to optimize a GROUP BY query

Body:
I am given a task to optimize the following query (not written by me)

SELECT
  "u"."email" as email,
  r.url as "domain",
  "u"."id" as "requesterId",
  s.total * 100 / count("r"."id") as "rate",
  count(("r"."url", "u"."email", "u"."id", s."total")) OVER () as total
FROM
  (
    SELECT
      url,
      id,
      "requesterId",
      created_at
    FROM
      (
        SELECT
          url,
          id,
          "requesterId",
          created_at,
          row_number() over (partition by main_request_uuid) as row_number
        FROM
          "requests" "request"
        GROUP BY
          main_request_uuid,
          retry_number,
          url,
          id,
          "requesterId",
          created_at
        ORDER BY
          main_request_uuid ASC,
          retry_number DESC
      ) "request_"
    WHERE
      request_.row_number = 1
  ) "r"
  INNER JOIN (
    SELECT
      "requesterId",
      url,
      count(created_at) AS "total"
    FROM
      (
        SELECT
          url,
          status,
          created_at,
          "requesterId"
        FROM
          (
            SELECT
              url,
              status,
              created_at,
              "requesterId",
              row_number() over (partition by main_request_uuid) as row_number
            FROM
              "requests" "request"
            GROUP BY
              main_request_uuid,
              retry_number,
              url,
              status,
              created_at,
              "requesterId"
            ORDER BY
              main_request_uuid ASC,
              retry_number DESC
          ) "request_"
        WHERE
          request_.row_number = 1
      ) "s"
    WHERE
      status IN ('success')
      AND s."created_at" :: date >= '2022-01-07' :: date
      AND s."created_at" :: date <= '2022-02-07' :: date
    GROUP BY
      s.url,
      s."requesterId"
  ) "s" ON s."requesterId" = r."requesterId"
  AND s.url = r.url
  INNER JOIN "users" "u" ON "u"."id" = r."requesterId"
WHERE
  r."created_at" :: date >= '2022-01-07' :: date
  AND r."created_at" :: date <= '2022-02-07' :: date
GROUP BY
  r.url,
  "u"."email",
  "u"."id",
  s.total
LIMIT
  10

So there is the requests table, which stores some API requests and there is a mechanism to retry a request if it fails, which is repeated 5 times, while keeping separate rows for each retry. If after 5 times it still fails, it's not continued anymore. This is the reason for the partition by subquery, which selects only the main requests.

What the query should return is the total number of requests and success rate, grouped by the url and requesterId. The query I was given is not only wrong, but also takes huge amounts of time to execute, so I came up with the optimized version below

WITH a AS (SELECT url,
                  id,
                  status,
                  "requesterId",
                  created_at
           FROM (
                    SELECT url,
                           id,
                           status,
                           "requesterId",
                           created_at,
                           row_number() over (partition by main_request_uuid) as row_number
                    FROM "requests" "request"
                    WHERE
                    created_at:: date >= '2022-01-07' :: date
                    AND created_at :: date <= '2022-02-07' :: date
                    GROUP BY main_request_uuid,
                             retry_number,
                             url,
                             id,
                             status,
                             "requesterId",
                             created_at
                    ORDER BY
                             main_request_uuid ASC,
                             retry_number DESC
                ) "request_"
           WHERE request_.row_number = 1),
     b AS (SELECT count(*) total, a2.url as url, a2."requesterId" FROM a a2 GROUP BY a2.url, a2."requesterId"),
     c AS (SELECT count(*) success, a3.url as url, a3."requesterId"
           FROM a a3
           WHERE status IN ('success')
           GROUP BY a3.url, a3."requesterId")
SELECT success * 100 / total as rate, b.url, b."requesterId", total, email
FROM b
         JOIN c ON b.url = c.url AND b."requesterId" = c."requesterId" JOIN users u ON b."requesterId" = u.id
LIMIT 10;

What the new version basically does is select all the main requests, and count the successful ones and the total count. The new version still takes a lot of time to execute (around 60s on a table with 4 million requests).

Is there a way to optimize this further?

You can see the table structure below. The table has no relevant indexes, but adding one on (url, requesterId) had no effect

column_name
data_type

id
bigint

requesterId
bigint

proxyId
bigint

url
character varying

status
USER-DEFINED

time_spent
integer

created_at
timestamp with time zone

request_information
jsonb

retry_number
smallint

main_request_uuid
character varying

And here is the execution plan on a backup table with 100k rows. It's taking 1.1s for 100k rows, but it would be more desired to at least cut it down to 200ms for this case

Limit  (cost=15196.40..15204.56 rows=1 width=77) (actual time=749.664..1095.476 rows=10 loops=1)
  CTE a
    ->  Subquery Scan on request_  (cost=15107.66..15195.96 rows=3 width=159) (actual time=226.805..591.188 rows=49474 loops=1)
          Filter: (request_.row_number = 1)
          Rows Removed by Filter: 70962
          ->  WindowAgg  (cost=15107.66..15188.44 rows=602 width=206) (actual time=226.802..571.185 rows=120436 loops=1)
                ->  Group  (cost=15107.66..15179.41 rows=602 width=198) (actual time=226.797..435.340 rows=120436 loops=1)
"                      Group Key: request.main_request_uuid, request.retry_number, request.url, request.id, request.status, request.""requesterId"", request.created_at"
                      ->  Gather Merge  (cost=15107.66..15170.62 rows=502 width=198) (actual time=226.795..386.198 rows=120436 loops=1)
                            Workers Planned: 2
                            Workers Launched: 2
                            ->  Group  (cost=14107.64..14112.66 rows=251 width=198) (actual time=212.749..269.504 rows=40145 loops=3)
"                                  Group Key: request.main_request_uuid, request.retry_number, request.url, request.id, request.status, request.""requesterId"", request.created_at"
                                  ->  Sort  (cost=14107.64..14108.27 rows=251 width=198) (actual time=212.744..250.031 rows=40145 loops=3)
"                                        Sort Key: request.main_request_uuid, request.retry_number DESC, request.url, request.id, request.status, request.""requesterId"", request.created_at"
                                        Sort Method: external merge  Disk: 7952kB
                                        Worker 0:  Sort Method: external merge  Disk: 8568kB
                                        Worker 1:  Sort Method: external merge  Disk: 9072kB
                                        ->  Parallel Seq Scan on requests request  (cost=0.00..14097.63 rows=251 width=198) (actual time=0.024..44.013 rows=40145 loops=3)
                                              Filter: (((created_at)::date >= '2022-01-07'::date) AND ((created_at)::date <= '2022-02-07'::date))
  ->  Nested Loop  (cost=0.43..8.59 rows=1 width=77) (actual time=749.662..1095.364 rows=10 loops=1)
"        Join Filter: (a2.""requesterId"" = u.id)"
        ->  Nested Loop  (cost=0.16..0.28 rows=1 width=64) (actual time=749.630..1095.163 rows=10 loops=1)
"              Join Filter: (((a2.url)::text = (a3.url)::text) AND (a2.""requesterId"" = a3.""requesterId""))"
              Rows Removed by Join Filter: 69
              ->  HashAggregate  (cost=0.08..0.09 rows=1 width=48) (actual time=703.128..703.139 rows=10 loops=1)
"                    Group Key: a3.url, a3.""requesterId"""
                    Batches: 5  Memory Usage: 4297kB  Disk Usage: 7040kB
                    ->  CTE Scan on a a3  (cost=0.00..0.07 rows=1 width=40) (actual time=226.808..648.251 rows=41278 loops=1)
                          Filter: (status = 'success'::requests_status_enum)
                          Rows Removed by Filter: 8196
              ->  HashAggregate  (cost=0.08..0.11 rows=3 width=48) (actual time=38.103..38.105 rows=8 loops=10)
"                    Group Key: a2.url, a2.""requesterId"""
                    Batches: 41  Memory Usage: 4297kB  Disk Usage: 7328kB
                    ->  CTE Scan on a a2  (cost=0.00..0.06 rows=3 width=40) (actual time=0.005..7.419 rows=49474 loops=10)
"        ->  Index Scan using ""PK_a3ffb1c0c8416b9fc6f907b7433"" on users u  (cost=0.28..8.29 rows=1 width=29) (actual time=0.015..0.015 rows=1 loops=10)"
"              Index Cond: (id = a3.""requesterId"")"
Planning Time: 1.494 ms
Execution Time: 1102.488 ms

Body:
These lines of your plan point to a possible optimization.

->  Parallel Seq Scan on requests request  (cost=0.00..14097.63 rows=251 width=198) (actual time=0.024..44.013 rows=40145 loops=3)
    Filter: (((created_at)::date >= '2022-01-07'::date) AND ((created_at)::date <= '2022-02-07'::date))

Sequential scans, parallel or not, are somewhat costly.

So, try changing these WHERE conditions to make them sargable and useful for a range scan.

    created_at:: date >= '2022-01-07' :: date
AND created_at :: date <= '2022-02-07' :: date

Change these to

    created_at >= '2022-01-07' :: date
AND created_at < '2022-01-07' :: date + INTERVAL '1' DAY

And, put a BTREE index on the created_at column.

CREATE INDEX ON requests (created_at);

Your query is complex, so I'm not totally sure this will work. But try it. The index should pull out only the rows for the dates you need.

And, your LIMIT clause without an accompanying ORDER BY clause gives postgreSQL permission to give you back whatever ten rows it wants from the result set. Don't use LIMIT without ORDER BY. Don't do it at all unless you need it.


问:
Map<String, List<String, Object>> add new list entry when key exists
Let's say I got Map<ID, Object> when looping over the entries via .entrySet().stream()

I want to map it to Map<String, List<Map<String, Object>>

When using toMap() I change the ID of my initial map to a String (with a database call), but different ID's can return the same string so there can be duplicates. Is it possible if my key already exists in the toMap of my new map that I'm collecting, that my ObjectOne is added in a new list entry of my new map in the format of Map<String, List<Map<String, Object>> .

I tried stuff with Collectors.groupingBy() and Collectors.mapping() but not getting it to work, curious if there is a way to do this

What I got now is the following solution, but I would like to collect it to map without having to define it first:

```<code>  Map<String, List<Map<String, Object>>> giantMap = new HashMap<>();

  initalMap.forEach((id, object) -> {
      Code code = repository.getCodeById(id);
      giantMap.computeIfAbsent(code, ignore -> new ArrayList<>())
                        .add(object);
   });
</code>```

答:
So, let's assume there is a map of some ids to objects of type ObjectOne: Map<ID, ObjectOne>.

The key IDs are converted to some Code type by a database call, and the ObjectOne values of the first map are just collected into another map using Collectors.groupingBy and Collectors.mapping as intended initially:

Map<ID, ObjectOne> initialMap = ...;

Map<Code, List<ObjectOne>> mapByCode = initialMap
        .entrySet()
        .stream() // Stream<Map.Entry<ID, ObjectOne>>
        .collect(Collectors.groupingBy(
            e -> repository.getCodeById(e.getKey()),
            Collectors.mapping(Map.Entry::getValue, Collectors.toList())
        ));
```
<p>Also, a <code>keySet</code> of the initial map may be iterated upon:</p>
<pre class="lang-java prettyprint-override"><code>// or using keySet()
Map<Code, List<ObjectOne>> mapByCode2 = initialMap
        .keySet()
        .stream() // Stream<ID>
        .collect(Collectors.groupingBy(
            repository::getCodeById,
            Collectors.mapping(initialMap::get, Collectors.toList())
        ));
</code>```

Body:
Let's say I got Map<ID, Object> when looping over the entries via .entrySet().stream()

I want to map it to Map<String, List<Map<String, Object>>

When using toMap() I change the ID of my initial map to a String (with a database call), but different ID's can return the same string so there can be duplicates. Is it possible if my key already exists in the toMap of my new map that I'm collecting, that my ObjectOne is added in a new list entry of my new map in the format of Map<String, List<Map<String, Object>> .

I tried stuff with Collectors.groupingBy() and Collectors.mapping() but not getting it to work, curious if there is a way to do this

What I got now is the following solution, but I would like to collect it to map without having to define it first:

  Map<String, List<Map<String, Object>>> giantMap = new HashMap<>();

  initalMap.forEach((id, object) -> {
      Code code = repository.getCodeById(id);
      giantMap.computeIfAbsent(code, ignore -> new ArrayList<>())
                        .add(object);
   });

Body:
So, let's assume there is a map of some ids to objects of type ObjectOne: Map<ID, ObjectOne>.

The key IDs are converted to some Code type by a database call, and the ObjectOne values of the first map are just collected into another map using Collectors.groupingBy and Collectors.mapping as intended initially:

Map<ID, ObjectOne> initialMap = ...;

Map<Code, List<ObjectOne>> mapByCode = initialMap
        .entrySet()
        .stream() // Stream<Map.Entry<ID, ObjectOne>>
        .collect(Collectors.groupingBy(
            e -> repository.getCodeById(e.getKey()),
            Collectors.mapping(Map.Entry::getValue, Collectors.toList())
        ));

Also, a keySet of the initial map may be iterated upon:

// or using keySet()
Map<Code, List<ObjectOne>> mapByCode2 = initialMap
        .keySet()
        .stream() // Stream<ID>
        .collect(Collectors.groupingBy(
            repository::getCodeById,
            Collectors.mapping(initialMap::get, Collectors.toList())
        ));


问:
Bug fixed with four nops in an if(0), world no longer makes sense
I was writing a function to figure out if a given system of linear inequalities has a solution, when all of a sudden it started giving the wrong answers after a seemingly innocuous change.

I undid some changes, re-did them, and then proceeded to fiddle for the next two hours, until I had reduced it to absurdity.

The following, inserted anywhere into the function body, but nowhere else in the program, fixes it:

```<code>if(0) {
    __asm__("nop\n");
    __asm__("nop\n");
    __asm__("nop\n");
    __asm__("nop\n");
}
</code>```

It's for a school assignment, so I probably shouldn't post the function on the web, but this is so ridiculous that I don't think any context is going to help you. And all the function does is a bunch of math and looping. It doesn't even touch memory that isn't allocated on the stack.

Please help me make sense of the world! I'm loathe to chalk it up to the GCC, since the first rule of debugging is not to blame the compiler. But heck, I'm about to. I'm running Mac OS 10.5 on a G5 tower, and the compiler in question identifies itself as 'powerpc-apple-darwin9-gcc-4.0.1' but I'm thinking it could be an impostor...

UPDATE: Curiouser and curiouser... I diffed the .s files with nops and without. Not only are there too many differences to check, but with no nops the .s file is 196,620 bytes, and with it's 156,719 bytes. (!)

UPDATE 2: Wow, should have posted the code! I came back to the code today, with fresh eyes, and immediately saw the error. See my sheepish self-answer below.

答:
Looks like you will need to put in some hard work and elbow grease

Your problem sounds similar to something I have debugged in the past where my app was running regular ... when out of nowhere it jumped to a different part of the app and the callstack got completely messed up ( however this was embedded programming )!

It sounds like you are spending your time "thinking" about "what should be happening" ... when you should be "looking" at "what is actually happening". A lot of the times the hardest bugs are things that you would never think "should happen".

I would approach the problem like so:

Break out your favorite debugger

Start stepping through your code and watch the call stack and local variables and look for suspicious activity

Make the system fail

Focus in to where the system is failing

Focus on iterating your code changes:

making code changes that will "make the system fail"

running/debugging and watching

If it runs fine you are looking/trying the wrong thing and you need to try something else. If you make it fail then you have made progress towards finding the bug.

If you don't know where or how the system fails you will not be able to solve the problem.

This will be a good opportunity to build your debugging skills. For more help on building your debugging skills read check out the book "9 rules for debugging".

Here is a poster from the book:

(source: google.com)

Concrete suggestions:

If you think it is the compiler, then run a different platform/OS/compiler.

Once you have ruled out the platform/OS/compiler, then try restructuring the code. Look for the "clever" code parts and see if they are actually doing what the code meant to do... maybe the clever solution wasn't actually clever and is doing something else.

OwnerDisplayName: rodarmor

Body:
I was writing a function to figure out if a given system of linear inequalities has a solution, when all of a sudden it started giving the wrong answers after a seemingly innocuous change.

I undid some changes, re-did them, and then proceeded to fiddle for the next two hours, until I had reduced it to absurdity.

The following, inserted anywhere into the function body, but nowhere else in the program, fixes it:

if(0) {
    __asm__("nop\n");
    __asm__("nop\n");
    __asm__("nop\n");
    __asm__("nop\n");
}

It's for a school assignment, so I probably shouldn't post the function on the web, but this is so ridiculous that I don't think any context is going to help you. And all the function does is a bunch of math and looping. It doesn't even touch memory that isn't allocated on the stack.

Please help me make sense of the world! I'm loathe to chalk it up to the GCC, since the first rule of debugging is not to blame the compiler. But heck, I'm about to. I'm running Mac OS 10.5 on a G5 tower, and the compiler in question identifies itself as 'powerpc-apple-darwin9-gcc-4.0.1' but I'm thinking it could be an impostor...

UPDATE: Curiouser and curiouser... I diffed the .s files with nops and without. Not only are there too many differences to check, but with no nops the .s file is 196,620 bytes, and with it's 156,719 bytes. (!)

UPDATE 2: Wow, should have posted the code! I came back to the code today, with fresh eyes, and immediately saw the error. See my sheepish self-answer below.

LastEditorDisplayName: rodarmor

OwnerDisplayName: Trevor Boyd Smith


问:
subscriber.next() is not firing after subscriber.error statement
Based on the input data I want to decide whether it is valid data or not and send the observable to the to end.

I have tried to create a observable and sequential subscribe.next() is working correctly but any error is coming then after that no statement is working.

```<code>const observable = new Observable((subscriber) => {
  subscriber.next(1);
  subscriber.next(2);
  subscriber.error('failed this after second');
  subscriber.next(3);
  subscriber.next(4);
  subscriber.complete();
});

observable.subscribe({
  next(x) {
    console.log('got value ' + x);
  },
  error(err) {
    console.error('something wrong occurred: ' + err);
  },
  complete() {
    console.log('done');
  },
});
</code>```

Current output:

got value 1

got value 2

something wrong occurred: failed this after second

Expected output

got value 1

got value 2

something wrong occurred: failed this after second

got value 3

got value 4

done

Here is the stackblitz link
https://stackblitz.com/edit/zlksm5?devtoolsheight=50&file=index.ts

答:
The Observable Contract

OnError:

Indicates that the Observable has terminated with a specified error condition and that it will be emitting no further items

Emphasis mine.

If you want something that keeps going after it completes, you don't want an observable.

Toward a solution

Just emit your error as a value. You could (for example) wrap your emissions in RxJS Notification objects so that you can materialize or dematerialize observables and keep a consistent API of emissions.

For example:

const observable = new Observable(subscriber => {
  subscriber.next({ kind: "N", value: 1 });
  subscriber.next({ kind: "N", value: 2 });
  subscriber.next({ kind: "E", error: new Error("failed this after second") });
  subscriber.next({ kind: "N", value: 3 });
  subscriber.next({ kind: "N", value: 4 });
  subscriber.next({ kind: "C" });
  subscriber.complete();
});

/**** Alternative written more succinctly ****/

const observable = of(
  { kind: "N", value: 1 },
  { kind: "N", value: 2 },
  { kind: "E", error: new Error("failed this after second") },
  { kind: "N", value: 3 },
  { kind: "N", value: 4 },
  { kind: "C" }
);

```
<pre class="lang-ts prettyprint-override"><code>observable.subscribe((notification) => {
  switch (notification.kind) {
    case "N":
      console.log("got value ", notification.value);
      break;
    case "E":
      console.error("something wrong occurred: ", notification.error.message);
      break;
    case "C":
      console.log("done");
  }
});
</code>```

Body:
Based on the input data I want to decide whether it is valid data or not and send the observable to the to end.

I have tried to create a observable and sequential subscribe.next() is working correctly but any error is coming then after that no statement is working.

const observable = new Observable((subscriber) => {
  subscriber.next(1);
  subscriber.next(2);
  subscriber.error('failed this after second');
  subscriber.next(3);
  subscriber.next(4);
  subscriber.complete();
});

observable.subscribe({
  next(x) {
    console.log('got value ' + x);
  },
  error(err) {
    console.error('something wrong occurred: ' + err);
  },
  complete() {
    console.log('done');
  },
});

Current output:

got value 1

got value 2

something wrong occurred: failed this after second

Expected output

got value 1

got value 2

something wrong occurred: failed this after second

got value 3

got value 4

done

Here is the stackblitz link
https://stackblitz.com/edit/zlksm5?devtoolsheight=50&file=index.ts

Body:
The Observable Contract

OnError:

Indicates that the Observable has terminated with a specified error condition and that it will be emitting no further items

Emphasis mine.

If you want something that keeps going after it completes, you don't want an observable.

Toward a solution

Just emit your error as a value. You could (for example) wrap your emissions in RxJS Notification objects so that you can materialize or dematerialize observables and keep a consistent API of emissions.

For example:

const observable = new Observable(subscriber => {
  subscriber.next({ kind: "N", value: 1 });
  subscriber.next({ kind: "N", value: 2 });
  subscriber.next({ kind: "E", error: new Error("failed this after second") });
  subscriber.next({ kind: "N", value: 3 });
  subscriber.next({ kind: "N", value: 4 });
  subscriber.next({ kind: "C" });
  subscriber.complete();
});

/**** Alternative written more succinctly ****/

const observable = of(
  { kind: "N", value: 1 },
  { kind: "N", value: 2 },
  { kind: "E", error: new Error("failed this after second") },
  { kind: "N", value: 3 },
  { kind: "N", value: 4 },
  { kind: "C" }
);

observable.subscribe((notification) => {
  switch (notification.kind) {
    case "N":
      console.log("got value ", notification.value);
      break;
    case "E":
      console.error("something wrong occurred: ", notification.error.message);
      break;
    case "C":
      console.log("done");
  }
});


问:
How do I take a set of arrays (strings) and create a multidimensional slice of those arrays in Golang?
I am trying to implement a function, that when passed an array of strings, it creates a slice of arrays, and adds to it every array that is passed. It would return the final slice of all arrays that was passed.

Just as a test, I initialized 4 arrays and tried to create a function that would do just this. However, it fails quite miserably. This is what I have so far. Not sure how to go about this.

```<code>func main() {
    array1 := []string{"x", "o", "x", "_", "_"}
    array2 := []string{"0", "o", "x", "_", "_"}
    array3 := []string{"o", "o", "o", "_", "_"}
    array4 := []string{"o", "o", "o", "o", "o"}

    FinalSlice(array1)
    FinalSlice(array2)
    FinalSlice(array3)
    fmt.Println(FinalSlice(array4))

}

func FinalSlice(array []string) [][]string {
    var slice [][]string
    for i, _ := range slice {
        slice[i] = array
    }
    return slice

}
</code>```

Right now this is the output:

```<code>[]
</code>```

答:
That is because you loop through an empty slice, which has no elements.

So your loop

for i, _ := range slice {}
```
<p>will actually run 0 iteration (that's why you end up with an empty array).</p>
<p>I don't understand the exact result you want to achieve, but if you want to concat arrays into a multi-dimensional one, you can use the below code:</p>
<pre class="lang-golang prettyprint-override"><code>package main

import "fmt"

func AppendSlice(source [][]string, value []string) [][]string {
    return append(source, value)
}

func main() {
    array1 := []string{"x", "o", "x", "_", "_"}
    array2 := []string{"0", "o", "x", "_", "_"}
    array3 := []string{"o", "o", "o", "_", "_"}
    array4 := []string{"o", "o", "o", "o", "o"}

    var finalArray [][]string

    finalArray = AppendSlice(finalArray, array1)
    finalArray = AppendSlice(finalArray, array2)
    finalArray = AppendSlice(finalArray, array3)
    finalArray = AppendSlice(finalArray, array4)

    // [[x o x _ _] [0 o x _ _] [o o o _ _] [o o o o o]]
    fmt.Println(finalArray)
}

</code>```

This may be improved in many ways, feel free to play around with this solution: https://go.dev/play/p/vXvqlRZuOUI

Body:
I am trying to implement a function, that when passed an array of strings, it creates a slice of arrays, and adds to it every array that is passed. It would return the final slice of all arrays that was passed.

Just as a test, I initialized 4 arrays and tried to create a function that would do just this. However, it fails quite miserably. This is what I have so far. Not sure how to go about this.

func main() {
    array1 := []string{"x", "o", "x", "_", "_"}
    array2 := []string{"0", "o", "x", "_", "_"}
    array3 := []string{"o", "o", "o", "_", "_"}
    array4 := []string{"o", "o", "o", "o", "o"}

    FinalSlice(array1)
    FinalSlice(array2)
    FinalSlice(array3)
    fmt.Println(FinalSlice(array4))

}

func FinalSlice(array []string) [][]string {
    var slice [][]string
    for i, _ := range slice {
        slice[i] = array
    }
    return slice

}

Right now this is the output:

[]

Body:
That is because you loop through an empty slice, which has no elements.

So your loop

for i, _ := range slice {}

will actually run 0 iteration (that's why you end up with an empty array).

I don't understand the exact result you want to achieve, but if you want to concat arrays into a multi-dimensional one, you can use the below code:

package main

import "fmt"

func AppendSlice(source [][]string, value []string) [][]string {
    return append(source, value)
}

func main() {
    array1 := []string{"x", "o", "x", "_", "_"}
    array2 := []string{"0", "o", "x", "_", "_"}
    array3 := []string{"o", "o", "o", "_", "_"}
    array4 := []string{"o", "o", "o", "o", "o"}

    var finalArray [][]string

    finalArray = AppendSlice(finalArray, array1)
    finalArray = AppendSlice(finalArray, array2)
    finalArray = AppendSlice(finalArray, array3)
    finalArray = AppendSlice(finalArray, array4)

    // [[x o x _ _] [0 o x _ _] [o o o _ _] [o o o o o]]
    fmt.Println(finalArray)
}

This may be improved in many ways, feel free to play around with this solution: https://go.dev/play/p/vXvqlRZuOUI


问:
Add new class to existing class when the page is loaded
Hello everyone I try to add a new class 'visible' to existing class 'menu' when the page is ready and all elements are loaded.

This is the code that I use.

.point {
  position: absolute;
  top: 50%;
  left: 50%;
}

.menu ul {
  background: rgb(255, 255, 255);
  height: 0px;
  opacity: 0;
  position: absolute;
  transition: .5s ease-in-out;
  transition-delay: 0.2s;
}

.menu li:hover ul {
  width: 300px;
  height: 200px;
  top: 30px;
  left: 30px;
  opacity: 1;
}

.menu li {
  list-style-type: none;
}

.menu ul li a {
  list-style-type: none;
  text-decoration: none;
  text-align: left;
  color: rgb(66, 66, 66);
}

.menu ul li h1 {
  font-family: Arial, Helvetica, sans-serif;
  list-style-type: none;
  text-decoration: none;
  text-align: left;
}

.point div {
  position: absolute;
  width: 60px;
  height: 60px;
  background: #999;
  z-index: 1;
  cursor: grab;
}

.point:hover div {
  background: #000;
  position: absolute;
  width: 60px;
  height: 60px;
  z-index: 2;
  cursor: grab;
}

nav.menu {
  visibility: hidden;
}

nav.menu.visible {
  visibility: visible;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <canvas class="webgl"></canvas>
  <div class="loading-bar"></div>
  <nav class="menu">
    <li>
      <div class="point point-0">
        <div class="point"></div>
        <ul>
          <li>
            <h1 href="#">num</h1>
          </li>
          <li>2</li>
          <li>3</li>
          <li>4</li>
          <li>5</li>
        </ul>
      </div>
    </li>
  </nav>
</body></code>```

https://jsfiddle.net/pect25L3/

I tryed

```<code>window.onload = function() {
document.getElementById('menu').className = 'visible';
};
</code>```

But nothing happens. Where can be my mistake?

Thank you.

答:
first you are trying to use an id selector for a class selector, this is a working code</p>
```<code>const visibleMenu = () =>{

const menu = document.querySelector('.menu');
menu.classList.add('visible')
};
window.onload = visibleMenu()
</code>```

Body:
Hello everyone I try to add a new class 'visible' to existing class 'menu' when the page is ready and all elements are loaded.

This is the code that I use.

.point {
  position: absolute;
  top: 50%;
  left: 50%;
}

.menu ul {
  background: rgb(255, 255, 255);
  height: 0px;
  opacity: 0;
  position: absolute;
  transition: .5s ease-in-out;
  transition-delay: 0.2s;
}

.menu li:hover ul {
  width: 300px;
  height: 200px;
  top: 30px;
  left: 30px;
  opacity: 1;
}

.menu li {
  list-style-type: none;
}

.menu ul li a {
  list-style-type: none;
  text-decoration: none;
  text-align: left;
  color: rgb(66, 66, 66);
}

.menu ul li h1 {
  font-family: Arial, Helvetica, sans-serif;
  list-style-type: none;
  text-decoration: none;
  text-align: left;
}

.point div {
  position: absolute;
  width: 60px;
  height: 60px;
  background: #999;
  z-index: 1;
  cursor: grab;
}

.point:hover div {
  background: #000;
  position: absolute;
  width: 60px;
  height: 60px;
  z-index: 2;
  cursor: grab;
}

nav.menu {
  visibility: hidden;
}

nav.menu.visible {
  visibility: visible;
}

  <canvas class="webgl"></canvas>

num

2

3

4

5

https://jsfiddle.net/pect25L3/

I tryed

window.onload = function() {
document.getElementById('menu').className = 'visible';
};

But nothing happens. Where can be my mistake?

Thank you.

Body:
first you are trying to use an id selector for a class selector, this is a working code

const visibleMenu = () =>{

const menu = document.querySelector('.menu');
menu.classList.add('visible')
};
window.onload = visibleMenu()


问:
firebase package not working using angular 12
hi i tried to use firebase with my angular application, i installed firebase package by command npm install firebase @angular/fire --save , when i import AngularFireModule it gives me error: Unable to evaluate this expression statically.

```<code>import { AngularFireModule } from '@angular/fire';
import { AngularFireDatabaseModule } from '@angular/fire/database';

 imports: [
    BrowserModule,
    AngularFireModule.initializeApp(environment.firebase),
    AngularFireDatabaseModule

  ],
</code>```

environement.ts

```<code>export const environment = {
  production: false,
  firebase: {
    apiKey: "AIzaSyC5Zpt1sAaY8obi2-guN8Y0yTrztJJBKe0",
    authDomain: "appangular88.firebaseapp.com",
    projectId: "appangular88",
    storageBucket: "appangular88.appspot.com",
    messagingSenderId: "725152387599",
    appId: "1:725152387599:web:2f1d40faac1f1281b8c97a",
    measurementId: "G-7BXN0J34QE"
  }
};
</code>```

答: Use ng instead of npm. "ng add @angular/fire"</p>

Body:
hi i tried to use firebase with my angular application, i installed firebase package by command npm install firebase @angular/fire --save , when i import AngularFireModule it gives me error: Unable to evaluate this expression statically.

import { AngularFireModule } from '@angular/fire';
import { AngularFireDatabaseModule } from '@angular/fire/database';

 imports: [
    BrowserModule,
    AngularFireModule.initializeApp(environment.firebase),
    AngularFireDatabaseModule

  ],

environement.ts

export const environment = {
  production: false,
  firebase: {
    apiKey: "AIzaSyC5Zpt1sAaY8obi2-guN8Y0yTrztJJBKe0",
    authDomain: "appangular88.firebaseapp.com",
    projectId: "appangular88",
    storageBucket: "appangular88.appspot.com",
    messagingSenderId: "725152387599",
    appId: "1:725152387599:web:2f1d40faac1f1281b8c97a",
    measurementId: "G-7BXN0J34QE"
  }
};


问:
Regex for detecting keys in the yaml file
I am writing a regex to detect the exposed passwords/secrets/keys in a yaml file.  Below is the example of the yaml file. The data key is common to all my yaml files. subkeys under the data key will vary for each file.

Scenario 1:

```<code>apiVersion: v1
data:
    PASSWORD: mypass123
    USER: {$USER_NAME}
metadata:
    Timestamp: 2021-03-31T14:29:09Z
</code>```

Scenario 2:

```<code>apiVersion: v1
data:
    DATABASE: {$DATABASE_NAME}
    USER: {$USER_NAME}
    API_KEY: mykey456=
metadata:
    Timestamp: 2021-03-31T14:29:09Z
</code>```

As you can see above sensitive information is exposed for the keys PASSWORD & API_KEY. I need a regex to match the data key & exposed values of sensitive information.

```<code>import re
import sys
from ruamel.yaml import YAML

yaml_str = """\
apiVersion: v1
data:
    PASSWORD: mypass123
    USER: {$USER_NAME}
metadata:
    Timestamp: 2021-03-31T14:29:09Z
"""

regex = r'data:\s*-\s*\b[a-z0-9_ .\-,]:([a-z0-9=_\-]{1,4096})'
</code>```

I have tried the above regex but it is not working. Any help is appreciated.

答:
What about just adding a list of keys that you think may be sensitive -- I don't think they would vary too widely? As an example:

(PASSWORD|DATABASE|other-sensitive-keys-here):\s*([^\n]+)

However, if you just want to grab the contents within the data: section, then I think @Thefourthbird has a good approach. Or even better, parse the yaml file itself.

Body:
I am writing a regex to detect the exposed passwords/secrets/keys in a yaml file.  Below is the example of the yaml file. The data key is common to all my yaml files. subkeys under the data key will vary for each file.

Scenario 1:

apiVersion: v1
data:
    PASSWORD: mypass123
    USER: {$USER_NAME}
metadata:
    Timestamp: 2021-03-31T14:29:09Z

Scenario 2:

apiVersion: v1
data:
    DATABASE: {$DATABASE_NAME}
    USER: {$USER_NAME}
    API_KEY: mykey456=
metadata:
    Timestamp: 2021-03-31T14:29:09Z

As you can see above sensitive information is exposed for the keys PASSWORD & API_KEY. I need a regex to match the data key & exposed values of sensitive information.

import re
import sys
from ruamel.yaml import YAML

yaml_str = """\
apiVersion: v1
data:
    PASSWORD: mypass123
    USER: {$USER_NAME}
metadata:
    Timestamp: 2021-03-31T14:29:09Z
"""

regex = r'data:\s*-\s*\b[a-z0-9_ .\-,]:([a-z0-9=_\-]{1,4096})'

I have tried the above regex but it is not working. Any help is appreciated.


问:
Multipart form data is not working in react native
I'm trying to make an api call with multipart as content-type. when I added the params to FormData, it is creating multiple array lists.

```<code> var formData = new FormData();

formData.append('name', "Mahendra")
formData.append('number', "12131233123")
formData.append('image', {uri : pathToImage, name : "image", "type":"image/jpeg"})
console.log(formData)
</code>```

When I log the request, I'm getting multiple arrays inside. Below is the request

```<code>{"_parts" : [["name","Mahendra"],["number","12131233123"],["image",{"uri":"/Users/XXXXC/Library/Developer/CoreSimulator/Devices/XXXXX/data/Containers/Data/Application/XXX/tmp/react-native-image-crop-picker/asdas3D4.jpg","name":"image","type":"image/jpeg"}]]}
</code>```

Can someone help me on this ?

Thanks in advance!

答: I'm not really sure to understand at which point you log them, but following the MDN docs, you shouldn't access the value directly but through the api methods. To send the data you have to use either XMLHttpRequest.send() or the fetch api

Body:
I'm trying to make an api call with multipart as content-type. when I added the params to FormData, it is creating multiple array lists.

 var formData = new FormData();

formData.append('name', "Mahendra")
formData.append('number', "12131233123")
formData.append('image', {uri : pathToImage, name : "image", "type":"image/jpeg"})
console.log(formData)

When I log the request, I'm getting multiple arrays inside. Below is the request

{"_parts" : [["name","Mahendra"],["number","12131233123"],["image",{"uri":"/Users/XXXXC/Library/Developer/CoreSimulator/Devices/XXXXX/data/Containers/Data/Application/XXX/tmp/react-native-image-crop-picker/asdas3D4.jpg","name":"image","type":"image/jpeg"}]]}

Can someone help me on this ?

Thanks in advance!