问:
Is there a way to generate a set of maps at compile time in c++?
I have an underlying function from another library as below -

```<code>template <typename K, typename V>
std::map<K,V> whatever(const int rc, const std::string& str) {
    return std::map<K,V>;
}
</code>```

Now, my code wants to use this function whatever().

I've 3 sets of values each of my template arguments can have, namely int, double, and string.
These values come as input parameters to my application. I want to generate a map of all possible combinations on the fly i.e. at compile time. There are 9 possible scenarios that can be generated -

```<code>map<int, int>
map<int, double>
map<int, string>

map<double, int>
map<double, double>
map<double, string>

map<string, int>
map<string, double>
map<string, string>
</code>```

The problem is essentially how to generate these 9 instances on the fly at compile-time since the templatized function accepts types, and input to my application is in form of enums.

```<code>0->int
1->string
2->double
</code>```

The current most optimal solution I was able to come up with is to create 2 std::variants -

```<code>std::variant<9 possible maps> v1;

std::map<enum, std::variant>>  enumToVariant;
The std::variant in enumToVariant is of type std::variant<int, double, string>.
</code>```

Following this, it is actually a one-liner using std::visit{overload} - which would visit both the respective variants and overload it with auto.

The problem with that method is it generates a single return type only. So it can only generate v1.
Source - https://www.cppstories.com/2018/09/visit-variants/

Is there a better way to do it? Or the approach I have is most optimal?

答:
Not clear to me what do you want, exactly.

Anyway... I propose you a simple program that show you how to generate a std::tuple (the type only) containing all 9 std::map types.

```<code>#include <map>
#include <tuple>
#include <string>

template <typename T0, typename ... Ts>
auto gam_helper ()
{ return std::make_tuple(std::map<T0, Ts>{}...); }

template <typename ... Ts>
auto getAllMaps ()
{ return std::tuple_cat(gam_helper<Ts, Ts...>()...); }

int main ()
{
  using TX = decltype(getAllMaps<int, double, std::string>());
  using T0 = std::tuple_element<0u, TX>::type;
  using T1 = std::tuple_element<1u, TX>::type;
  using T2 = std::tuple_element<2u, TX>::type;
  using T3 = std::tuple_element<3u, TX>::type;
  using T4 = std::tuple_element<4u, TX>::type;
  using T5 = std::tuple_element<5u, TX>::type;
  using T6 = std::tuple_element<6u, TX>::type;
  using T7 = std::tuple_element<7u, TX>::type;
  using T8 = std::tuple_element<8u, TX>::type;

  static_assert( std::is_same_v<T0, std::map<int, int>>);
  static_assert( std::is_same_v<T1, std::map<int, double>>);
  static_assert( std::is_same_v<T2, std::map<int, std::string>>);
  static_assert( std::is_same_v<T3, std::map<double, int>>);
  static_assert( std::is_same_v<T4, std::map<double, double>>);
  static_assert( std::is_same_v<T5, std::map<double, std::string>>);
  static_assert( std::is_same_v<T6, std::map<std::string, int>>);
  static_assert( std::is_same_v<T7, std::map<std::string, double>>);
  static_assert( std::is_same_v<T8, std::map<std::string, std::string>>);
}
</code>```

Body:
I have an underlying function from another library as below -

template <typename K, typename V>
std::map<K,V> whatever(const int rc, const std::string& str) {
    return std::map<K,V>;
}

Now, my code wants to use this function whatever().

I've 3 sets of values each of my template arguments can have, namely int, double, and string.
These values come as input parameters to my application. I want to generate a map of all possible combinations on the fly i.e. at compile time. There are 9 possible scenarios that can be generated -

map<int, int>
map<int, double>
map<int, string>

map<double, int>
map<double, double>
map<double, string>

map<string, int>
map<string, double>
map<string, string>

The problem is essentially how to generate these 9 instances on the fly at compile-time since the templatized function accepts types, and input to my application is in form of enums.

0->int
1->string
2->double

The current most optimal solution I was able to come up with is to create 2 std::variants -

std::variant<9 possible maps> v1;

std::map<enum, std::variant>>  enumToVariant;
The std::variant in enumToVariant is of type std::variant<int, double, string>.

Following this, it is actually a one-liner using std::visit{overload} - which would visit both the respective variants and overload it with auto.

The problem with that method is it generates a single return type only. So it can only generate v1.
Source - https://www.cppstories.com/2018/09/visit-variants/

Is there a better way to do it? Or the approach I have is most optimal?

Body:
Not clear to me what do you want, exactly.

Anyway... I propose you a simple program that show you how to generate a std::tuple (the type only) containing all 9 std::map types.

#include <map>
#include <tuple>
#include <string>

template <typename T0, typename ... Ts>
auto gam_helper ()
{ return std::make_tuple(std::map<T0, Ts>{}...); }

template <typename ... Ts>
auto getAllMaps ()
{ return std::tuple_cat(gam_helper<Ts, Ts...>()...); }

int main ()
{
  using TX = decltype(getAllMaps<int, double, std::string>());
  using T0 = std::tuple_element<0u, TX>::type;
  using T1 = std::tuple_element<1u, TX>::type;
  using T2 = std::tuple_element<2u, TX>::type;
  using T3 = std::tuple_element<3u, TX>::type;
  using T4 = std::tuple_element<4u, TX>::type;
  using T5 = std::tuple_element<5u, TX>::type;
  using T6 = std::tuple_element<6u, TX>::type;
  using T7 = std::tuple_element<7u, TX>::type;
  using T8 = std::tuple_element<8u, TX>::type;

  static_assert( std::is_same_v<T0, std::map<int, int>>);
  static_assert( std::is_same_v<T1, std::map<int, double>>);
  static_assert( std::is_same_v<T2, std::map<int, std::string>>);
  static_assert( std::is_same_v<T3, std::map<double, int>>);
  static_assert( std::is_same_v<T4, std::map<double, double>>);
  static_assert( std::is_same_v<T5, std::map<double, std::string>>);
  static_assert( std::is_same_v<T6, std::map<std::string, int>>);
  static_assert( std::is_same_v<T7, std::map<std::string, double>>);
  static_assert( std::is_same_v<T8, std::map<std::string, std::string>>);
}


来源: stackexchange

问:
How to get NULL or Zero values in SQL Server results set
Trying to get the output of all mentioned accounts(total of 9) even though there are no existing records for the GB.periode = 11

Tried using ISNULL(SUM(GB.bdr_val), 0) but still I'm only getting output for GB.reknr = 5210 OR GB.reknr = 5211 OR GB.reknr = 5250 OR GB.reknr = 5340.

```<code>SELECT
    SUM(GB.bdr_val) AS Total_Material_M,
    GR.oms25_0 AS Desc2, GB.reknr AS Account
FROM
    [100].[dbo].[gbkmut] GB
INNER JOIN
    [100].[dbo].[grtbk] GR ON GB.reknr = GR.reknr
WHERE
    GB.bkjrcode = 2021
    AND GB.periode = 11
    AND (GB.reknr = 5000 OR GB.reknr = 5050 OR GB.reknr = 5150 OR
         GB.reknr = 5200 OR GB.reknr = 5210 OR GB.reknr = 5211 OR
         GB.reknr = 5250 OR GB.reknr = 5340 OR GB.reknr = 5341)
GROUP BY
    GR.oms25_0,GB.reknr
ORDER BY
    GB.reknr ASC
</code>```

I have a sample DB layout below,

```<code>CREATE TABLE gbkmut
(
    id INT,
    reknr INT,
    bdr_val INT,
    bkjrcode INT,
    periode INT
);

INSERT INTO gbkmut VALUES (1, 5210, 3511, 2021, 11);
INSERT INTO gbkmut VALUES (2, 5211, -40, 2021, 11);
INSERT INTO gbkmut VALUES (3, 5250, 33832, 2021, 11);
INSERT INTO gbkmut VALUES (3, 5340, -16, 2021, 11);

CREATE TABLE grtbk
(
    id INT,
    reknr INT,
    oms25_0 varchar(60)
);

INSERT INTO grtbk VALUES (1, 5210, 'Description 1');
INSERT INTO grtbk VALUES (2, 5211, 'Description 2');
INSERT INTO grtbk VALUES (3, 5250, 'Description 3');
INSERT INTO grtbk VALUES (4, 5340, 'Description 4');
INSERT INTO grtbk VALUES (5, 5000, 'Description 5');
INSERT INTO grtbk VALUES (6, 5050, 'Description 6');
INSERT INTO grtbk VALUES (7, 5150, 'Description 7');
INSERT INTO grtbk VALUES (8, 5200, 'Description 8');
INSERT INTO grtbk VALUES (9, 5341, 'Description 9');
</code>```

I still need the query output to show all the Total_Material_M, Desc2 and Account columns to show up even the values are 0 for specific bkjrcode and periode value combinations and SUMS, not sure what I'm doing wrong here.

答:
You need to switch around the order of the joins and change it to a LEFT JOIN. You also need to move the conditions for GB into the ON clause.

SELECT
    SUM(GB.bdr_val) AS Total_Material_M,
    GR.oms25_0 AS Desc2, GB.reknr AS Account
FROM
    dbo.grtbk GR
LEFT JOIN
    dbo.gbkmut GB ON GB.reknr = GR.reknr
    AND GB.bkjrcode = 2021
    AND GB.periode = 11
    AND (GB.reknr = 5000 OR GB.reknr = 5050 OR GB.reknr = 5150 OR
         GB.reknr = 5200 OR GB.reknr = 5210 OR GB.reknr = 5211 OR
         GB.reknr = 5250 OR GB.reknr = 5340 OR GB.reknr = 5341)
GROUP BY
    GR.oms25_0,
    GB.reknr
ORDER BY
    GB.reknr ASC;
```

db<>fiddle

ContentLicense: CC BY-SA 4.0

Body:
Trying to get the output of all mentioned accounts(total of 9) even though there are no existing records for the GB.periode = 11

Tried using ISNULL(SUM(GB.bdr_val), 0) but still I'm only getting output for GB.reknr = 5210 OR GB.reknr = 5211 OR GB.reknr = 5250 OR GB.reknr = 5340.

SELECT
    SUM(GB.bdr_val) AS Total_Material_M,
    GR.oms25_0 AS Desc2, GB.reknr AS Account
FROM
    [100].[dbo].[gbkmut] GB
INNER JOIN
    [100].[dbo].[grtbk] GR ON GB.reknr = GR.reknr
WHERE
    GB.bkjrcode = 2021
    AND GB.periode = 11
    AND (GB.reknr = 5000 OR GB.reknr = 5050 OR GB.reknr = 5150 OR
         GB.reknr = 5200 OR GB.reknr = 5210 OR GB.reknr = 5211 OR
         GB.reknr = 5250 OR GB.reknr = 5340 OR GB.reknr = 5341)
GROUP BY
    GR.oms25_0,GB.reknr
ORDER BY
    GB.reknr ASC

I have a sample DB layout below,

CREATE TABLE gbkmut
(
    id INT,
    reknr INT,
    bdr_val INT,
    bkjrcode INT,
    periode INT
);

INSERT INTO gbkmut VALUES (1, 5210, 3511, 2021, 11);
INSERT INTO gbkmut VALUES (2, 5211, -40, 2021, 11);
INSERT INTO gbkmut VALUES (3, 5250, 33832, 2021, 11);
INSERT INTO gbkmut VALUES (3, 5340, -16, 2021, 11);

CREATE TABLE grtbk
(
    id INT,
    reknr INT,
    oms25_0 varchar(60)
);

INSERT INTO grtbk VALUES (1, 5210, 'Description 1');
INSERT INTO grtbk VALUES (2, 5211, 'Description 2');
INSERT INTO grtbk VALUES (3, 5250, 'Description 3');
INSERT INTO grtbk VALUES (4, 5340, 'Description 4');
INSERT INTO grtbk VALUES (5, 5000, 'Description 5');
INSERT INTO grtbk VALUES (6, 5050, 'Description 6');
INSERT INTO grtbk VALUES (7, 5150, 'Description 7');
INSERT INTO grtbk VALUES (8, 5200, 'Description 8');
INSERT INTO grtbk VALUES (9, 5341, 'Description 9');

I still need the query output to show all the Total_Material_M, Desc2 and Account columns to show up even the values are 0 for specific bkjrcode and periode value combinations and SUMS, not sure what I'm doing wrong here.

Body:
You need to switch around the order of the joins and change it to a LEFT JOIN. You also need to move the conditions for GB into the ON clause.

SELECT
    SUM(GB.bdr_val) AS Total_Material_M,
    GR.oms25_0 AS Desc2, GB.reknr AS Account
FROM
    dbo.grtbk GR
LEFT JOIN
    dbo.gbkmut GB ON GB.reknr = GR.reknr
    AND GB.bkjrcode = 2021
    AND GB.periode = 11
    AND (GB.reknr = 5000 OR GB.reknr = 5050 OR GB.reknr = 5150 OR
         GB.reknr = 5200 OR GB.reknr = 5210 OR GB.reknr = 5211 OR
         GB.reknr = 5250 OR GB.reknr = 5340 OR GB.reknr = 5341)
GROUP BY
    GR.oms25_0,
    GB.reknr
ORDER BY
    GB.reknr ASC;

db<>fiddle


问:
Append data in one dimenssional list to a multidimensional list
I have a list as follows:

```<code>List<String> responseList = new ArrayList<>();
 responseList.add("test1")
 responseList.add("test2")
 responseList.add("test3")
 responseList.add("test4")
</code>```

I need to add the data in the above list to the below list in which 0 th row should have values test1 and test2 . 1 st row should have test3 and test4

```<code>List<List<String>> ActualEmployeeList  = new ArrayList<>();
</code>```

答:
Using a simple for loop:

```<code>List<List<String>> ActualEmployeeList = new ArrayList();
for (int i = 0; i < responseList.size()-1; i += 2) {
    ActualEmployeeList.add(responseList.subList(i, i+2));
}
</code>```

Possible streams solution. Not sure this is optimal:

```<code>List<List<String>> ActualEmployeeList = IntStream.range(0, responseList.size()-1)
            .filter(x -> x % 2 == 0)
            .mapToObj(i -> responseList.subList(i, i+2))
            .collect(Collectors.toList());
</code>```

Body:
I have a list as follows:

List<String> responseList = new ArrayList<>();
 responseList.add("test1")
 responseList.add("test2")
 responseList.add("test3")
 responseList.add("test4")

I need to add the data in the above list to the below list in which 0 th row should have values test1 and test2 . 1 st row should have test3 and test4

List<List<String>> ActualEmployeeList  = new ArrayList<>();

Body:
Using a simple for loop:

List<List<String>> ActualEmployeeList = new ArrayList();
for (int i = 0; i < responseList.size()-1; i += 2) {
    ActualEmployeeList.add(responseList.subList(i, i+2));
}

Possible streams solution. Not sure this is optimal:

List<List<String>> ActualEmployeeList = IntStream.range(0, responseList.size()-1)
            .filter(x -> x % 2 == 0)
            .mapToObj(i -> responseList.subList(i, i+2))
            .collect(Collectors.toList());


问:
Using pika, how to connect to rabbitmq running in docker, started with docker-compose with external network?
I have the following docker-compose file:

```<code>version: '2.3'
networks:
    default: { external: true, name: $NETWORK_NAME } # NETWORK_NAME in .env file is `uv_atp_network`.

services:
    car_parts_segmentor:
#        container_name: uv-car-parts-segmentation
        image: "uv-car-parts-segmentation:latest"
        ports:
            - "8080:8080"
        volumes:
            - ../../../../uv-car-parts-segmentation/configs:/uveye/configs
            - /isilon/:/isilon/
#            - local_data_folder:local_data_folder
        command: "--run_service rabbit"
        runtime: nvidia
        depends_on:
          rabbitmq_local:
            condition: service_started
        links:
          - rabbitmq_local
        restart: always

    rabbitmq_local:
        image: 'rabbitmq:3.6-management-alpine'
        container_name: "rabbitmq"
        ports:
          - ${RABBIT_PORT:?unspecified_rabbit_port}:5672
          - ${RABBIT_MANAGEMENT_PORT:?unspecified_rabbit_management_port}:15672

</code>```

When this runs, docker ps shows

```<code>21400efd6493   uv-car-parts-segmentation:latest                             "python /uveye/app/m…"   5 seconds ago   Up 1 second    0.0.0.0:8080->8080/tcp, :::8080->8080/tcp                                                                                joint_car_parts_segmentor_1
bf4ab8581f1f   rabbitmq:3.6-management-alpine                               "docker-entrypoint.s…"   5 seconds ago   Up 4 seconds   4369/tcp, 5671/tcp, 0.0.0.0:5672->5672/tcp, :::5672->5672/tcp, 15671/tcp, 25672/tcp, 0.0.0.0:15672->15672/tcp, :::15672->15672/tcp   rabbitmq
</code>```

I want to create a connection to that rabbitmq. The user:pass is guest:guest.

I was unable to do it, with the very uninformative AMQPConnectionError in all cases:

Below code runs in another, unrelated container.

```<code>connection = pika.BlockingConnection(pika.URLParameters("amqp://guest:guest@rabbitmq/"))
connection = pika.BlockingConnection(pika.URLParameters("amqp://guest:guest@localhost/"))
</code>```

Also tried with

```<code>$ docker inspect -f '{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}' rabbitmq
172.27.0.2
</code>```

and

```<code>connection = pika.BlockingConnection(pika.URLParameters("amqp://guest:guest@172.27.0.2/")) #
</code>```

Also tried with

```<code>
    credentials = pika.credentials.PlainCredentials(
        username="guest",
        password="guest"
    )
    parameters = pika.ConnectionParameters(
        host=ip_address, # tried all above options
        port=5672,
        credentials=credentials,
        heartbeat=10,
    )

</code>```

Note that the container car_parts_segmentor is able to see the container rabbitmq. Both are started by docker-compose.

My assumption is this has to do with the uv_atp_network both containers live in, and I am trying to access a docker inside that network, from outside the network.

Is this really the problem?

If so, how can this be achieved?

For the future - how to get more informative errors from pika?

答:
As I suspected, the problem was the name rabbitmq existed only in the network uv_atp_network.

The code attempting to connect to that network runs inside a container of its own, which was not present in the network.

Solution connect the current container to the network:

```<code>import socket

client = docker.from_env()
network_name = "uv_atp_network"
atp_container = client.containers.get(socket.gethostname())
client.networks.get(network_name).connect(container=atp_container.id)
</code>```

After this, the above code in the question does work, because rabbitmq can be resolved.

```<code>connection = pika.BlockingConnection(pika.URLParameters("amqp://guest:guest@rabbitmq/"))
</code>```

Body:
I have the following docker-compose file:

version: '2.3'
networks:
    default: { external: true, name: $NETWORK_NAME } # NETWORK_NAME in .env file is `uv_atp_network`.

services:
    car_parts_segmentor:
#        container_name: uv-car-parts-segmentation
        image: "uv-car-parts-segmentation:latest"
        ports:
            - "8080:8080"
        volumes:
            - ../../../../uv-car-parts-segmentation/configs:/uveye/configs
            - /isilon/:/isilon/
#            - local_data_folder:local_data_folder
        command: "--run_service rabbit"
        runtime: nvidia
        depends_on:
          rabbitmq_local:
            condition: service_started
        links:
          - rabbitmq_local
        restart: always

    rabbitmq_local:
        image: 'rabbitmq:3.6-management-alpine'
        container_name: "rabbitmq"
        ports:
          - ${RABBIT_PORT:?unspecified_rabbit_port}:5672
          - ${RABBIT_MANAGEMENT_PORT:?unspecified_rabbit_management_port}:15672

When this runs, docker ps shows

21400efd6493   uv-car-parts-segmentation:latest                             "python /uveye/app/m…"   5 seconds ago   Up 1 second    0.0.0.0:8080->8080/tcp, :::8080->8080/tcp                                                                                joint_car_parts_segmentor_1
bf4ab8581f1f   rabbitmq:3.6-management-alpine                               "docker-entrypoint.s…"   5 seconds ago   Up 4 seconds   4369/tcp, 5671/tcp, 0.0.0.0:5672->5672/tcp, :::5672->5672/tcp, 15671/tcp, 25672/tcp, 0.0.0.0:15672->15672/tcp, :::15672->15672/tcp   rabbitmq

I want to create a connection to that rabbitmq. The user:pass is guest:guest.

I was unable to do it, with the very uninformative AMQPConnectionError in all cases:

Below code runs in another, unrelated container.

connection = pika.BlockingConnection(pika.URLParameters("amqp://guest:guest@rabbitmq/"))
connection = pika.BlockingConnection(pika.URLParameters("amqp://guest:guest@localhost/"))

Also tried with

$ docker inspect -f '{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}' rabbitmq
172.27.0.2

and

connection = pika.BlockingConnection(pika.URLParameters("amqp://guest:guest@172.27.0.2/")) #

Also tried with

    credentials = pika.credentials.PlainCredentials(
        username="guest",
        password="guest"
    )
    parameters = pika.ConnectionParameters(
        host=ip_address, # tried all above options
        port=5672,
        credentials=credentials,
        heartbeat=10,
    )

Note that the container car_parts_segmentor is able to see the container rabbitmq. Both are started by docker-compose.

My assumption is this has to do with the uv_atp_network both containers live in, and I am trying to access a docker inside that network, from outside the network.

Is this really the problem?

If so, how can this be achieved?

For the future - how to get more informative errors from pika?

Body:
As I suspected, the problem was the name rabbitmq existed only in the network uv_atp_network.

The code attempting to connect to that network runs inside a container of its own, which was not present in the network.

Solution connect the current container to the network:

import socket

client = docker.from_env()
network_name = "uv_atp_network"
atp_container = client.containers.get(socket.gethostname())
client.networks.get(network_name).connect(container=atp_container.id)

After this, the above code in the question does work, because rabbitmq can be resolved.

connection = pika.BlockingConnection(pika.URLParameters("amqp://guest:guest@rabbitmq/"))


问:
Exception in thread "main" java.lang.IllegalAccessError: class TestTarzan tried to access method 'void Tarzan.<init>(int, int)'
Absolute beginner in learning Java here. I'm trying to implement a class which accepts user input. Here is the code:

```<code>public class Tarzan {
    int total;
    int safe;

    Tarzan(int total, int safe) {
        this.total = total;
        this.safe = safe;
    }

    Tarzan() {
        total = 50;
        safe = 30;
    }

    int calculateResult() {
        int result = total - safe;
        return result;
    }
}
</code>```
```<code>import java.util.Scanner;

public class TestTarzan {
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        System.out.println("Enter total: ");
        int t = sc.nextInt();

        System.out.println("Enter safe: ");
        int s = sc.nextInt();

        Tarzan ta = new Tarzan(t, s);
        int res = ta.calculateResult();
        System.out.println(res);
        sc.close();
    }
}
</code>```

Then when running java .\TestTarzan.java, I got this error:

```<code>Exception in thread "main" java.lang.IllegalAccessError: class TestTarzan tried to access method 'void Tarzan.<init>(int, int)' (TestTarzan is in unnamed module of loader com.sun.tools.javac.launcher.Main$MemoryClassLoader @38c6f217; Tarzan is in unnamed module of loader 'app')
        at TestTarzan.main(TestTarzan.java:13)
</code>```

Any idea why?

答:
While it is true that changing the access modifier of the constructor to public will fix this issue, it is important you learn an important lesson you are not getting from the comments or from the posted answer.

There are times when you want to control instance creation of an object and in those cases, it is perfectly fine to have access modification other than public. In this case, not having an access modifier in the constructor makes that method "package private." That means that only classes inside the same package (folder) can invoke this method. Even though the class itself is public, the constructor is not. Your Test class must be outside the package and that is why it cannot invoke the constructor of a class that the test class has visibility of.

The other problem you have with the IllegalStateError might be caused by not compiling all the classes you need to execute your program. You may want to try javac {your_package}/*.java to make sure all your classes under that package are compiled. Or better yet, use a build tool like Maven and build your classes that way. Remember, if the classes are in different folders, you might be partially compiling your classes if you exclude those packages when invoking your javac command.

Body:
Absolute beginner in learning Java here. I'm trying to implement a class which accepts user input. Here is the code:

public class Tarzan {
    int total;
    int safe;

    Tarzan(int total, int safe) {
        this.total = total;
        this.safe = safe;
    }

    Tarzan() {
        total = 50;
        safe = 30;
    }

    int calculateResult() {
        int result = total - safe;
        return result;
    }
}

import java.util.Scanner;

public class TestTarzan {
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        System.out.println("Enter total: ");
        int t = sc.nextInt();

        System.out.println("Enter safe: ");
        int s = sc.nextInt();

        Tarzan ta = new Tarzan(t, s);
        int res = ta.calculateResult();
        System.out.println(res);
        sc.close();
    }
}

Then when running java .\TestTarzan.java, I got this error:

Exception in thread "main" java.lang.IllegalAccessError: class TestTarzan tried to access method 'void Tarzan.<init>(int, int)' (TestTarzan is in unnamed module of loader com.sun.tools.javac.launcher.Main$MemoryClassLoader @38c6f217; Tarzan is in unnamed module of loader 'app')
        at TestTarzan.main(TestTarzan.java:13)

Any idea why?


问:
How to avoid many database round trips and a lot of irrelevant data?
I have worked with various applications and encountered this situation many times. Until now I have not figured out what is the best approach.

Here's the scenario:

I have an application either desktop or web

I need to retrieve simple documents from the database. The document has a general details and item details so the database:

GeneralDetails table:

```<code>| DocumentID | DateCreated | Owner     |
| 1          | 07/07/07    | Naruto    |
| 2          | 08/08/08    | Goku      |
| 3          | 09/09/09    | Taguro    |
</code>```

ItemDetails table

```<code>| DocumentID | Item        | Quantity  |
| 1          | Marbles     | 20        |
| 1          | Cards       | 56        |
| 2          | Yo-yo       | 1         |
| 2          | Chess board | 3         |
| 2          | GI Joe      | 12        |
| 3          | Rubber Duck | 1         |
</code>```

As you can see, the tables have a one-to-many relationship. Now, in order to retrieve all the documents and their respective items, I always do either of the two:

Method 1 - Many round trips (pseudo-code):

```<code> Documents = GetFromDB("select DocumentID, Owner " +
                       "from GeneralDetails")
 For Each Document in Documents
{
    Display(Document["CreatedBy"])
    DocumentItems = GetFromDB("select Item, Quantity " +
                              "from ItemDetails " +
                              "where DocumentID = " + Document["DocumentID"] + "")
    For Each DocumentItem in DocumentItems
    {
        Display(DocumentItem["Item"] + " " + DocumentItem["Quantity"])
    }
}
</code>```

Method 2 - Much irrelevant data (pseudo-code):

```<code>DocumentsAndItems = GetFromDB("select g.DocumentID, g.Owner, i.Item, i.Quantity " +
                              "from GeneralDetails as g " +
                              "inner join ItemDetails as i " +
                              "on g.DocumentID = i.DocumentID")
//Display...
</code>```

I used the first method when I was in college for desktop applications, the performance was not bad so I realized it was okay.

Until one day, I saw an article "Make the web faster", it says that many round trips to the database is bad; so ever since then I have used the second method.

On the second method, I avoided round trips by using inner join to retrieve the first and the second table at once, but it produces unecessary or redundant data. See the result set.

```<code>| DocumentID | Owner     | Item        | Quantity  |
| 1          | Naruto    | Marbles     | 20        |
| 1          | Naruto    | Cards       | 56        |
| 2          | Goku      | Yo-yo       | 1         |
| 2          | Goku      | Chess board | 3         |
| 2          | Goku      | GI Joe      | 12        |
| 3          | Taguro    | Rubber Duck | 1         |
</code>```

The result set has redundant DocumentID and Owner. It looks like an unnormalized database.

Now, the question is, how do I avoid round trips and at the same time avoid redundant data?

答:
You can read first table, extract keys of rows you want from second table and retrieve them via second select.

Something like

```<code>DocumentItems = GetFromDB("select Item, Quantity " +
                          "from ItemDetails " +
                          "where DocumentID in (" + LISTING_OF_KEYS + ")")
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have worked with various applications and encountered this situation many times. Until now I have not figured out what is the best approach.

Here's the scenario:

I have an application either desktop or web

I need to retrieve simple documents from the database. The document has a general details and item details so the database:

GeneralDetails table:

| DocumentID | DateCreated | Owner     |
| 1          | 07/07/07    | Naruto    |
| 2          | 08/08/08    | Goku      |
| 3          | 09/09/09    | Taguro    |

ItemDetails table

| DocumentID | Item        | Quantity  |
| 1          | Marbles     | 20        |
| 1          | Cards       | 56        |
| 2          | Yo-yo       | 1         |
| 2          | Chess board | 3         |
| 2          | GI Joe      | 12        |
| 3          | Rubber Duck | 1         |

As you can see, the tables have a one-to-many relationship. Now, in order to retrieve all the documents and their respective items, I always do either of the two:

Method 1 - Many round trips (pseudo-code):

 Documents = GetFromDB("select DocumentID, Owner " +
                       "from GeneralDetails")
 For Each Document in Documents
{
    Display(Document["CreatedBy"])
    DocumentItems = GetFromDB("select Item, Quantity " +
                              "from ItemDetails " +
                              "where DocumentID = " + Document["DocumentID"] + "")
    For Each DocumentItem in DocumentItems
    {
        Display(DocumentItem["Item"] + " " + DocumentItem["Quantity"])
    }
}

Method 2 - Much irrelevant data (pseudo-code):

DocumentsAndItems = GetFromDB("select g.DocumentID, g.Owner, i.Item, i.Quantity " +
                              "from GeneralDetails as g " +
                              "inner join ItemDetails as i " +
                              "on g.DocumentID = i.DocumentID")
//Display...

I used the first method when I was in college for desktop applications, the performance was not bad so I realized it was okay.

Until one day, I saw an article "Make the web faster", it says that many round trips to the database is bad; so ever since then I have used the second method.

On the second method, I avoided round trips by using inner join to retrieve the first and the second table at once, but it produces unecessary or redundant data. See the result set.

| DocumentID | Owner     | Item        | Quantity  |
| 1          | Naruto    | Marbles     | 20        |
| 1          | Naruto    | Cards       | 56        |
| 2          | Goku      | Yo-yo       | 1         |
| 2          | Goku      | Chess board | 3         |
| 2          | Goku      | GI Joe      | 12        |
| 3          | Taguro    | Rubber Duck | 1         |

The result set has redundant DocumentID and Owner. It looks like an unnormalized database.

Now, the question is, how do I avoid round trips and at the same time avoid redundant data?

Body:
You can read first table, extract keys of rows you want from second table and retrieve them via second select.

Something like

DocumentItems = GetFromDB("select Item, Quantity " +
                          "from ItemDetails " +
                          "where DocumentID in (" + LISTING_OF_KEYS + ")")


问:
how to write $or query in node
This is how I write Mongo queries in Node.

query["serviceProvider.type"] = "prepaid";

but I need to write this query in my Node code which works only in MongoDB CLI. How can I achieve this i.e. I need to query same keys with two different values.

```<code>db = db.getSiblingDB("test");
db.getCollection("transactions").find(
    {

                $or : [
                    {
                        "serviceProvider.type" : "prepaid"
                    },
                    {
                        "serviceProvider.type" : "dth"
                    }
                ]

    }
);

</code>```
```<code>{
    "_id" : ObjectId("5d8b057e3a22472facdb89a4"),
    "customer" : {
        "isCustomerPaid" : true,
        "customerID" : "",
        "customer" : ""
    },
    "transaction" : {
        "transStatus" : false,
        "transID" : "15693919985540280",
        "number" : "8332900803",
        "amount" : NumberInt(5),
        "error" : "Something went wrong. Please try again after sometime."
    },
    "couponSurvey" : {
        "status" : false,
        "isEligible" : false
    },
    "status" : true,
    "advisor" : {
        "advisorID" : "BAA0280",
        "name" : "John BA",
        "phoneNumber" : 8005301205.0
    },
    "serviceProvider" : {
        "type" : "dth",
        "providerID" : "5bbb42e7a28b1daee826d7ec",
        "providerName" : "Sun Direct"
    },
    "provider" : {
        "refId" : "00",
        "status" : "fail",
        "startTime" : ISODate("2019-09-25T06:13:18.554+0000"),
        "endTime" : ISODate("2019-09-25T06:13:18.554+0000"),
        "message" : "Invalid Denomination"
    },
    "extras" : {
        "imei" : "865300302225654",
        "latitude" : "99.9385189",
        "longitude" : "11.5827393"
    },
    "createdAt" : ISODate("2019-09-25T06:13:18.790+0000"),
    "updatedAt" : ISODate("2019-09-25T06:13:18.790+0000"),
    "__v" : NumberInt(0)
}
</code>```

This is the sample data in database. Please let me know how I can query the parameters I require.

答:
If you want to query if value at a particular key is one of a list of values, instead of bothering with $or you can use $in.

```<code>const findQuery = {
  "serviceProvider.type": {
    $in: [
      "prepaid",
      "dth"
    ]
  }
}
</code>```

Mongoplayground Link Here

Title: how to write $or query in node

Body:
This is how I write Mongo queries in Node.

query["serviceProvider.type"] = "prepaid";

but I need to write this query in my Node code which works only in MongoDB CLI. How can I achieve this i.e. I need to query same keys with two different values.

db = db.getSiblingDB("test");
db.getCollection("transactions").find(
    {

                $or : [
                    {
                        "serviceProvider.type" : "prepaid"
                    },
                    {
                        "serviceProvider.type" : "dth"
                    }
                ]

    }
);

{
    "_id" : ObjectId("5d8b057e3a22472facdb89a4"),
    "customer" : {
        "isCustomerPaid" : true,
        "customerID" : "",
        "customer" : ""
    },
    "transaction" : {
        "transStatus" : false,
        "transID" : "15693919985540280",
        "number" : "8332900803",
        "amount" : NumberInt(5),
        "error" : "Something went wrong. Please try again after sometime."
    },
    "couponSurvey" : {
        "status" : false,
        "isEligible" : false
    },
    "status" : true,
    "advisor" : {
        "advisorID" : "BAA0280",
        "name" : "John BA",
        "phoneNumber" : 8005301205.0
    },
    "serviceProvider" : {
        "type" : "dth",
        "providerID" : "5bbb42e7a28b1daee826d7ec",
        "providerName" : "Sun Direct"
    },
    "provider" : {
        "refId" : "00",
        "status" : "fail",
        "startTime" : ISODate("2019-09-25T06:13:18.554+0000"),
        "endTime" : ISODate("2019-09-25T06:13:18.554+0000"),
        "message" : "Invalid Denomination"
    },
    "extras" : {
        "imei" : "865300302225654",
        "latitude" : "99.9385189",
        "longitude" : "11.5827393"
    },
    "createdAt" : ISODate("2019-09-25T06:13:18.790+0000"),
    "updatedAt" : ISODate("2019-09-25T06:13:18.790+0000"),
    "__v" : NumberInt(0)
}

This is the sample data in database. Please let me know how I can query the parameters I require.

Body:
If you want to query if value at a particular key is one of a list of values, instead of bothering with $or you can use $in.

const findQuery = {
  "serviceProvider.type": {
    $in: [
      "prepaid",
      "dth"
    ]
  }
}

Mongoplayground Link Here


问:
Moving an slice item from one position to another in go
I' trying to move an item from one position to another inside a slice. Go Playground

```<code>indexToRemove := 1
indexWhereToInsert := 4

slice := []int{0,1,2,3,4,5,6,7,8,9}

slice = append(slice[:indexToRemove], slice[indexToRemove+1:]...)
fmt.Println("slice:", slice)

newSlice := append(slice[:indexWhereToInsert], 1)
fmt.Println("newSlice:", newSlice)

slice = append(newSlice, slice[indexWhereToInsert:]...)
fmt.Println("slice:", slice)
</code>```

This produces to following output:

```<code>slice: [0 2 3 4 5 6 7 8 9]
newSlice: [0 2 3 4 1]
slice: [0 2 3 4 1 1 6 7 8 9]
</code>```

But I would expect the output be like this:

```<code>slice: [0 2 3 4 5 6 7 8 9]
newSlice: [0 2 3 4 1]
slice: [0 2 3 4 1 **5** 6 7 8 9]
</code>```

Where is my fault?

答:
Here's a simple shift right example without copy but also includes a loop showing how it's all really pointers.

Playground

package main

import "fmt"

func main() {
    s := []int{2, 3, 5, 7, 11, 13}
    for _, e := range s {
        // Will always shift 2 as it's been shifted each time
        fmt.Println(e, shiftRight(s, e))
    }
}

func shiftRight(s []int, e int) []int {
    if len(s) > 1 { // No where to shift to if 1 item
        // Go through the slice finding the item to shift
        for i, item := range s {
            if item == e {
                if i == len(s)-1 {
                    break // already at the end, can't shift any further
                }
                s[i] = s[i+1]
                s[i+1] = item
                break
            }
        }
    }
    return s
}

```

Body:
I' trying to move an item from one position to another inside a slice. Go Playground

indexToRemove := 1
indexWhereToInsert := 4

slice := []int{0,1,2,3,4,5,6,7,8,9}

slice = append(slice[:indexToRemove], slice[indexToRemove+1:]...)
fmt.Println("slice:", slice)

newSlice := append(slice[:indexWhereToInsert], 1)
fmt.Println("newSlice:", newSlice)

slice = append(newSlice, slice[indexWhereToInsert:]...)
fmt.Println("slice:", slice)

This produces to following output:

slice: [0 2 3 4 5 6 7 8 9]
newSlice: [0 2 3 4 1]
slice: [0 2 3 4 1 1 6 7 8 9]

But I would expect the output be like this:

slice: [0 2 3 4 5 6 7 8 9]
newSlice: [0 2 3 4 1]
slice: [0 2 3 4 1 **5** 6 7 8 9]

Where is my fault?


问:
Error after running the command "npx react-native start"
```<code>Failed to construct transformer:  Error: error:0308010C:digital envelope routines::unsupported
        at new Hash (node:internal/crypto/hash:67:19)
        at Object.createHash (node:crypto:130:10)
        at stableHash (C:\Users\Anupam K Krishnan\Desktop\lcorn\myProject\node_modules\metro-cache\src\stableHash.js:19:8)
        at Object.getCacheKey (C:\Users\Anupam K Krishnan\Desktop\lcorn\myProject\node_modules\metro-transform-worker\src\index.js:593:7)
        at getTransformCacheKey (C:\Users\Anupam K Krishnan\Desktop\lcorn\myProject\node_modules\metro\src\DeltaBundler\getTransformCacheKey.js:24:19)
        at new Transformer (C:\Users\Anupam K Krishnan\Desktop\lcorn\myProject\node_modules\metro\src\DeltaBundler\Transformer.js:48:9)
        at C:\Users\Anupam K Krishnan\Desktop\lcorn\myProject\node_modules\metro\src\Bundler.js:22:29
        at runNextTicks (node:internal/process/task_queues:61:5)
        at processTimers (node:internal/timers:497:9) {
      opensslErrorStack: [ 'error:03000086:digital envelope routines::initialization error' ],
      library: 'digital envelope routines',
      reason: 'unsupported',
      code: 'ERR_OSSL_EVP_UNSUPPORTED'
    }
</code>```

I'm a beginner at react-native

Kindly tell how can I resolve this

答: I encountered the same error, but for some reason switching node versions with nvm did not work. Removing nvm and using the system's node v16.5 solved the problem...</p>

Body:
Failed to construct transformer:  Error: error:0308010C:digital envelope routines::unsupported
        at new Hash (node:internal/crypto/hash:67:19)
        at Object.createHash (node:crypto:130:10)
        at stableHash (C:\Users\Anupam K Krishnan\Desktop\lcorn\myProject\node_modules\metro-cache\src\stableHash.js:19:8)
        at Object.getCacheKey (C:\Users\Anupam K Krishnan\Desktop\lcorn\myProject\node_modules\metro-transform-worker\src\index.js:593:7)
        at getTransformCacheKey (C:\Users\Anupam K Krishnan\Desktop\lcorn\myProject\node_modules\metro\src\DeltaBundler\getTransformCacheKey.js:24:19)
        at new Transformer (C:\Users\Anupam K Krishnan\Desktop\lcorn\myProject\node_modules\metro\src\DeltaBundler\Transformer.js:48:9)
        at C:\Users\Anupam K Krishnan\Desktop\lcorn\myProject\node_modules\metro\src\Bundler.js:22:29
        at runNextTicks (node:internal/process/task_queues:61:5)
        at processTimers (node:internal/timers:497:9) {
      opensslErrorStack: [ 'error:03000086:digital envelope routines::initialization error' ],
      library: 'digital envelope routines',
      reason: 'unsupported',
      code: 'ERR_OSSL_EVP_UNSUPPORTED'
    }

I'm a beginner at react-native

Kindly tell how can I resolve this


问:
Faster AUC in sklearn or python
I have over half a million pairs of true labels and predicted scores (the length of each 1d array varies and can be between 10,000-30,000 in length) that I need to calculate the AUC for. Right now, I have a for-loop that calls:

```<code># Simple Example with two pairs of true/predicted values instead of 500,000
from sklearn import metrics
import numpy as np

pred = [None] * 2
pred[0] = np.array([3,2,1])
pred[1] = np.array([15,12,14,11,13])

true = [None] * 2
true[0] = np.array([1,0,0])
true[1] = np.array([1,1,1,0,0])

for i in range(2):
    fpr, tpr, thresholds = metrics.roc_curve(true[i], pred[i])
    print metrics.auc(fpr, tpr)
</code>```

However, it takes about 1-1.5 hours to process the entire dataset and calculate the AUC for each true/prediction pair. Is there a faster/better way to do this?

Update

Each of the 500k entries can have shape (1, 10k+). I understand that I could parallelize it but I'm stuck on a machine with only two processors and so my time can really only be effectively cut down to say, 30-45, minutes which is still too long. I've identified that the AUC calculation itself is slow and was hoping to find a faster AUC algorithm than what is available in sklearn. Or, at least, find a better way to vectorize the AUC calculation so that it can be broadcasted across multiple rows.

答:
I came up with a vectorized way to calculate ROC AUC. It's faster than sklearns implementation. Suppose you have N examples with N_pos (+1) and N_neg (-1).

So N = N_pos + N_neg

Compute an index vector (I): [1, 2, 3, 4,..., N]

Compute the ranking vector (R): [1, 0, 1, ..., 1]

The ranking vector is where your 0s and 1s end up due to your ranking score (e.g., predicted probability from model). The first position means this label got the highest score.

Now we have vectorized way to compute ROC AUC:

See here for details and a comparison to sklearn: https://medium.com/building-ibotta/understanding-roc-auc-part-2-2-a1e418a3afdb

Title: Faster AUC in sklearn or python

Body:
I have over half a million pairs of true labels and predicted scores (the length of each 1d array varies and can be between 10,000-30,000 in length) that I need to calculate the AUC for. Right now, I have a for-loop that calls:

# Simple Example with two pairs of true/predicted values instead of 500,000
from sklearn import metrics
import numpy as np

pred = [None] * 2
pred[0] = np.array([3,2,1])
pred[1] = np.array([15,12,14,11,13])

true = [None] * 2
true[0] = np.array([1,0,0])
true[1] = np.array([1,1,1,0,0])

for i in range(2):
    fpr, tpr, thresholds = metrics.roc_curve(true[i], pred[i])
    print metrics.auc(fpr, tpr)

However, it takes about 1-1.5 hours to process the entire dataset and calculate the AUC for each true/prediction pair. Is there a faster/better way to do this?

Update

Each of the 500k entries can have shape (1, 10k+). I understand that I could parallelize it but I'm stuck on a machine with only two processors and so my time can really only be effectively cut down to say, 30-45, minutes which is still too long. I've identified that the AUC calculation itself is slow and was hoping to find a faster AUC algorithm than what is available in sklearn. Or, at least, find a better way to vectorize the AUC calculation so that it can be broadcasted across multiple rows.


问:
Loading type from new assembly using structuremap.net
I'm playing around with structuremap.net and what I'm trying to do (I'm not sure if it possible or not) is loading type implementing specific interface and this type exist in assembly that's not refrence in my application, for example i want to drop new assembly in the application directory and configure the IOC container to load , currently i'm not using a configuration file i'm just testing the concept :)

Thanks in advance

答:
It's possible to scan all Assemblies in the application directory:

```<code>ObjectFactory.Initialize(
    c => c.Scan( s =>
    {
        s.AssembliesFromBaseDirectory();
        s.AddAllTypesOf<IMyInterface>().NameBy(type => type.Name);
    })
);
</code>```

or specific assemblies in a specific folder:

```<code>ObjectFactory.Initialize(
    c => c.Scan( s =>
    {
        s.AssembliesFromPath("thePath", assembly => assembly.GetName()
            .Name.Contains("Extension"));
        s.AddAllTypesOf<IMyInterface>();
    })
);
</code>```

Body:
It's possible to scan all Assemblies in the application directory:

ObjectFactory.Initialize(
    c => c.Scan( s =>
    {
        s.AssembliesFromBaseDirectory();
        s.AddAllTypesOf<IMyInterface>().NameBy(type => type.Name);
    })
);

or specific assemblies in a specific folder:

ObjectFactory.Initialize(
    c => c.Scan( s =>
    {
        s.AssembliesFromPath("thePath", assembly => assembly.GetName()
            .Name.Contains("Extension"));
        s.AddAllTypesOf<IMyInterface>();
    })
);


问:
Firestore: Query multiple nested collections
I have a nested collection in firestore as shown below:

```<code>db-dev
        user
             user-id-1
                       events-collection
                       ...
             user-id-2
                       events-collection
                       ...
             user-id-3
                       events-collection
                       ...
</code>```

I want to query all the events from events-collection. However, I also want to keep the above schema as the admin needs to view all events-collection and specific users need to view their specific collection.

The query I write now looks something like this:

```<code>const uids = await getAllUserIds(); //Returns all user ID
const promises = uids.map(element => db.collection(`db-dev/user/${element}/events-collection/`).get())

const documents = await Promise.all(promises);
</code>```

I am not very confident if this is the most optimized way to query the data or should I use something else? Can somebody please help me out here?

答:
To read from all events-collection collections in one go, you can use a collection group query.

For example, without any conditions, this reads all documents from all collections named events-collection:

```<code>db.collectionGroup('events-collection').get()
</code>```

If you want to read only the events-collection collections under /user, you can use the trick that Sam showed here: CollectionGroupQuery but limit search to subcollections under a particular document

Body:
I have a nested collection in firestore as shown below:

db-dev
        user
             user-id-1
                       events-collection
                       ...
             user-id-2
                       events-collection
                       ...
             user-id-3
                       events-collection
                       ...

I want to query all the events from events-collection. However, I also want to keep the above schema as the admin needs to view all events-collection and specific users need to view their specific collection.

The query I write now looks something like this:

const uids = await getAllUserIds(); //Returns all user ID
const promises = uids.map(element => db.collection(`db-dev/user/${element}/events-collection/`).get())

const documents = await Promise.all(promises);

I am not very confident if this is the most optimized way to query the data or should I use something else? Can somebody please help me out here?

Body:
To read from all events-collection collections in one go, you can use a collection group query.

For example, without any conditions, this reads all documents from all collections named events-collection:

db.collectionGroup('events-collection').get()

If you want to read only the events-collection collections under /user, you can use the trick that Sam showed here: CollectionGroupQuery but limit search to subcollections under a particular document


问:
C++ pass by reference tricky situation
I'm trying to figure what happens to an "rvalue",temporary object, after the variable used to refer this object deleted from stack.

Code example:

```<code>#include<iostream>
using namespace std;

class Base
{
  private:
  int &ref;
  public:
  Base(int &passed):ref(passed)
  {
    cout << "Value is " << ref << endl;
  }
  int getvalue(){
    return ref;
  }
};

int main()
{
  Base *myobject;
    {
    int ref=10;
    myobject = new Base (ref);
    ref++;
    }                           //ref delete from stack.
  cout << myobject->getvalue() << endl;
  return 0;
}
</code>```

I expected the second output(second cout) to give me some random garbage because ref deleted but instead I got the value of the current state of ref, I wander what happened after the ref got deleted is it pure luck? or myobject.ref stored the value of the ref he construct with?

Edit: adding a visualizer to support my point that in the end myobject.ref pointing nowhere C++ visualizer

答:
From Reference declaration documentation

it is possible to create a program where the lifetime of the referred-to object ends, but the reference remains accessible (dangling). Accessing such a reference is undefined behavior.

In your program the referred-to object ref ends at } after ref++. This means that the ref data member is now a dangling reference. And according to the above quoted statement, accessing that reference(which you do when you call getValue) is undefiend behavior.

Undefined behavior means anything1 can happen including but not limited to the program giving your expected output. But never rely(or make conclusions based) on the output of a program that has undefined behavior.

So the output that you're seeing(maybe seeing) is a result of undefined behavior. And as i said don't rely on the output of a program that has UB. For example, the output of the same program is different here and here.

So the first step to make the program correct would be to remove UB. Then and only then you can start reasoning about the output of the program.

1For a more technically accurate definition of undefined behavior see this where it is mentioned that: there are no restrictions on the behavior of the program.

Title: C++ pass by reference tricky situation

Body:
I'm trying to figure what happens to an "rvalue",temporary object, after the variable used to refer this object deleted from stack.

Code example:

#include<iostream>
using namespace std;

class Base
{
  private:
  int &ref;
  public:
  Base(int &passed):ref(passed)
  {
    cout << "Value is " << ref << endl;
  }
  int getvalue(){
    return ref;
  }
};

int main()
{
  Base *myobject;
    {
    int ref=10;
    myobject = new Base (ref);
    ref++;
    }                           //ref delete from stack.
  cout << myobject->getvalue() << endl;
  return 0;
}

I expected the second output(second cout) to give me some random garbage because ref deleted but instead I got the value of the current state of ref, I wander what happened after the ref got deleted is it pure luck? or myobject.ref stored the value of the ref he construct with?

Edit: adding a visualizer to support my point that in the end myobject.ref pointing nowhere <a href="https://pythontutor.com/cpp.html#code=%23include%3Ciostream%3E%0Ausing%20namespace%20std%3B%0A%0Aclass%20Base%0A%7B%0A%20%20private%3A%0A%20%20int%20%26ref%3B%0A%20%20public%3A%0A%20%20Base%28int%20%26passed%29%3Aref%28passed%29%0A%20%20%7B%0A%20%20%20%20cout%20%3C%3C%20%22Value%20is%20%22%20%3C%3C%20ref%20%3C%3C%20endl%3B%0A%20%20%7D%0A%20%20int%20getvalue%28%29%7B%0A%20%20%20%20return%20ref%3B%0A%20%20%7D%0A%7D%3B%0A%0Aint%20main%28%29%0A%7B%0A%20%20Base%20*myobject%3B%0A%20%20%7B%0A%20%20int%20ref%3D10%3B%0A%20%20myobject%20%3D%20new%20Base%20%28ref%29%3B%0A%20%20ref%2B%2B%3B%0A%20%20%7D%0A%20%20cout%20%3C%3C%20myobject-%3Egetvalue%28%29%3B%0A%20%20return%200%3B%0A%7D&curInstr=12&mode=display&origin=opt-frontend.js&py=cpp_g%2B%2B9.3.0&rawInputLstJSON=%5B%5D" rel="nofollow noreferrer">C++ visualizer


问:
What does this line mean ? (Logstash Conf & Grok Syntax)
Hi i'm new to Logstash and Grok syntax, I'm trying to understand what are those line meaning

```<code>codec => multiline { pattern => "^{$" negate => "true" what => "previous" }
</code>```

and

```<code>mutate {
                gsub => ["message", "'", '"']
        }
</code>```

Thanks !

答:
it is pretty well explain in the official documentation of the multiline codec plugin:

pattern => ^{$ matches lines that only contain a { character and end immediately

negate => true means that line NOT matching the pattern are considered

what => previous means that the current matched line relates to the previous one

In summary, these settings mean that all lines that do NOT consist of only { belong to the previous line.

Concretely, this multiline filter is for putting together JSON data that was pretty-printed on several line, like this:

```<code>{
   "bla": {
       "test": 1
   }
}
</code>```

The above pretty-printed JSON will be handled as if it had been printed as a single line, like this:

```<code>{ "bla": { "test": 1 } }
</code>```

Regarding the second filter (mutate/gsub), it is used to replace all single quotes with double quotes.

Body:
Hi i'm new to Logstash and Grok syntax, I'm trying to understand what are those line meaning

codec => multiline { pattern => "^{$" negate => "true" what => "previous" }

and

mutate {
                gsub => ["message", "'", '"']
        }

Thanks !

Body:
it is pretty well explain in the official documentation of the multiline codec plugin:

pattern => ^{$ matches lines that only contain a { character and end immediately

negate => true means that line NOT matching the pattern are considered

what => previous means that the current matched line relates to the previous one

In summary, these settings mean that all lines that do NOT consist of only { belong to the previous line.

Concretely, this multiline filter is for putting together JSON data that was pretty-printed on several line, like this:

{
   "bla": {
       "test": 1
   }
}

The above pretty-printed JSON will be handled as if it had been printed as a single line, like this:

{ "bla": { "test": 1 } }

Regarding the second filter (mutate/gsub), it is used to replace all single quotes with double quotes.


问:
Location of a directory created with mkdir in PHP
I've been trying a bunch of stuff with creating zips and files and whatnot with php, and it's safe to say I messed up quite a few times...

My most recent:

```<code>$tmpp = tempnam('../test','mod');
echo "<br/>"."<br/>".basename($tmpp).'<br/>'."<br/>".$tmpp.'<br/>'."<br/>";
echo mkdir(basename('../test/'.$tmpp));
</code>```

I meant to do

```<code>$tmpp = tempnam('../test','mod');
echo "<br/>"."<br/>".basename($tmpp).'<br/>'."<br/>".$tmpp.'<br/>'."<br/>";
echo mkdir('../test/'.basename($tmpp));
</code>```

Oh well though, mistake is made. Where is this just created directory? How can I see all the other files and directories and things as well as the tmp folder?

edit: long story short: I've created a bunch of files and directories that I can't account for and I want to be able to find them on clean then off my server. How can I view ALL the files on my server, including in the tmp folder?

答:
What's the return value of mkdir? "false" ?

If so, I think maybe you need check your write permisson of the account which execute this php script.

Body:
I've been trying a bunch of stuff with creating zips and files and whatnot with php, and it's safe to say I messed up quite a few times...

My most recent:

$tmpp = tempnam('../test','mod');
echo "
"."
".basename($tmpp).'
'."
".$tmpp.'
'."
";
echo mkdir(basename('../test/'.$tmpp));

I meant to do

$tmpp = tempnam('../test','mod');
echo "
"."
".basename($tmpp).'
'."
".$tmpp.'
'."
";
echo mkdir('../test/'.basename($tmpp));

Oh well though, mistake is made. Where is this just created directory? How can I see all the other files and directories and things as well as the tmp folder?

edit: long story short: I've created a bunch of files and directories that I can't account for and I want to be able to find them on clean then off my server. How can I view ALL the files on my server, including in the tmp folder?


问:
Pythonic way to find duplicate and unique values in a list of dictonaries
I have a list of dictonaries:

```<code>[
{'name' : 'product a', 'sku': 'p100', 'price: 1.2},
{'name' : 'product x', 'sku': 'p120', 'price: 1.3},
{'name' : 'product x', 'sku': 'p100', 'price: 2.2},
{'name' : 'product a', 'sku': 'p100', 'price: 4.1},
{'name' : 'product a', 'sku': 'p20', 'price: 1.3},
{'name' : 'product a', 'sku': 'p20', 'price: 2.2}]
</code>```

And I want to find duplicate and unique values of sku and return them as two new lists. (Duplicate in my case means 3 or more times. Triplicate)

This is a working solution:

```<code>def find_dict_duplicates(lines, key, times=2):
    duplicate = []
    unique = []
    for line in lines:
        count = 0
        for l in lines:
            if line[key] == l[key]:
                count += 1
        if count > times:
            duplicates.append(line)
        else:
            unique.append(line)
return duplicate, unique
</code>```

Results:

```<code>duplicates =
[
{'name' : 'product a', 'sku': 'p100', 'price: 1.2},
{'name' : 'product a', 'sku': 'p100', 'price: 2.2},
{'name' : 'product a', 'sku': 'p100', 'price: 4.1}]

unique =
[
{'name' : 'product a', 'sku': 'p120', 'price: 1.3},
{'name' : 'product a', 'sku': 'p20', 'price: 1.3},
{'name' : 'product a', 'sku': 'p20', 'price: 2.2}]    # The critiria is more than 2 times to be consider duplicate so this is correct
</code>```

But is super slow and ugly.
Is slow because if a list contains 50.000 products then the comparison needed is 50.000^2 = 2.500.000.000 (5+ minutes waiting)
And ugly since this is more like c than python.

Can you sudgest a better way?

答: You can iterate through the dictionary once and maintain another dictionary which stores count of each value. Then you can use the count dictionary to get the unique and duplicate entries. Its complexity is O(n).</p>

Body:
I have a list of dictonaries:

[
{'name' : 'product a', 'sku': 'p100', 'price: 1.2},
{'name' : 'product x', 'sku': 'p120', 'price: 1.3},
{'name' : 'product x', 'sku': 'p100', 'price: 2.2},
{'name' : 'product a', 'sku': 'p100', 'price: 4.1},
{'name' : 'product a', 'sku': 'p20', 'price: 1.3},
{'name' : 'product a', 'sku': 'p20', 'price: 2.2}]

And I want to find duplicate and unique values of sku and return them as two new lists. (Duplicate in my case means 3 or more times. Triplicate)

This is a working solution:

def find_dict_duplicates(lines, key, times=2):
    duplicate = []
    unique = []
    for line in lines:
        count = 0
        for l in lines:
            if line[key] == l[key]:
                count += 1
        if count > times:
            duplicates.append(line)
        else:
            unique.append(line)
return duplicate, unique

Results:

duplicates =
[
{'name' : 'product a', 'sku': 'p100', 'price: 1.2},
{'name' : 'product a', 'sku': 'p100', 'price: 2.2},
{'name' : 'product a', 'sku': 'p100', 'price: 4.1}]

unique =
[
{'name' : 'product a', 'sku': 'p120', 'price: 1.3},
{'name' : 'product a', 'sku': 'p20', 'price: 1.3},
{'name' : 'product a', 'sku': 'p20', 'price: 2.2}]    # The critiria is more than 2 times to be consider duplicate so this is correct

But is super slow and ugly.
Is slow because if a list contains 50.000 products then the comparison needed is 50.000^2 = 2.500.000.000 (5+ minutes waiting)
And ugly since this is more like c than python.

Can you sudgest a better way?


问:
Selenium Automation - How to click on particular button periodically until getting another element's updated text value?
In my webpage, I have a refresh button and one Text Field,
when i landed to that page, Initially that Text Field value would be processing (In backend there is a functionality which is processing, Inorder to inform the user, textfield value is processing in UI), and after functionality is done, that Text Field would be completed

Now coming to the question,
We will get to know the updated value of Text Field only when we click on the refresh button,

Is there a way to make a WebElement to be waited until that Text field has value as completed? We also need to click on that particular refresh button periodically to check that text field value became completed or not

I've found a method called textToBePresentInElement in ExpectedConditions, But using this, we cannot refresh button periodically,
Any other solution selenium webdriver is providing?

答:
It's possible to implement a custom Expected condition:

```<code>import org.openqa.selenium.support.ui.ExpectedCondition

public static ExpectedCondition<Boolean> textToBePresentForElementWithRefreshByClick(By originalElement, Strint expectedText, By refreshElement) {
    return new ExpectedCondition<Boolean>() {
        private boolean hasText = false;
        private String currentText = "";

        @Override
        public Boolean apply(WebDriver driver) {
            currentText = driver.findElement(originalElement).getText();
            hasText = currentText == expectedText;
            if(!hasText) {
                driver.findElement(refreshElement).click();
                // Optionally some sleep might be added here, like Thread.sleep(1000);
            }
            return hasText;
        }

        @Override
        public String toString() {
            return String.format("element \"%s\" should have text \"%s\", found text: \"%s\"", originalElement.toString(), expectedText, currentText);
        }
    };
}
</code>```

Usage:

```<code>By originalElement = ...;
By refreshElement = ...;

new WebDriverWait(driver, Duration.ofSeconds(10)).until(
    textToBePresentForElementWithRefreshByClick(originalElement, "completed", refreshElement)
)
</code>```

Body:
It's possible to implement a custom Expected condition:

import org.openqa.selenium.support.ui.ExpectedCondition

public static ExpectedCondition<Boolean> textToBePresentForElementWithRefreshByClick(By originalElement, Strint expectedText, By refreshElement) {
    return new ExpectedCondition<Boolean>() {
        private boolean hasText = false;
        private String currentText = "";

        @Override
        public Boolean apply(WebDriver driver) {
            currentText = driver.findElement(originalElement).getText();
            hasText = currentText == expectedText;
            if(!hasText) {
                driver.findElement(refreshElement).click();
                // Optionally some sleep might be added here, like Thread.sleep(1000);
            }
            return hasText;
        }

        @Override
        public String toString() {
            return String.format("element \"%s\" should have text \"%s\", found text: \"%s\"", originalElement.toString(), expectedText, currentText);
        }
    };
}

Usage:

By originalElement = ...;
By refreshElement = ...;

new WebDriverWait(driver, Duration.ofSeconds(10)).until(
    textToBePresentForElementWithRefreshByClick(originalElement, "completed", refreshElement)
)


答:
A vectorized dplyr solution with pmax(), which facilitates tidyselection while avoiding rowwise() inefficiency:

Solution

Once you've set everything up

```<code>library(dplyr)

# ...
# Code to generate 'your_data'.
# ...
</code>```

here is your solution for the columns {max1, max2, max3}

```<code>your_data %>% transmute(YEAR = year, MAX = pmax(max1, max2, max3))
</code>```

and more generally for all columns of the form max*:

```<code>your_data %>% transmute(YEAR = year, MAX = do.call(pmax, unname(across(
  # Tidy selection of 'max*' columns:
  starts_with("max")
))))
</code>```

At your discretion, you can replace starts_with() with another selection helper like matches("^max\\d+$").

Results

Given your_data reproduced here

```<code>your_data <- structure(
  list(
    year = c(2001, 2002, 2003, 2004),
    max1 = c(10, 103, 21, 27),
    max2 = c(101, 19, 23, 28),
    max3 = c(87, 88, 89, 91)
  ),
  row.names = c(NA, -4L),
  class = "data.frame"
)
</code>```

this tidy workflow should yield the following data.frame:

```<code>  YEAR MAX
1 2001 101
2 2002 103
3 2003  89
4 2004  91
</code>```

Title: how to get max from multiple columns in R

Body:
INPUT:-
 year max1 max2 max3
2001   10  101   87
2002  103   19   88
2003   21   23   89
2004   27   28   91

OUTPUT:-

YEAR    MAX

2001     101

2002     103

2003      89

2004      91

Body:
A vectorized dplyr solution with pmax(), which facilitates tidyselection while avoiding rowwise() inefficiency:

Solution

Once you've set everything up

library(dplyr)

# ...
# Code to generate 'your_data'.
# ...

here is your solution for the columns {max1, max2, max3}

your_data %>% transmute(YEAR = year, MAX = pmax(max1, max2, max3))

and more generally for all columns of the form max*:

your_data %>% transmute(YEAR = year, MAX = do.call(pmax, unname(across(
  # Tidy selection of 'max*' columns:
  starts_with("max")
))))

At your discretion, you can replace starts_with() with another selection helper like matches("^max\\d+$").

Results

Given your_data reproduced here

your_data <- structure(
  list(
    year = c(2001, 2002, 2003, 2004),
    max1 = c(10, 103, 21, 27),
    max2 = c(101, 19, 23, 28),
    max3 = c(87, 88, 89, 91)
  ),
  row.names = c(NA, -4L),
  class = "data.frame"
)

this tidy workflow should yield the following data.frame:

  YEAR MAX
1 2001 101
2 2002 103
3 2003  89
4 2004  91


问:
How to customize file_picker UI in flutter
I find it difficult to customize the UI of the file picker. I want to implement a picker with my own new UI rather than a native picker. What should I do?

waiting for a good answer!
I'm not good at English, so I got help from a translator. thank you for reading.

https://github.com/fluttercandies/flutter_wechat_assets_picker
Is it possible to customize with this plugin?

答: you can use file_manager plugin it support android and linux by the time this answer was written .


问:
react-i18next navigates back to first screen in navigation on changeLanguage
My problem is that when changing language with react-18next it navigates back to first screen.

I call it like this for example:

i18n.changeLanguage('en')

and I have init like:

```<code>i18n.use(initReactI18next).init({
  resources: {
    en: {
      translation: en
    },
    nl: {
      translation: nl
    }
  }
})
</code>```

And if my navigation has routes like ['Main', 'Settings', 'Language'] and my language change button is in Language view (I navigate there like: Main -> Settings -> Language), it redirects user to Main screen after language has changed.

Language changes correctly and everything works, apart that it seems to reset everything. I don't have any specific navigation setup.

Anybody has experienced anything like this?

答: I found the problem - I was using useTranslation hook inside my navigation component. So as translations changed there, it also reset navigation to first screen.</p>

Body:
My problem is that when changing language with react-18next it navigates back to first screen.

I call it like this for example:

i18n.changeLanguage('en')

and I have init like:

i18n.use(initReactI18next).init({
  resources: {
    en: {
      translation: en
    },
    nl: {
      translation: nl
    }
  }
})

And if my navigation has routes like ['Main', 'Settings', 'Language'] and my language change button is in Language view (I navigate there like: Main -> Settings -> Language), it redirects user to Main screen after language has changed.

Language changes correctly and everything works, apart that it seems to reset everything. I don't have any specific navigation setup.

Anybody has experienced anything like this?


问:
How to disable other buttons onclick for a short period of time
i have simple quizz project where i fetch data of questions and answers my problem is when i click on one of the answers i want other buttons to be disabled because if someone keeps pressing on other options the quiz will rapidly change questions. i want to disable other answer options when i clik on the  answer and then after the next question generates enable them again and so on</p>
```<code>
import './App.css';
import axios from 'axios'
import {useState,useEffect} from 'react'

function App() {
  const [quiz,setQuiz] = useState([])
  const [answer,setAnswer] = useState([])
  const [correct,setCorrect] =useState('')
  const [points,setPoints] = useState(0)
  const [turns,setTurns] = useState(0)
  const [disabled,setDisabled] = useState(false)

  function refreshPage() {
    window.location.reload(false);
  }

  useEffect(()=>{
    axios.get('https://opentdb.com/api.php?amount=10')
    .then(res =>{
       setQuiz(res.data.results[0])
       let tempVar = res.data.results[0] ;
       setAnswer([...tempVar.incorrect_answers,tempVar.correct_answer].sort(()=>Math.random() - 0.5))
      setCorrect(tempVar.correct_answer)
      console.log(res.data)
      console.log(answer)

    })
    .catch(err=>{
      console.log(err);
    })
  },[])

  const  handleClick = (e) =>{
    setDisabled(true)
    if(disabled && e.target.innerText === correct){

      setPoints(points + 1)
      setTurns(turns + 1)
      e.target.style.background = 'green'
      setTimeout(() => e.target.style.background = '', 2000);

      setTimeout(() => {
        axios.get('https://opentdb.com/api.php?amount=10')
        .then(res=>{
           setQuiz(res.data.results[0])
           let tempVar = res.data.results[0] ;
           setAnswer([...tempVar.incorrect_answers,tempVar.correct_answer].sort(()=>Math.random() - 0.5))
          setCorrect(tempVar.correct_answer)
      })
      .catch(err=>{
        console.log(err);
      })
    }, 2000);
    console.log(points)
    } else if(e.target.innerText !== correct){
      setTurns(turns + 1)
      e.target.style.background = 'red'
     setTimeout(() => e.target.style.background='', 2000);

      setTimeout(() => {
        axios.get('https://opentdb.com/api.php?amount=10')
        .then(res=>{
           setQuiz(res.data.results[0])
           let tempVar = res.data.results[0] ;
           setAnswer([...tempVar.incorrect_answers,tempVar.correct_answer].sort(()=>Math.random() - 0.5))
          setCorrect(tempVar.correct_answer)
      })
      .catch(err=>{
        console.log(err);
      })
    }, 2000);
    }
    }

if(points >= 10|| turns >= 10){
  return (
    <div className='score'>
      <h1>Well done !</h1>
     <p>Your Score: {points}</p>
      <button className='button-28' onClick={refreshPage}>New Test</button>
    </div>
  )
}

  return (
    <div className="App">
     <div className='grid'>
   <h1>{quiz.question}</h1>
   { answer?.map(answers =>
   <button className='button-28' onClick={handleClick}key={answers}>{answers}</button>
   )
   }

    </div>
    </div>

  );
}

export default App;
</code>```

答:
try like this:</p>
```<code>const [loading, setLoading] = useState(false)

const getDate = async () => {
   setLoading(true)
   const data = await axios.get('/teste')
   ...
   setLoading(false)
}

<button disabled={loading}>Teste</button>
</code>```

Body:
i have simple quizz project where i fetch data of questions and answers my problem is when i click on one of the answers i want other buttons to be disabled because if someone keeps pressing on other options the quiz will rapidly change questions. i want to disable other answer options when i clik on the  answer and then after the next question generates enable them again and so on

import './App.css';
import axios from 'axios'
import {useState,useEffect} from 'react'

function App() {
  const [quiz,setQuiz] = useState([])
  const [answer,setAnswer] = useState([])
  const [correct,setCorrect] =useState('')
  const [points,setPoints] = useState(0)
  const [turns,setTurns] = useState(0)
  const [disabled,setDisabled] = useState(false)

  function refreshPage() {
    window.location.reload(false);
  }

  useEffect(()=>{
    axios.get('https://opentdb.com/api.php?amount=10')
    .then(res =>{
       setQuiz(res.data.results[0])
       let tempVar = res.data.results[0] ;
       setAnswer([...tempVar.incorrect_answers,tempVar.correct_answer].sort(()=>Math.random() - 0.5))
      setCorrect(tempVar.correct_answer)
      console.log(res.data)
      console.log(answer)

    })
    .catch(err=>{
      console.log(err);
    })
  },[])

  const  handleClick = (e) =>{
    setDisabled(true)
    if(disabled && e.target.innerText === correct){

      setPoints(points + 1)
      setTurns(turns + 1)
      e.target.style.background = 'green'
      setTimeout(() => e.target.style.background = '', 2000);

      setTimeout(() => {
        axios.get('https://opentdb.com/api.php?amount=10')
        .then(res=>{
           setQuiz(res.data.results[0])
           let tempVar = res.data.results[0] ;
           setAnswer([...tempVar.incorrect_answers,tempVar.correct_answer].sort(()=>Math.random() - 0.5))
          setCorrect(tempVar.correct_answer)
      })
      .catch(err=>{
        console.log(err);
      })
    }, 2000);
    console.log(points)
    } else if(e.target.innerText !== correct){
      setTurns(turns + 1)
      e.target.style.background = 'red'
     setTimeout(() => e.target.style.background='', 2000);

      setTimeout(() => {
        axios.get('https://opentdb.com/api.php?amount=10')
        .then(res=>{
           setQuiz(res.data.results[0])
           let tempVar = res.data.results[0] ;
           setAnswer([...tempVar.incorrect_answers,tempVar.correct_answer].sort(()=>Math.random() - 0.5))
          setCorrect(tempVar.correct_answer)
      })
      .catch(err=>{
        console.log(err);
      })
    }, 2000);
    }
    }

if(points >= 10|| turns >= 10){
  return (

Well done !

Your Score: {points}

      <button className='button-28' onClick={refreshPage}>New Test</button>

  )
}

  return (

{quiz.question}

   { answer?.map(answers =>
   <button className='button-28' onClick={handleClick}key={answers}>{answers}</button>
   )
   }

  );
}

export default App;

Body:
try like this:

const [loading, setLoading] = useState(false)

const getDate = async () => {
   setLoading(true)
   const data = await axios.get('/teste')
   ...
   setLoading(false)
}

<button disabled={loading}>Teste</button>


问:
Getting "405: method not allowed" error while pinging to Jfrog Artifactory in Jfrog CLI
I have Installed Jfrog CLI (2.12.0) and configured it by using jf config addcommand.

After passing the platform URL, username and password I executed  jf rt ping to check the connection.

But am getting the below error as a response

```<code>[root@osc-in-bldslave-1 opt]# jf rt ping
19:13:51 [Error] Server response: 405 Method Not Allowed
{
  "errors": [
    {
      "status": 405,
      "message": "Method Not Allowed"
    }
  ]
}
</code>```

Please let me know if you need any other details.

Below are the Steps I followed while Jfrog CLI configuration. Correct me if there is any issues with configuration.

```<code>[root@osc-in-bldslave-1 ~]# jf -version
jf version 2.12.0
[root@osc-in-bldslave-1 ~]#
[root@osc-in-bldslave-1 ~]# jf config add
Choose a server ID : <server id>
JFrog platform URL [http://xxx.xx.xxx.xx:8081/]: http://xxx.xx.xxx.xx:8081/
JFrog access token (Leave blank for username and password/API key):
JFrog username [username]: <username>
JFrog password or API key:<passing password here>
Is the Artifactory reverse proxy configured to accept a client certificate? (y/n) [n]? n
[root@osc-in-bldslave-1 ~]#
[root@osc-in-bldslave-1 ~]# jf rt ping
09:55:13 [Error] Server response: 405 Method Not Allowed
{
  "errors": [
    {
      "status": 405,
      "message": "Method Not Allowed"
    }
  ]
}
[root@osc-in-bldslave-1 ~]#
</code>```

But if it try pinging to my URL directly using below command it is working fine.

```<code>[root@osc-in-bldslave-1 ~]# jf rt ping --url=http://172.xx.xxx.xx:8081/artifactory/
OK
</code>```

I deleted and installed Jfrog CLI freshly, still am facing the same 405: method not allowed issue.

Can anyone please let me know what am missing?

答:
Looks like while configuring the JFrog CLI some of the parameters are incorrect, due to which the error is thrown. Same was tested in my env and its workings as expected.

➜  jf -version jf version 2.12.0

➜ jf rt ping OK

Body:
I have Installed Jfrog CLI (2.12.0) and configured it by using jf config addcommand.

After passing the platform URL, username and password I executed  jf rt ping to check the connection.

But am getting the below error as a response

[root@osc-in-bldslave-1 opt]# jf rt ping
19:13:51 [Error] Server response: 405 Method Not Allowed
{
  "errors": [
    {
      "status": 405,
      "message": "Method Not Allowed"
    }
  ]
}

Please let me know if you need any other details.

Below are the Steps I followed while Jfrog CLI configuration. Correct me if there is any issues with configuration.

[root@osc-in-bldslave-1 ~]# jf -version
jf version 2.12.0
[root@osc-in-bldslave-1 ~]#
[root@osc-in-bldslave-1 ~]# jf config add
Choose a server ID : <server id>
JFrog platform URL [http://xxx.xx.xxx.xx:8081/]: http://xxx.xx.xxx.xx:8081/
JFrog access token (Leave blank for username and password/API key):
JFrog username [username]: <username>
JFrog password or API key:<passing password here>
Is the Artifactory reverse proxy configured to accept a client certificate? (y/n) [n]? n
[root@osc-in-bldslave-1 ~]#
[root@osc-in-bldslave-1 ~]# jf rt ping
09:55:13 [Error] Server response: 405 Method Not Allowed
{
  "errors": [
    {
      "status": 405,
      "message": "Method Not Allowed"
    }
  ]
}
[root@osc-in-bldslave-1 ~]#

But if it try pinging to my URL directly using below command it is working fine.

[root@osc-in-bldslave-1 ~]# jf rt ping --url=http://172.xx.xxx.xx:8081/artifactory/
OK

I deleted and installed Jfrog CLI freshly, still am facing the same 405: method not allowed issue.

Can anyone please let me know what am missing?


问:
I want to export the data saved in text views to the external storage of mobile and then can access the saved file from file manager
the code I used to show data in the text view from the database is
here
I tried Shared prefrences too but the app crashes when I execute it.
I want to export the data in txt file in the external storage.
Which method do I have to use to complete this action.

```<code>public class Export2 extends AppCompatActivity {
ImageView back;
Button button;
TextView tv,tv2,tv3;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_export2);
    initview();
    initListener();

}
</code>```

Defining the objects

```<code>public void initview(){
    tv = findViewById(R.id.details2);
    tv2 = findViewById(R.id.babydetails2);
    tv3 = findViewById(R.id.vac_result2);
    back = findViewById(R.id.back);
    button = findViewById(R.id.exportbtn);
}

public void initListener(){

    back.setOnClickListener(v -> Export2.super.onBackPressed());
}
</code>```

details I added to the textview through String Builder.

```<code>public void details(){

    DBase dBase = new DBase(this);
    DbaseBaby dbaseBaby = new DbaseBaby(this);
    VaccineDB2 vaccineDB2 = new VaccineDB2(this);

    Cursor cursor = dBase.getData();

    StringBuilder sb = new StringBuilder();

    while(cursor.moveToNext()){
        sb.append("\nMobile Number :" +cursor.getString(1) + "\nEmail : " +cursor.getString(2)
                + "\nMother's name : " +cursor.getString(3) + "\nFather's name : " +cursor.getString(4));
    }
    tv.setText(sb);

    Cursor c = dbaseBaby.getData();

    StringBuilder sb2 = new StringBuilder();

    while(c.moveToNext()){
        sb2.append(" \nBaby name : " + c.getString(1) + " \nBirthdate : "+ c.getString(2)
                + " \nGender : " + c.getString(3) + " \nAge group : " + c.getString(4));
    }
    tv2.setText(sb2);

    Cursor cu = vaccineDB2.getData();

    StringBuilder sBuilder = new StringBuilder();

    while (cu.moveToNext()){
        sBuilder.append("\nVaccine : "+cu.getString(1) + "\nVaccine : "+cu.getString(2)
                + "\nVaccine : "+cu.getString(3)  + "\nVaccine : "+cu.getString(4)  + "\nVaccine : "+cu.getString(5)
                + "\nVaccine : "+cu.getString(6)  + "\nVaccine : "+cu.getString(7)  + "\nVaccine : "+cu.getString(8)
                + "\nVaccine : "+cu.getString(9)  + "\nVaccine : "+cu.getString(10));
    }
    tv3.setText(sBuilder);
}
</code>```

}

答:
You can use this code:

```<code>public void saveInTxt() throws IOException {
    String txt1 = tv.getText().toString();
    String txt2 = tv2.getText().toString();
    String txt3 = tv3.getText().toString();
    File f = new File("YOUR PATH");
    FileWriter fw = new FileWriter(f);

    fw.write(txt1);
    fw.write("\n");
    fw.write(txt2);
    fw.write("\n");
    fw.write(txt3);
    fw.write("\n");
    fw.flush();
    fw.close();
}
</code>```

Note: You will need to ask for write permission.

Body:
the code I used to show data in the text view from the database is
here
I tried Shared prefrences too but the app crashes when I execute it.
I want to export the data in txt file in the external storage.
Which method do I have to use to complete this action.

public class Export2 extends AppCompatActivity {
ImageView back;
Button button;
TextView tv,tv2,tv3;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_export2);
    initview();
    initListener();

}

Defining the objects

public void initview(){
    tv = findViewById(R.id.details2);
    tv2 = findViewById(R.id.babydetails2);
    tv3 = findViewById(R.id.vac_result2);
    back = findViewById(R.id.back);
    button = findViewById(R.id.exportbtn);
}

public void initListener(){

    back.setOnClickListener(v -> Export2.super.onBackPressed());
}

details I added to the textview through String Builder.

public void details(){

    DBase dBase = new DBase(this);
    DbaseBaby dbaseBaby = new DbaseBaby(this);
    VaccineDB2 vaccineDB2 = new VaccineDB2(this);

    Cursor cursor = dBase.getData();

    StringBuilder sb = new StringBuilder();

    while(cursor.moveToNext()){
        sb.append("\nMobile Number :" +cursor.getString(1) + "\nEmail : " +cursor.getString(2)
                + "\nMother's name : " +cursor.getString(3) + "\nFather's name : " +cursor.getString(4));
    }
    tv.setText(sb);

    Cursor c = dbaseBaby.getData();

    StringBuilder sb2 = new StringBuilder();

    while(c.moveToNext()){
        sb2.append(" \nBaby name : " + c.getString(1) + " \nBirthdate : "+ c.getString(2)
                + " \nGender : " + c.getString(3) + " \nAge group : " + c.getString(4));
    }
    tv2.setText(sb2);

    Cursor cu = vaccineDB2.getData();

    StringBuilder sBuilder = new StringBuilder();

    while (cu.moveToNext()){
        sBuilder.append("\nVaccine : "+cu.getString(1) + "\nVaccine : "+cu.getString(2)
                + "\nVaccine : "+cu.getString(3)  + "\nVaccine : "+cu.getString(4)  + "\nVaccine : "+cu.getString(5)
                + "\nVaccine : "+cu.getString(6)  + "\nVaccine : "+cu.getString(7)  + "\nVaccine : "+cu.getString(8)
                + "\nVaccine : "+cu.getString(9)  + "\nVaccine : "+cu.getString(10));
    }
    tv3.setText(sBuilder);
}

}

Body:
You can use this code:

public void saveInTxt() throws IOException {
    String txt1 = tv.getText().toString();
    String txt2 = tv2.getText().toString();
    String txt3 = tv3.getText().toString();
    File f = new File("YOUR PATH");
    FileWriter fw = new FileWriter(f);

    fw.write(txt1);
    fw.write("\n");
    fw.write(txt2);
    fw.write("\n");
    fw.write(txt3);
    fw.write("\n");
    fw.flush();
    fw.close();
}

Note: You will need to ask for write permission.


问:
How to make a widget maximum size be equal to the flex value in a row
I have this small code:

Container(
  color: Colors.blue,
  child: Row(
    children: [
      Expanded(
        child: Container(
          color: Colors.red,
          child: const Text('Red text that can be long long long long long'),
        ),
      ),
      Flexible(
        child: Container(
          color: Colors.green,
          child: const Text('Small text'),
        ),
      ),
    ],
  ),
),
```
<p>which renders into this:</p>
<p><img src="https://i.stack.imgur.com/ZP2wy.png" alt="enter image description here" /></p>
<p>Notice how the long text is wrapped even though there is still space around the small text.</p>
<p>I would like the small text to only take the size it needs to let the long text take the rest. And if the small text becomes bigger, its maximum size would be the size of the <code>Flexible</code> widget in the row (half of the <code>Row</code> in my example since both <code>Expanded</code> and <code>Flexible</code> have <code>flex: 1</code>).</p>
<p>If the small text is small enough, it should look like:</p>
```| Red text that can be long long long long | Small text |
| long                                     |            |
```
<p>And if the "small" text is long too:</p>
```| Red text that can be long | Small text that is also  |
| long long long long       | very long                |
```

Is there a way to do that?

答:
You can use ConstrainedBox:constraints: BoxConstraints.loose( Size.fromWidth(maxWidth / 2) for green.

body:LayoutBuilder(
  builder: (context, constraints) => Row(
    children: [
      Expanded(
        child: Container(
          color: Colors.red,
          child: const Text(
              'Red text that can be long long long lbe long long long lbe long long long long long'),
        ),
      ),
      ConstrainedBox(
        constraints: BoxConstraints.loose(
            Size.fromWidth(constraints.maxWidth / 2)),
        child: Container(
          color: Colors.green,
          child: const Text('Smalled g long th xt'),
        ),
      ),
    ],
  ),
),
```

Body:
I have this small code:

Container(
  color: Colors.blue,
  child: Row(
    children: [
      Expanded(
        child: Container(
          color: Colors.red,
          child: const Text('Red text that can be long long long long long'),
        ),
      ),
      Flexible(
        child: Container(
          color: Colors.green,
          child: const Text('Small text'),
        ),
      ),
    ],
  ),
),

which renders into this:

Notice how the long text is wrapped even though there is still space around the small text.

I would like the small text to only take the size it needs to let the long text take the rest. And if the small text becomes bigger, its maximum size would be the size of the Flexible widget in the row (half of the Row in my example since both Expanded and Flexible have flex: 1).

If the small text is small enough, it should look like:

| Red text that can be long long long long | Small text |
| long                                     |            |

And if the "small" text is long too:

| Red text that can be long | Small text that is also  |
| long long long long       | very long                |

Is there a way to do that?


问:
Perforce Stream Graph missing changes to child stream (red arrow to parent)
in Perforce I go to the Stream Graph every morning to bring updates from parent stream to my feature stream. I always see a red arrow going from my feature stream to the parent. This marks that there are changes in my stream that the parent is missing, so that's normal.
Today that red arrow is gone and in history I can't see anyone merging my branch to the parent (And no one would have any reason to do so since the feature just started development and had some minor changes merged with no actual functionality yet)
I closed Perforce and re-opened it but the arrow is still gone, I fear I messed something up somehow.

Any ideas/suggestions/things I can check?

答:
The hypothesis is that there is a change in your feature branch which has not been merged to the parent but which is not being shown in the stream graph.  Let's look at some of the tools we have in Perforce to prove or disprove this hypothesis.

The very easiest thing to check is: what happens if you do a merge from the feature stream to the parent?  Run a merge in "preview" mode -- does it say that there are files to merge?  If so, then we know that merge is doing the expected thing, but the stream graph is out of date with it.  This could be the result of the stream having been edited recently in a way that temporarily invalidated the cached merge status (see this article for more discussion).

Let's suppose that merge agrees with the stream graph.  The next tool is to make your hypothesis more specific: identify a particular changelist that should require merging.  The most recent changelist on your feature branch should be a good candidate.  Open one of the files in that changelist in Revision Graph, and look for arrows between it and the parent stream.  Is there:

any kind of arrow from that revision back to the parent stream?

a "copy" arrow from the parent stream overwriting that revision?

either of the above but indirectly via some other stream?

If there's none of the above, and the file still doesn't require a merge, check the stream definitions.  Is that file in a share path, or is it isolated from the parent?  Are the options set to globally block or allow merges from this stream to the parent?


问:
Filtering in join in supabase
Im using supabase with a database which have 2 tables (that are implicates in this issue).
Tables are teachers and users. Both have ID and id_teacher/id_user respectively.
Im working in a query where i need to get all teacher, joining in users table, where theres a image column.
I need just to get the teachers where the user have an not null image.

```<code>    const query = supabase.from(`teachers`).select(
      `
        *,
        id_user(
          image
        )
      `
    )
</code>```

This query works to get teachers joining in users table. Because i get my wanted response.
This is a short example.

```<code>{
    "id": 560,
    "teacher_experience": 9,
    "id_user":{
        "image": "example-image.jpg"
    }
}
</code>```

The trouble is when i try to use some filter to avoid null images.

```<code>query.not('id_user.image', 'eq', null)
query.not('id_user.image', 'in', null)
query.ilike('id_user.image', 'null')
</code>```

Are just an examples o filters tha i tryed for avoid the teachers which user.image have a null value.
Because, i want to NOT GET the entire item, but i get an item wiht a id_user = null

```<code>{
    "id": 560,
    "teacher_experience": 9,
    "id_user": null          // In this case image is null but still giving me the user
}
</code>```

How is the correct form to solve this?

答:
This feature came up recently with the release of the support for PostgREST 9. You have to use !inner keyword, you can now filter rows of the top-level table.

```<code>   const query = supabase.from(`teachers`).select(
      `
        *,
        id_user!inner(image)
      `
    ).not("id_users.image", "is", "NULL")
</code>```

Title: Filtering in join in supabase

Body:
Im using supabase with a database which have 2 tables (that are implicates in this issue).
Tables are teachers and users. Both have ID and id_teacher/id_user respectively.
Im working in a query where i need to get all teacher, joining in users table, where theres a image column.
I need just to get the teachers where the user have an not null image.

    const query = supabase.from(`teachers`).select(
      `
        *,
        id_user(
          image
        )
      `
    )

This query works to get teachers joining in users table. Because i get my wanted response.
This is a short example.

{
    "id": 560,
    "teacher_experience": 9,
    "id_user":{
        "image": "example-image.jpg"
    }
}

The trouble is when i try to use some filter to avoid null images.

query.not('id_user.image', 'eq', null)
query.not('id_user.image', 'in', null)
query.ilike('id_user.image', 'null')

Are just an examples o filters tha i tryed for avoid the teachers which user.image have a null value.
Because, i want to NOT GET the entire item, but i get an item wiht a id_user = null

{
    "id": 560,
    "teacher_experience": 9,
    "id_user": null          // In this case image is null but still giving me the user
}

How is the correct form to solve this?

Body:
This feature came up recently with the release of the support for PostgREST 9. You have to use !inner keyword, you can now filter rows of the top-level table.

   const query = supabase.from(`teachers`).select(
      `
        *,
        id_user!inner(image)
      `
    ).not("id_users.image", "is", "NULL")


问:
docker pull ignores http_proxy and https_proxy environment variables?
It looks like docker pull <image> ignore the http_proxy and https_proxy environment variables. I want to intercept the communication in order to better understand which HTTP requests docker pull performs - is there a way to look at them?

I'm executing docker pull on Ubuntu 18.

答:
at least in my case the solution above didn't work for me as my environment was controlling docker with systemd

In summary:

Create a file named /etc/systemd/system/docker.service.d/http-proxy.conf

Populate the file. Sample:

[Service]
Environment="HTTP_PROXY=http://proxy.example.com:80"
Environment="HTTPS_PROXY=https://proxy.example.com:443"
Environment="NO_PROXY=localhost,127.0.0.1,docker-registry.example.com,.corp"

sudo systemctl daemon-reload and sudo systemctl restart docker

Proxy specific information: https://docs.docker.com/config/daemon/systemd/#httphttps-proxy


问:
add a single data to serializer in django

I'm writing an API where the user's followers are listed.I also want to send the total number of followers in this API.But the totalFollower field keeps repeating.I only want it sent once. Like that:

```<code>[
totalFollower:2
followers:
{
    {
        "following": "gizli_takip",
    },
    {
        "following": "herkeseacikvetakip",
    }
}]
</code>```

MY serializer

```<code>class SerializerUserFollowings(serializers.ModelSerializer):
following = serializers.CharField(source="follower.username")

totalFollower = serializers.ReadOnlyField()
class Meta:
    model  = ModelFollower
    fields = ("following","totalFollower")
</code>```

答:
You have a couple of options:

Use a DRF paginator on your view, which will give a count in the response body:

```<code>from rest_framework.pagination import PageNumberPagination

class YourView(...):
    pagination_class = PageNumberPagination
    ...
</code>```

Alternatively if you are using a viewset or something similar like ListAPIView you can add the specific data into the response for the list function:

```<code>class YourView(ListAPIView):

    def get_queryset(self):
        return <some query for filtering follows by user>

    def list(self, request, *args, **kwargs):
        response = super().list(request, args, kwargs)
        response.data["count"] = self.get_queryset().count()
        return response
</code>```

Body:
I'm writing an API where the user's followers are listed.I also want to send the total number of followers in this API.But the totalFollower field keeps repeating.I only want it sent once. Like that:

[
totalFollower:2
followers:
{
    {
        "following": "gizli_takip",
    },
    {
        "following": "herkeseacikvetakip",
    }
}]

MY serializer

class SerializerUserFollowings(serializers.ModelSerializer):
following = serializers.CharField(source="follower.username")

totalFollower = serializers.ReadOnlyField()
class Meta:
    model  = ModelFollower
    fields = ("following","totalFollower")

Body:
You have a couple of options:

Use a DRF paginator on your view, which will give a count in the response body:

from rest_framework.pagination import PageNumberPagination

class YourView(...):
    pagination_class = PageNumberPagination
    ...

Alternatively if you are using a viewset or something similar like ListAPIView you can add the specific data into the response for the list function:

class YourView(ListAPIView):

    def get_queryset(self):
        return <some query for filtering follows by user>

    def list(self, request, *args, **kwargs):
        response = super().list(request, args, kwargs)
        response.data["count"] = self.get_queryset().count()
        return response


问:
How to get the part of a file after the first line that matches a regular expression
I have a file with about 1000 lines. I want the part of my file after the line which matches my grep statement.

That is:

```<code>cat file | grep 'TERMINATE'     # It is found on line 534
</code>```

So, I want the file from line 535 to line 1000 for further processing.

How can I do that?

答:
As a simple approximation you could use

```<code>grep -A100000 TERMINATE file
</code>```

which greps for TERMINATE and outputs up to 100,000 lines following that line.

From the man page:

-A NUM, --after-context=NUM

Print  NUM  lines  of  trailing  context  after  matching lines.
Places  a  line  containing  a  group  separator  (--)   between
contiguous  groups  of  matches.  With the -o or --only-matching
option, this has no effect and a warning is given.

Body:
I have a file with about 1000 lines. I want the part of my file after the line which matches my grep statement.

That is:

cat file | grep 'TERMINATE'     # It is found on line 534

So, I want the file from line 535 to line 1000 for further processing.

How can I do that?

Body:
As a simple approximation you could use

grep -A100000 TERMINATE file

which greps for TERMINATE and outputs up to 100,000 lines following that line.

From the man page:

-A NUM, --after-context=NUM

Print  NUM  lines  of  trailing  context  after  matching lines.
Places  a  line  containing  a  group  separator  (--)   between
contiguous  groups  of  matches.  With the -o or --only-matching
option, this has no effect and a warning is given.