问:
sending the value from jsp to java or javascript to java
I have a list of names in a table. When I click the name, it displays people under that particular name.
Ex:

```<code>aaa       bbb
          ccc
</code>```

Now I want to do moveover on aaa which l show 2 (number of ppl under aaa) in a tooltip.

```<code><a id="tool" title="toolTip" onmouseover="toolTip(localArrGroupNames[<%=in.intValue() %>])">

function toolTip(name){
  alert(name);
  //can I send this name to a java class ???

}
</code>```

I get the name aaa in the localArrGroupNames[0].But I am unable to get the name in a java class where i count the number of people below the aaa. How to send this value to java class? Please help me.

答:
you need to submit a request to the server you can do this using ajax to perform asynchronously, or you could submit using a form in the jsp page.

You will of course need to supply the correct url (either form action, or ajax connection url), and have the appropriate servlet running on server.

If doing ajax, most people use jquery and/or DWR

Body:
I have a list of names in a table. When I click the name, it displays people under that particular name.
Ex:

aaa       bbb
          ccc

Now I want to do moveover on aaa which l show 2 (number of ppl under aaa) in a tooltip.

<a id="tool" title="toolTip" onmouseover="toolTip(localArrGroupNames[<%=in.intValue() %>])">

function toolTip(name){
  alert(name);
  //can I send this name to a java class ???

}

I get the name aaa in the localArrGroupNames[0].But I am unable to get the name in a java class where i count the number of people below the aaa. How to send this value to java class? Please help me.


来源: 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.

答:
If I understand correctly, you are looking for OUTER JOIN, INNER JOIN will return rows that match between all conditions on two tables.

For this below query RIGHT JOIN will return rows based on [dbo].[grtbk] even conditions didn't match, But rows will be NULL
when the row didn't match by the conditions GB.bdr_val, so we need to use ISNULL in the aggregate function.

```<code>SELECT
    SUM(ISNULL(GB.bdr_val,0)) AS Total_Material_M,
    GR.oms25_0 AS Desc2,
    GR.reknr AS Account
FROM
    [dbo].[gbkmut] GB
RIGHT JOIN
    [dbo].[grtbk] GR ON GB.reknr = GR.reknr
    AND GB.bkjrcode = 2021
    AND GB.periode = 11
GROUP BY
    GR.oms25_0, GR.reknr
ORDER BY
    GR.reknr ASC
</code>```

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:
If I understand correctly, you are looking for OUTER JOIN, INNER JOIN will return rows that match between all conditions on two tables.

For this below query RIGHT JOIN will return rows based on [dbo].[grtbk] even conditions didn't match, But rows will be NULL
when the row didn't match by the conditions GB.bdr_val, so we need to use ISNULL in the aggregate function.

SELECT
    SUM(ISNULL(GB.bdr_val,0)) AS Total_Material_M,
    GR.oms25_0 AS Desc2,
    GR.reknr AS Account
FROM
    [dbo].[gbkmut] GB
RIGHT JOIN
    [dbo].[grtbk] GR ON GB.reknr = GR.reknr
    AND GB.bkjrcode = 2021
    AND GB.periode = 11
GROUP BY
    GR.oms25_0, GR.reknr
ORDER BY
    GR.reknr ASC


问:
Getting full name of the OS using Ansible facts
I used gather_facts to get the OS details of each instance that I'm dealing with. For Amazon Linux OS, it just says Amazon 2 or Amazon 2018.

Use case: I'm dynamically constructing the file name for a task. The file name is nothing but the name of the OS. When I see the contents of /etc/os-release, it says Amazon Linux only but Ansible facts returns:

"ansible_facts": {
    "discovered_interpreter_python": "/usr/bin/python2.7",
    "distribution": "Amazon",
    "distribution_file_parsed": true,
    "distribution_file_path": "/etc/os-release",
    "distribution_file_variety": "Amazon",
    "distribution_major_version": "2",
    "distribution_minor_version": "NA",
    "distribution_release": "NA",
    "distribution_version": "2",
    "gather_subset": [
        "distribution",
        "!all",
        "!min"
    ],
    "module_setup": true,
    "os_family": "RedHat",
}
```

Is there a way to get the full name of the distribution? I personally feel Amazon 2 doesn't set the proper context.

答:
A RHEL system

```<code>cat /etc/redhat-release
Red Hat Enterprise Linux Server release 7.9 (Maipo)
</code>```

will report as follow

    distribution: RedHat
    distribution_file_parsed: true
    distribution_file_path: /etc/redhat-release
    distribution_file_search_string: Red Hat
    distribution_file_variety: RedHat
    distribution_major_version: '7'
    distribution_release: Maipo
    distribution_version: '7.9'
    gather_subset:
    - distribution
    - '!all'
    - '!min'
    module_setup: true
    os_family: RedHat
```
<blockquote>
<p><em>I expect the name to be returned as specified in os-release file</em></p>
</blockquote>
<p>Which could be than used for</p>
<pre class="lang-yaml prettyprint-override"><code>"{{ distribution_file_search_string }} Linux {{ distribution_version }} ({{ distribution_release }})"
</code>```

So it is almost the case. Furthermore you can have your own set_fact parts

- name: Set OS facts
  set_fact:
    NAME: "{{ distribution }} Linux"
    VERSION: "{{ distribution_major_version }}"
    VERSION_ID: "{{ distribution_version }}"
    PRETTY_NAME: "{{ distribution }} Linux {{ distribution_version }}"

- name: Set OS facts
  set_fact:
    ID: "amzn"
    ID_LIKE: "centos rhel fedora"
  when:  (ansible_facts['distribution'] == "Amazon" and ansible_facts['distribution_major_version'] == "2")
```

with Conditionals.

If really necessary one could enhance or extend the module facts/system/distribution.py.

Body:
I used gather_facts to get the OS details of each instance that I'm dealing with. For Amazon Linux OS, it just says Amazon 2 or Amazon 2018.

Use case: I'm dynamically constructing the file name for a task. The file name is nothing but the name of the OS. When I see the contents of /etc/os-release, it says Amazon Linux only but Ansible facts returns:

"ansible_facts": {
    "discovered_interpreter_python": "/usr/bin/python2.7",
    "distribution": "Amazon",
    "distribution_file_parsed": true,
    "distribution_file_path": "/etc/os-release",
    "distribution_file_variety": "Amazon",
    "distribution_major_version": "2",
    "distribution_minor_version": "NA",
    "distribution_release": "NA",
    "distribution_version": "2",
    "gather_subset": [
        "distribution",
        "!all",
        "!min"
    ],
    "module_setup": true,
    "os_family": "RedHat",
}

Is there a way to get the full name of the distribution? I personally feel Amazon 2 doesn't set the proper context.

Body:
A RHEL system

cat /etc/redhat-release
Red Hat Enterprise Linux Server release 7.9 (Maipo)

will report as follow

    distribution: RedHat
    distribution_file_parsed: true
    distribution_file_path: /etc/redhat-release
    distribution_file_search_string: Red Hat
    distribution_file_variety: RedHat
    distribution_major_version: '7'
    distribution_release: Maipo
    distribution_version: '7.9'
    gather_subset:
    - distribution
    - '!all'
    - '!min'
    module_setup: true
    os_family: RedHat

I expect the name to be returned as specified in os-release file

Which could be than used for

"{{ distribution_file_search_string }} Linux {{ distribution_version }} ({{ distribution_release }})"

So it is almost the case. Furthermore you can have your own set_fact parts

- name: Set OS facts
  set_fact:
    NAME: "{{ distribution }} Linux"
    VERSION: "{{ distribution_major_version }}"
    VERSION_ID: "{{ distribution_version }}"
    PRETTY_NAME: "{{ distribution }} Linux {{ distribution_version }}"

- name: Set OS facts
  set_fact:
    ID: "amzn"
    ID_LIKE: "centos rhel fedora"
  when:  (ansible_facts['distribution'] == "Amazon" and ansible_facts['distribution_major_version'] == "2")

with Conditionals.

If really necessary one could enhance or extend the module facts/system/distribution.py.


问:
Playwright for Python: Leaving Tabs and Browser Windows Open After Testing
Open a new tab manually on a browser open by Playwright

I am using Playwright for Python to open a browser, visit a URL and then do some action.

Can I keep the browser's window open after my code runs?

If I put a breakpoint in my Python code, I can not open a new tab in the browser open by Playwright: the page stays blank. What can I do to keep that tab open?

My code:

from playwright.sync_api import sync_playwright

playwright = sync_playwright().start()
browser = playwright.chromium.launch(headless=False)
context = browser.new_context()
auth_page = context.new_page()
auth_page.goto("https://www.toto.fr/")
print('Put breakpoint here')
```

答:
Replace your breakpoint by auth_page.pause()

You can learn more about the api page.pause() here.


问:
Invalid instantiation exception when pass dynamic object to custom interpolated string handler in .NET 6
I found an issue upgrading to the .NET 6 LogErrorInterpolatedStringHandler in my logger method.

Here is the classic method:

```<code>public static void Log(string message, params object[] pars)
{
    // Log message
}
</code>```

and here is the upgraded one:

```<code>public static void Log(ref LogErrorInterpolatedStringHandler message, params object[] pars)
{
    // Log message
}
</code>```

I upgraded the method in order to get the performance improvements of C# 10 and .NET 6 described here.

The new version of the method works well except when passing dynamic object in the interpolated string.

Here is an example:

```<code>// Works well
Logger.Log($"Log: {stringOrEverythingElseObject}");

// Exception
Logger.Log($"Log: {dynamicObject}");
</code>```

The exception thrown is

The generic type '<>A{00000004}`3' was used with an invalid instantiation in assembly 'MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.

I found a pull request similar to my problem but could not understand how to fix in my code.

Do you have any idea?
Thanks!

答:
TL;DR

There is not much you can do except casting dynamicObject to object at the call site:

```<code>Logger.Log($"Log: {(object)dynamicObject}");
</code>```

or removing ref from the handler:

```<code>[InterpolatedStringHandler]
public struct LogErrorInterpolatedStringHandler
</code>```

But not sure how it will affect performance (though using dynamic should have much more effect on performance than this, in general you should avoid dynamic in performance sensitive code)

Attempt to explain

ref structs do not work with dynamic very well due to the following limitation:

A ref struct can't be a type argument.

While code handling the dynamic uses the related types as type parameters. I.e. the following code:

var handler = new Handler();
handler.AppendFormatted((dynamic)5);

ref struct Handler
{
    // or public void AppendFormatted<T>(T value) { }
    public void AppendFormatted(object value) { }
}
```
<p>Will result in something like this generated by compiler:</p>
```private static class <>o__0
{
    public static CallSite<<>A{00000002}<CallSite, Handler, object>> <>p__0;
}
```

Note the Handler in the list of type parameters which will lead to the exactly the same runtime error. Removing ref from the handler fixes the issue.

As noted in comments in this test and this comment by Stephen Toub currently Roslyn does not emit any build time errors for this code while it fails in runtime.

Body:
I found an issue upgrading to the .NET 6 LogErrorInterpolatedStringHandler in my logger method.

Here is the classic method:

public static void Log(string message, params object[] pars)
{
    // Log message
}

and here is the upgraded one:

public static void Log(ref LogErrorInterpolatedStringHandler message, params object[] pars)
{
    // Log message
}

I upgraded the method in order to get the performance improvements of C# 10 and .NET 6 described here.

The new version of the method works well except when passing dynamic object in the interpolated string.

Here is an example:

// Works well
Logger.Log($"Log: {stringOrEverythingElseObject}");

// Exception
Logger.Log($"Log: {dynamicObject}");

The exception thrown is

The generic type '<>A{00000004}`3' was used with an invalid instantiation in assembly 'MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.

I found a pull request similar to my problem but could not understand how to fix in my code.

Do you have any idea?
Thanks!

Body:
TL;DR

There is not much you can do except casting dynamicObject to object at the call site:

Logger.Log($"Log: {(object)dynamicObject}");

or removing ref from the handler:

[InterpolatedStringHandler]
public struct LogErrorInterpolatedStringHandler

But not sure how it will affect performance (though using dynamic should have much more effect on performance than this, in general you should avoid dynamic in performance sensitive code)

Attempt to explain

ref structs do not work with dynamic very well due to the following limitation:

A ref struct can't be a type argument.

While code handling the dynamic uses the related types as type parameters. I.e. the following code:

var handler = new Handler();
handler.AppendFormatted((dynamic)5);

ref struct Handler
{
    // or public void AppendFormatted<T>(T value) { }
    public void AppendFormatted(object value) { }
}

Will result in something like this generated by compiler:

private static class <>o__0
{
    public static CallSite<<>A{00000002}<CallSite, Handler, object>> <>p__0;
}

Note the Handler in the list of type parameters which will lead to the exactly the same runtime error. Removing ref from the handler fixes the issue.

As noted in comments in this test and this comment by Stephen Toub currently Roslyn does not emit any build time errors for this code while it fails in runtime.


问:
Why does camel route give Failed to send reply with payload error after calling the Message Consumption Listener?
I have defined a camel route in my file route builder like this :

```<code>from("timer:first-timer") .bean(new MsgConsumptionListener(),"receiveMessage")
            .log(">>>> Body content is  ::::::::   ---> ${body}")
            .log(">>> Name is ::::::: ------> ${body.Name}")
            .setHeader("Name",method(MsgConsumptionListener.class))
            .to("log:first-timer");
</code>```

Inside the MsgConsumptionListener.java , I am consuming the message like this :

```<code>    @Async
    @JmsListener(destination = "MyQueue")
    public String receiveMessage(final Message jsonMessage) throws JMSException {
        String messageData = null;
        log.info("Message has been received----->" +jsonMessage);
        String rcvrName = null;
        if(jsonMessage instanceof TextMessage) {
            TextMessage textMessage = (TextMessage)jsonMessage;
            messageData = textMessage.getText();
            Map map = new Gson().fromJson(messageData, Map.class);
            rcvrName  = (String) map.get("Name");
            log.info("Receiver Name----->" +rcvrName);
        }
        return rcvrName;
    }
</code>```

I can see the message is getting consumed , but the camel route gives the below error when it calls the listener :

```<code>    c.f.i.listener.MsgConsumptionListener         : Message has been received----->ActiveMQTextMessage {commandId = 5, responseRequired = true, destination = queue://MyQueue, transactionId = null, expiration = 0, timestamp = 1644257093499, arrival = 0, brokerInTime = 1644257093500, brokerOutTime = 1644298154164, correlationId = null, replyTo = null, persistent = true, type = null, priority = 4, groupID = null, groupSequence = 0, targetConsumerId = null, compressed = false, userID = null, content = org.apache.activemq.util.ByteSequence@4d7cdcac, marshalledProperties = null, dataStructure = null, redeliveryCounter = 1, size = 0, properties = null, readOnlyProperties = true, readOnlyBody = true, droppable = false, jmsXGroupFirstForConsumer = false, text = {"Name":"Kunal"}}

    c.f.i.listener.MsgConsumptionListener         : Receiver Name----->Kunal
    [           main] o.a.c.impl.engine.AbstractCamelContext   : Routes startup summary (total:1 started:1)
    [           main] o.a.c.impl.engine.AbstractCamelContext   :     Started route1 (timer://first-timer)
    [           main] o.a.c.impl.engine.AbstractCamelContext   : Apache Camel 3.11.2 (camel-1) started in 724ms (build:72ms init:622ms start:30ms)
    o.s.j.l.DefaultMessageListenerContainer  : Execution of JMS message listener failed, and no ErrorHandler has been set.

    org.springframework.jms.listener.adapter.ReplyFailureException: Failed to send reply with payload [bp_exchange.in]; nested exception is javax.jms.InvalidDestinationException: Cannot determine response destination: Request message does not contain reply-to destination, and no default response destination set.
    [r://first-timer] c.f.i.listener.FileEventListener         : Message has been received----->null
    [r://first-timer] route1                                   : >>>
    [r://first-timer] c.f.i.listener.FileEventListener         : Message has been received----->null
    [r://first-timer] route1                                   : >>> The file Name set in the header is :
    [r://first-timer] c.f.i.listener.FileEventListener         : Message has been received----->null
</code>```

So the camel route is not able to get the message attribute Name and set it in the header .
Does anybody know as to what the issue is and what I should be doing to get the message attribute in the route ?

My objective is to use the file route builder to call my MsgConsumption listener and whenever a message is dropped in the queue , I want the route to trigger the listener , consume the message and get the attribute Name from the message to be used for further processing .

答:
I'm not a Spring JMS expert, but it appears you are mixing Spring JMS listener behavior with Camel route behavior in a way that won't work. If I understand your objective above, you want the route to pick up the queued message and process it. If that's true, I recommend not using Spring JMS listener and also remove the from(timer) in your route and change it to from(activemq) and take the logic in your current listener that examines the message and extracts the name and put that in a bean that the route calls. Like:</p>
```<code>from("activemq:myqueue")
.bean(GetTheNameBean)
.to("log:message")
</code>```

Body:
I have defined a camel route in my file route builder like this :

from("timer:first-timer") .bean(new MsgConsumptionListener(),"receiveMessage")
            .log(">>>> Body content is  ::::::::   ---> ${body}")
            .log(">>> Name is ::::::: ------> ${body.Name}")
            .setHeader("Name",method(MsgConsumptionListener.class))
            .to("log:first-timer");

Inside the MsgConsumptionListener.java , I am consuming the message like this :

    @Async
    @JmsListener(destination = "MyQueue")
    public String receiveMessage(final Message jsonMessage) throws JMSException {
        String messageData = null;
        log.info("Message has been received----->" +jsonMessage);
        String rcvrName = null;
        if(jsonMessage instanceof TextMessage) {
            TextMessage textMessage = (TextMessage)jsonMessage;
            messageData = textMessage.getText();
            Map map = new Gson().fromJson(messageData, Map.class);
            rcvrName  = (String) map.get("Name");
            log.info("Receiver Name----->" +rcvrName);
        }
        return rcvrName;
    }

I can see the message is getting consumed , but the camel route gives the below error when it calls the listener :

    c.f.i.listener.MsgConsumptionListener         : Message has been received----->ActiveMQTextMessage {commandId = 5, responseRequired = true, destination = queue://MyQueue, transactionId = null, expiration = 0, timestamp = 1644257093499, arrival = 0, brokerInTime = 1644257093500, brokerOutTime = 1644298154164, correlationId = null, replyTo = null, persistent = true, type = null, priority = 4, groupID = null, groupSequence = 0, targetConsumerId = null, compressed = false, userID = null, content = org.apache.activemq.util.ByteSequence@4d7cdcac, marshalledProperties = null, dataStructure = null, redeliveryCounter = 1, size = 0, properties = null, readOnlyProperties = true, readOnlyBody = true, droppable = false, jmsXGroupFirstForConsumer = false, text = {"Name":"Kunal"}}

    c.f.i.listener.MsgConsumptionListener         : Receiver Name----->Kunal
    [           main] o.a.c.impl.engine.AbstractCamelContext   : Routes startup summary (total:1 started:1)
    [           main] o.a.c.impl.engine.AbstractCamelContext   :     Started route1 (timer://first-timer)
    [           main] o.a.c.impl.engine.AbstractCamelContext   : Apache Camel 3.11.2 (camel-1) started in 724ms (build:72ms init:622ms start:30ms)
    o.s.j.l.DefaultMessageListenerContainer  : Execution of JMS message listener failed, and no ErrorHandler has been set.

    org.springframework.jms.listener.adapter.ReplyFailureException: Failed to send reply with payload [bp_exchange.in]; nested exception is javax.jms.InvalidDestinationException: Cannot determine response destination: Request message does not contain reply-to destination, and no default response destination set.
    [r://first-timer] c.f.i.listener.FileEventListener         : Message has been received----->null
    [r://first-timer] route1                                   : >>>
    [r://first-timer] c.f.i.listener.FileEventListener         : Message has been received----->null
    [r://first-timer] route1                                   : >>> The file Name set in the header is :
    [r://first-timer] c.f.i.listener.FileEventListener         : Message has been received----->null

So the camel route is not able to get the message attribute Name and set it in the header .
Does anybody know as to what the issue is and what I should be doing to get the message attribute in the route ?

My objective is to use the file route builder to call my MsgConsumption listener and whenever a message is dropped in the queue , I want the route to trigger the listener , consume the message and get the attribute Name from the message to be used for further processing .

Body:
I'm not a Spring JMS expert, but it appears you are mixing Spring JMS listener behavior with Camel route behavior in a way that won't work. If I understand your objective above, you want the route to pick up the queued message and process it. If that's true, I recommend not using Spring JMS listener and also remove the from(timer) in your route and change it to from(activemq) and take the logic in your current listener that examines the message and extracts the name and put that in a bean that the route calls. Like:

from("activemq:myqueue")
.bean(GetTheNameBean)
.to("log:message")


问:
How to handle the cllocationmanager and google api?
Iam developing one applciation.In that i use the google places api for getting the information about any location.ANd i used the cllocation manager for finding the specific location latitude and longitude values.And i pass that updated latitude and longitude values to that google api url in the cllocationmanager delegate method..After getting that values directly establish the connection with that url in the same cllocationmanager delegate menthod.it called every time and remaining nsurlconnection methods didn't give the result.So i want to get the updated location values at the first time and establish the connection and stop the location updated values process.So please tell me how to correct this one.Or is this right way or not for getting the current location details.Is there any other way for getting the current location details.</p>

答:
```<code>- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation
       fromLocation:(CLLocation *)oldLocation {

//After you enter in this method get the newLocation.
[locationManager stopUpadatingLocation];

}
</code>```

ContentLicense: CC BY-SA 3.0


问:
Replace external jar dependency with local intellij project
So I have an intellij IDEA project (project A) which includes a bunch of external jar libraries. I am currently working on one of those external jar libraries (project B) and I want to replace it with the local project (project B) on my computer.

So, in short:
I have Project A which depends on jar B
I want to replace jar B with my local project (project B)

That way, when I run project A, it uses Project B local rather than Jar B external. Anyone know any good easy ways of doing this?

答:
Solution with gradle:

In Project A build.gradle add mavenLocal() to the repositories.

```<code>...
repositories {
  mavenLocal()
  maven { url ... }
}
...
</code>```

In Project B you need the maven-publish plugin, and the related task.

```<code>plugins {
  id 'maven-publish'
}

sourceSets {
  main {
    java {
      srcDir 'src/main/java'
    }
  }
}

task sourcesJar(type: Jar) {
  from sourceSets.main.allJava
  classifier = 'sources'
}

publishing {
  publications {
    mavenJava(MavenPublication) {
      artifactId = rootProject.name //or some string eg.: 'projectb'
      groupId = project.group //or some string eg.: 'com.example'
      version = project.version //or some string eg.: '1.0.3.9'
      from components.java
      artifact sourcesJar
    }
  }
}
</code>```

Now you can run the publishToMavenLocal task from your terminal, or from Gradle View in IntelliJ. (It is on the right side by default, gradle tab, expand your project and bellow publishing you can find the task.)

Body:
Solution with gradle:

In Project A build.gradle add mavenLocal() to the repositories.

...
repositories {
  mavenLocal()
  maven { url ... }
}
...

In Project B you need the maven-publish plugin, and the related task.

plugins {
  id 'maven-publish'
}

sourceSets {
  main {
    java {
      srcDir 'src/main/java'
    }
  }
}

task sourcesJar(type: Jar) {
  from sourceSets.main.allJava
  classifier = 'sources'
}

publishing {
  publications {
    mavenJava(MavenPublication) {
      artifactId = rootProject.name //or some string eg.: 'projectb'
      groupId = project.group //or some string eg.: 'com.example'
      version = project.version //or some string eg.: '1.0.3.9'
      from components.java
      artifact sourcesJar
    }
  }
}

Now you can run the publishToMavenLocal task from your terminal, or from Gradle View in IntelliJ. (It is on the right side by default, gradle tab, expand your project and bellow publishing you can find the task.)


问:
Standard way to "clamp" a number between two values in Swift
Given:

```<code>let a = 4.2
let b = -1.3
let c = 6.4
</code>```

I want to know the simplest, Swiftiest way to clamp these values to a given range, say 0...5, such that:

```<code>a -> 4.2
b -> 0
c -> 5
</code>```

I know I can do the following:

```<code>let clamped = min(max(a, 0), 5)
</code>```

Or something like:

```<code>let clamped = (a < 0) ? 0 : ((a > 5) ? 5 : a)
</code>```

But I was wondering if there were any other ways to do this in Swift—in particular, I want to know (and document on SO, since there doesn't appear to be a question about clamping numbers in Swift) whether there is anything in the Swift standard library intended specifically for this purpose.

There may not be, and if so, that's also an answer I'll happily accept.

答:
Extending FixedWidthInteger and creating an instance generic method to accept a RangeExpression and taking care of the edge cases:

```<code>extension FixedWidthInteger {
    func clamped<R: RangeExpression>(with range: R) -> Self where R.Bound == Self {
        switch range {
        case let range as ClosedRange<Self>:
            return Swift.min(range.upperBound, Swift.max(range.lowerBound, self))
        case let range as PartialRangeFrom<Self>:
            return Swift.max(range.lowerBound, self)
        case let range as PartialRangeThrough<Self>:
            return Swift.min(range.upperBound, self)
        case let range as Range<Self>:
            return Swift.min(range.dropLast().upperBound, Swift.max(range.lowerBound, self))
        case let range as PartialRangeUpTo<Self>:
            return Swift.min(range.upperBound.advanced(by: -1), self)
        default: return self
        }
    }
}
</code>```

Playground testing:

```<code>100.clamped(with: 1...)     // 100
100.clamped(with: ..<100)   // 99
100.clamped(with: ...100)   // 100
100.clamped(with: 1..<100)  // 99
100.clamped(with: 1...100)  // 100

0.clamped(with: 1...)       // 1
0.clamped(with: ..<100)     // 0
0.clamped(with: ...100)     // 0
0.clamped(with: 1..<100)    // 1
0.clamped(with: 1...100)    // 1
</code>```

To achieve the same results with a FloatingPoint implementation you can use its nextDown property for the edge cases:

```<code>extension BinaryFloatingPoint {
    func clamped<R: RangeExpression>(with range: R) -> Self where R.Bound == Self {
        switch range {
        case let range as ClosedRange<Self>:
            return Swift.min(range.upperBound, Swift.max(range.lowerBound, self))
        case let range as PartialRangeFrom<Self>:
            return Swift.max(range.lowerBound, self)
        case let range as PartialRangeThrough<Self>:
            return Swift.min(range.upperBound, self)
        case let range as Range<Self>:
            return Swift.min(range.upperBound.nextDown, Swift.max(range.lowerBound, self))
        case let range as PartialRangeUpTo<Self>:
            return Swift.min(range.upperBound.nextDown, self)
        default: return self
        }
    }
}
</code>```

Playground testing:

```<code>let value = 100.0

value.clamped(with: 1...)     // 100
value.clamped(with: ..<100)   // 99.99999999999999
value.clamped(with: ...100)   // 100
value.clamped(with: 1..<100)  // 99.99999999999999
value.clamped(with: 1...100)  // 100
</code>```

Body:
Given:

let a = 4.2
let b = -1.3
let c = 6.4

I want to know the simplest, Swiftiest way to clamp these values to a given range, say 0...5, such that:

a -> 4.2
b -> 0
c -> 5

I know I can do the following:

let clamped = min(max(a, 0), 5)

Or something like:

let clamped = (a < 0) ? 0 : ((a > 5) ? 5 : a)

But I was wondering if there were any other ways to do this in Swift—in particular, I want to know (and document on SO, since there doesn't appear to be a question about clamping numbers in Swift) whether there is anything in the Swift standard library intended specifically for this purpose.

There may not be, and if so, that's also an answer I'll happily accept.

Body:
Extending FixedWidthInteger and creating an instance generic method to accept a RangeExpression and taking care of the edge cases:

extension FixedWidthInteger {
    func clamped<R: RangeExpression>(with range: R) -> Self where R.Bound == Self {
        switch range {
        case let range as ClosedRange<Self>:
            return Swift.min(range.upperBound, Swift.max(range.lowerBound, self))
        case let range as PartialRangeFrom<Self>:
            return Swift.max(range.lowerBound, self)
        case let range as PartialRangeThrough<Self>:
            return Swift.min(range.upperBound, self)
        case let range as Range<Self>:
            return Swift.min(range.dropLast().upperBound, Swift.max(range.lowerBound, self))
        case let range as PartialRangeUpTo<Self>:
            return Swift.min(range.upperBound.advanced(by: -1), self)
        default: return self
        }
    }
}

Playground testing:

100.clamped(with: 1...)     // 100
100.clamped(with: ..<100)   // 99
100.clamped(with: ...100)   // 100
100.clamped(with: 1..<100)  // 99
100.clamped(with: 1...100)  // 100

0.clamped(with: 1...)       // 1
0.clamped(with: ..<100)     // 0
0.clamped(with: ...100)     // 0
0.clamped(with: 1..<100)    // 1
0.clamped(with: 1...100)    // 1

To achieve the same results with a FloatingPoint implementation you can use its nextDown property for the edge cases:

extension BinaryFloatingPoint {
    func clamped<R: RangeExpression>(with range: R) -> Self where R.Bound == Self {
        switch range {
        case let range as ClosedRange<Self>:
            return Swift.min(range.upperBound, Swift.max(range.lowerBound, self))
        case let range as PartialRangeFrom<Self>:
            return Swift.max(range.lowerBound, self)
        case let range as PartialRangeThrough<Self>:
            return Swift.min(range.upperBound, self)
        case let range as Range<Self>:
            return Swift.min(range.upperBound.nextDown, Swift.max(range.lowerBound, self))
        case let range as PartialRangeUpTo<Self>:
            return Swift.min(range.upperBound.nextDown, self)
        default: return self
        }
    }
}

Playground testing:

let value = 100.0

value.clamped(with: 1...)     // 100
value.clamped(with: ..<100)   // 99.99999999999999
value.clamped(with: ...100)   // 100
value.clamped(with: 1..<100)  // 99.99999999999999
value.clamped(with: 1...100)  // 100


答:
This is a classic gaps-and-islands problem.

There are many solutions. A common one is to use LAG to identify rows which change value, then a conditional windowed COUNT to assign the group numbers

WITH PrevValues AS (
    SELECT *,
      LAG(COL_1) OVER (ORDER BY COL_2) AS PrevCol1
    FROM YourTable t
)
SELECT COL_1,COL_2,COL_3,
  COUNT(CASE WHEN PrevCol1 = COL_1 THEN NULL ELSE 1 END)
      OVER (ORDER BY COL_2 ROWS UNBOUNDED PRECEDING) AS New_Col_3
FROM PrevValues t
```

db<>fiddle

Title: Set value for group by order

Body:
I have SQL table with columns COL_1, COL_2:

COL_1
COL_2
COL_3

a
2021-09-11 14:25:15.699
1

b
2021-09-11 14:25:36.489
2

a
2021-09-11 14:33:36.500
3

a
2021-09-11 14:36:24.915
3

a
2021-09-11 14:36:38.900
3

a
2021-09-11 14:36:54.905
3

c
2021-09-11 14:37:09.092
4

a
2021-09-11 14:39:09.111
5

d
2021-09-11 14:39:30.292
6

I need to get COL_3. I got column 4 by grouping column 1 and sorting by date (column 2), if the group changes, I assign a new index for the following groups.

Body:
This is a classic gaps-and-islands problem.

There are many solutions. A common one is to use LAG to identify rows which change value, then a conditional windowed COUNT to assign the group numbers

WITH PrevValues AS (
    SELECT *,
      LAG(COL_1) OVER (ORDER BY COL_2) AS PrevCol1
    FROM YourTable t
)
SELECT COL_1,COL_2,COL_3,
  COUNT(CASE WHEN PrevCol1 = COL_1 THEN NULL ELSE 1 END)
      OVER (ORDER BY COL_2 ROWS UNBOUNDED PRECEDING) AS New_Col_3
FROM PrevValues t

db<>fiddle


问:
get current users data from firestore on reactjs using uid as a link between the user auth and firestore. get this Error: Too many re-renders
i am trying to get user data from firestore using uid to link the firestore data and the user auth. i have tried this but keep getting a blank screen with too many re-renders errors. would anyone be able to help?
my firestore collection is named values and it stores Fname,Lname, bio, username and uid

```<code>import {
 StyleSheet,
 Text,
 View,
 Image,
} from 'react-native';
import { auth, db } from '../Firebase'

const  UserProfileView = () => {

   const [user, setUser] = useState();
   const {uid} = auth.currentUser.uid;

     const userRef = db.collection('values').doc(uid);
     const doc =  userRef.get();
     doc.data;

   const userData = doc.data;
   setUser(userData);

// Get user on mount
useEffect(() => {
   UserProfileView();
}, []);

//adapted from https://www.bootdey.com/react-native-snippet/12/User-profile-with-options

</code>```

My return the only code that relates to the above is the text tag with user && user?.Fname

```<code>    return (
      <View style={styles.container}>
          <View style={styles.header}>
            <View style={styles.headerContent}>
                <Image style={styles.avatar}
                  source={{uri: 'https://bootdey.com/img/Content/avatar/avatar6.png'}}/>

                <Text style={styles.name}>{auth.currentUser?.uid} </Text>
                <Text style={styles.name}>{user && user?.Fname}</Text>
                <Text style={styles.userInfo}>{auth.currentUser?.email}</Text>
                <Text style={styles.userInfo}>Florida </Text>
            </View>
          </View>

          <View style={styles.body}>
            <View style={styles.item}>
              <View style={styles.iconContent}>
                <Image style={styles.icon} source={{uri: 'https://img.icons8.com/color/70/000000/cottage.png'}}/>
              </View>
              <View style={styles.infoContent}>
                <Text style={styles.info}>Home</Text>
              </View>
            </View>

            <View style={styles.item}>
              <View style={styles.iconContent}>
                <Image style={styles.icon} source={{uri: 'https://img.icons8.com/color/70/000000/administrator-male.png'}}/>
              </View>
              <View style={styles.infoContent}>
                <Text style={styles.info}>Settings</Text>
              </View>
            </View>

            <View style={styles.item}>
              <View style={styles.iconContent}>
                <Image style={styles.icon} source={{uri: 'https://img.icons8.com/color/70/000000/filled-like.png'}}/>
              </View>
              <View style={styles.infoContent}>
                <Text style={styles.info}>News</Text>
              </View>
            </View>

            <View style={styles.item}>
              <View style={styles.iconContent}>
                <Image style={styles.icon} source={{uri: 'https://img.icons8.com/color/70/000000/facebook-like.png'}}/>
              </View>
              <View style={styles.infoContent}>
                <Text style={styles.info}>Shop</Text>
              </View>
            </View>

          </View>
      </View>
    );
  }
export default UserProfileView;```
```

答:
Your code is recursive, you're defining UserProfileView functional component and calling it itself inside the UseEffect hook.

Refactor code as below:

import { StyleSheet, Text, View, Image } from "react-native";
import { auth, db } from "../Firebase";

const UserProfileView = () => {
  const [user, setUser] = useState(null);

  const fetchUserInfo = async () => {
    const { uid } = auth().currentUser;
    // Discard fetch when user ID not defined
    if (!uid) return;
    const userRef = db.collection("values").doc(uid);
    const doc = await userRef.get();
    const userData = doc.data();
    setUser(userData);
  };

  // Get user on mount
  useEffect(() => {
    fetchUserInfo();
  }, []);

  if (!user) return null;

  return (
    <View style={styles.container}>
      <View style={styles.header}>
        <View style={styles.headerContent}>
          <Image
            style={styles.avatar}
            source={{
              uri: "https://bootdey.com/img/Content/avatar/avatar6.png",
            }}
          />

          <Text style={styles.name}>{auth.currentUser?.uid} </Text>
          <Text style={styles.name}>{user && user?.Fname}</Text>
          <Text style={styles.userInfo}>{auth.currentUser?.email}</Text>
          <Text style={styles.userInfo}>Florida </Text>
        </View>
      </View>

      <View style={styles.body}>
        <View style={styles.item}>
          <View style={styles.iconContent}>
            <Image
              style={styles.icon}
              source={{
                uri: "https://img.icons8.com/color/70/000000/cottage.png",
              }}
            />
          </View>
          <View style={styles.infoContent}>
            <Text style={styles.info}>Home</Text>
          </View>
        </View>

        <View style={styles.item}>
          <View style={styles.iconContent}>
            <Image
              style={styles.icon}
              source={{
                uri: "https://img.icons8.com/color/70/000000/administrator-male.png",
              }}
            />
          </View>
          <View style={styles.infoContent}>
            <Text style={styles.info}>Settings</Text>
          </View>
        </View>

        <View style={styles.item}>
          <View style={styles.iconContent}>
            <Image
              style={styles.icon}
              source={{
                uri: "https://img.icons8.com/color/70/000000/filled-like.png",
              }}
            />
          </View>
          <View style={styles.infoContent}>
            <Text style={styles.info}>News</Text>
          </View>
        </View>

        <View style={styles.item}>
          <View style={styles.iconContent}>
            <Image
              style={styles.icon}
              source={{
                uri: "https://img.icons8.com/color/70/000000/facebook-like.png",
              }}
            />
          </View>
          <View style={styles.infoContent}>
            <Text style={styles.info}>Shop</Text>
          </View>
        </View>
      </View>
    </View>
  );
};
export default UserProfileView;

```

Body:
i am trying to get user data from firestore using uid to link the firestore data and the user auth. i have tried this but keep getting a blank screen with too many re-renders errors. would anyone be able to help?
my firestore collection is named values and it stores Fname,Lname, bio, username and uid

import {
 StyleSheet,
 Text,
 View,
 Image,
} from 'react-native';
import { auth, db } from '../Firebase'

const  UserProfileView = () => {

   const [user, setUser] = useState();
   const {uid} = auth.currentUser.uid;

     const userRef = db.collection('values').doc(uid);
     const doc =  userRef.get();
     doc.data;

   const userData = doc.data;
   setUser(userData);

// Get user on mount
useEffect(() => {
   UserProfileView();
}, []);

//adapted from https://www.bootdey.com/react-native-snippet/12/User-profile-with-options

My return the only code that relates to the above is the text tag with user && user?.Fname

    return (
      <View style={styles.container}>
          <View style={styles.header}>
            <View style={styles.headerContent}>
                <Image style={styles.avatar}
                  source={{uri: 'https://bootdey.com/img/Content/avatar/avatar6.png'}}/>

                <Text style={styles.name}>{auth.currentUser?.uid} </Text>
                <Text style={styles.name}>{user && user?.Fname}</Text>
                <Text style={styles.userInfo}>{auth.currentUser?.email}</Text>
                <Text style={styles.userInfo}>Florida </Text>
            </View>
          </View>

          <View style={styles.body}>
            <View style={styles.item}>
              <View style={styles.iconContent}>
                <Image style={styles.icon} source={{uri: 'https://img.icons8.com/color/70/000000/cottage.png'}}/>
              </View>
              <View style={styles.infoContent}>
                <Text style={styles.info}>Home</Text>
              </View>
            </View>

            <View style={styles.item}>
              <View style={styles.iconContent}>
                <Image style={styles.icon} source={{uri: 'https://img.icons8.com/color/70/000000/administrator-male.png'}}/>
              </View>
              <View style={styles.infoContent}>
                <Text style={styles.info}>Settings</Text>
              </View>
            </View>

            <View style={styles.item}>
              <View style={styles.iconContent}>
                <Image style={styles.icon} source={{uri: 'https://img.icons8.com/color/70/000000/filled-like.png'}}/>
              </View>
              <View style={styles.infoContent}>
                <Text style={styles.info}>News</Text>
              </View>
            </View>

            <View style={styles.item}>
              <View style={styles.iconContent}>
                <Image style={styles.icon} source={{uri: 'https://img.icons8.com/color/70/000000/facebook-like.png'}}/>
              </View>
              <View style={styles.infoContent}>
                <Text style={styles.info}>Shop</Text>
              </View>
            </View>

          </View>
      </View>
    );
  }
export default UserProfileView;```


问:
Between in createdCriteria not works
I have a very strange problem. I create 3 entities with the following data:

```<code>CCB ccb1 = new Ccb(1)
CCB ccb2 = new Ccb(2)
CCB ccb3 = new Ccb(3)
</code>```

Where the parameter (Long) is the object id.

Then, when wanting to create a list with the between clause, it is created with size = 0:

```<code>    ConcurrentLinkedQueue<Long> ccbIds = new ConcurrentLinkedQueue(
            Ccb.createCriteria().list {
                between("id", 1, 5)
                projections {
                    id()
                }
            }
    )
</code>```

I've tried this alternative and it doesn't work either:

```<code>    ConcurrentLinkedQueue<Long> ccbIds = new ConcurrentLinkedQueue(
            Ccb.createCriteria().list {
                between("id", "1", "5")
                projections {
                    id()
                }
            }
    )
</code>```

The incredible thing is that if I replace the between with the eq:

```<code>    ConcurrentLinkedQueue<Long> ccbIds = new ConcurrentLinkedQueue(
            Ccb.createCriteria().list {
                eq("id", 2)
                projections {
                    id()
                }
            }
    )
</code>```

Now the list returns me the element with id 2!
I can't understand where is the error.

Thanks!

EDIT:

Config of DataSource.groovy:

```<code>    dataSource {
        dbCreate = "create-drop"
        driverClassName = "org.h2.Driver"
        dialect = "org.hibernate.dialect.H2Dialect"
        url = "jdbc:h2:mem:devDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE"
    }
</code>```

答: After run different tests, I came to the conclusion that it is a bug in Grails when using the H2 storage. With SQL it works fine.</p>

Title: Between in createdCriteria not works

Body:
I have a very strange problem. I create 3 entities with the following data:

CCB ccb1 = new Ccb(1)
CCB ccb2 = new Ccb(2)
CCB ccb3 = new Ccb(3)

Where the parameter (Long) is the object id.

Then, when wanting to create a list with the between clause, it is created with size = 0:

    ConcurrentLinkedQueue<Long> ccbIds = new ConcurrentLinkedQueue(
            Ccb.createCriteria().list {
                between("id", 1, 5)
                projections {
                    id()
                }
            }
    )

I've tried this alternative and it doesn't work either:

    ConcurrentLinkedQueue<Long> ccbIds = new ConcurrentLinkedQueue(
            Ccb.createCriteria().list {
                between("id", "1", "5")
                projections {
                    id()
                }
            }
    )

The incredible thing is that if I replace the between with the eq:

    ConcurrentLinkedQueue<Long> ccbIds = new ConcurrentLinkedQueue(
            Ccb.createCriteria().list {
                eq("id", 2)
                projections {
                    id()
                }
            }
    )

Now the list returns me the element with id 2!
I can't understand where is the error.

Thanks!

EDIT:

Config of DataSource.groovy:

    dataSource {
        dbCreate = "create-drop"
        driverClassName = "org.h2.Driver"
        dialect = "org.hibernate.dialect.H2Dialect"
        url = "jdbc:h2:mem:devDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE"
    }


问:
How to put a newline in ant property
This doesn't seem to work:

```<code><property name="foo" value="\n bar \n"/>
</code>```

I use the property value in the body of an e-mail message (which is sent as plain text):

```<code><mail ...>
  <message>some text${foo}</message>
</code>```

and I get literal "\n" in the e-mail output.

答:
You want ${line.separator}.  See this post for an example.  Also, the Ant echo task manual page has an example using ${line.separator}.

By using ${line.separator} you're simply using a Java system property.  You can read up on the list of system properties here, and here is Ant's manual page on Properties.

Title: How to put a newline in ant property

Body:
This doesn't seem to work:

<property name="foo" value="\n bar \n"/>

I use the property value in the body of an e-mail message (which is sent as plain text):

<mail ...>
  <message>some text${foo}</message>

and I get literal "\n" in the e-mail output.


问:
Device manager does not work (open) after updating Android Studio to 2021.1.1
Android studio's device manager AVD manager works fine in old versions, but in 2021.1.1 version does not open!
Windows 10 and 11 tested
last version flutter
Intel
Sdk manager everything updated
could anyone help?</p>

答:
I too met this problem temp solution this that which wrote Zaid Salam

My version Android Studio -> Bumblebee 2021.1.1 Patch 1

My OS -> macOS Monterey


问:
How to scroll down to click the element in Android using appium and java?
I would like to know how to scroll down to click the element in Android using appium and java?

I am having a list of elements inside "android.support.v7.widget.RecyclerView". Since it has more than 10 elements, we need to swipe the screen to see the below elements.
Each element has same id which is "com.osanda.exampleapp/textViewTitle". But their texts are different like "Apple", "Orange", "Grapes"......

All I need is to scroll and click the relevant element using its text("Apple", "Orange", "Grapes".....)

I have followed many tutorials but couldn't do it properly. I have managed to scroll down the screen. But it won't work when the element is in the middle position of the scroll.

When I listed the element names it only shows the visible elements, not all elements.

```<code>List<WebElement> elements = androidDriver.findElementByClassName("android.support.v7.widget.RecyclerView").findElements(By.id("com.osanda.exampleapp:id/textViewTitle"));
        for(WebElement element : elements) {
            System.out.println(element.getText());
        }
</code>```

Thank You.

答:
You could use this one

```<code>public void scrollAndClick(String visibleText) {
 androidDriver.findElementByAndroidUIAutomator
  ("new UiScrollable(new UiSelector().scrollable(true).
   instance(0)).scrollIntoView(
  new UiSelector().textContains(\""+visibleText+
  "\").instance(0))").click();
    }
   }
</code>```

or this one:

```<code>String uiSelector = "new UiSelector().textMatches
(\"" + text+ "\")";
String command = "new UiScrollable(
new UiSelector().scrollable(true).
instance(0)).scrollIntoView("+ uiSelector + ");";
driver.findElementByAndroidUIAutomator(command);
</code>```

It will scroll till the text is visible.

Body:
I would like to know how to scroll down to click the element in Android using appium and java?

I am having a list of elements inside "android.support.v7.widget.RecyclerView". Since it has more than 10 elements, we need to swipe the screen to see the below elements.
Each element has same id which is "com.osanda.exampleapp/textViewTitle". But their texts are different like "Apple", "Orange", "Grapes"......

All I need is to scroll and click the relevant element using its text("Apple", "Orange", "Grapes".....)

I have followed many tutorials but couldn't do it properly. I have managed to scroll down the screen. But it won't work when the element is in the middle position of the scroll.

When I listed the element names it only shows the visible elements, not all elements.

List<WebElement> elements = androidDriver.findElementByClassName("android.support.v7.widget.RecyclerView").findElements(By.id("com.osanda.exampleapp:id/textViewTitle"));
        for(WebElement element : elements) {
            System.out.println(element.getText());
        }

Thank You.

Body:
You could use this one

public void scrollAndClick(String visibleText) {
 androidDriver.findElementByAndroidUIAutomator
  ("new UiScrollable(new UiSelector().scrollable(true).
   instance(0)).scrollIntoView(
  new UiSelector().textContains(\""+visibleText+
  "\").instance(0))").click();
    }
   }

or this one:

String uiSelector = "new UiSelector().textMatches
(\"" + text+ "\")";
String command = "new UiScrollable(
new UiSelector().scrollable(true).
instance(0)).scrollIntoView("+ uiSelector + ");";
driver.findElementByAndroidUIAutomator(command);

It will scroll till the text is visible.


问:
magento setup:upgrade showing could not validate a connection to elastic search
I am cloning a magento repo. after i did composer update and then bin/magento setup:upgrade it is giving me the following error

-- Could not validate a connection to elastic search. no alive nodes found in your cluster --

the elastic search is up and running. If i install a fresh magento project (2.4.3) setup:upgrade command works fine.

I also checked the status of the elastic search and it showed as below pic
elastic search status

I have already checked a previous thread relating to not connecting to elastic search. have tried every answers there and I believe that thread was a different problem.

答:
Its seems to be a elasticsearch connection problems,
Verify the core_config_data according the @Andrew response.

If you are using docker, maybe can be a permission problems:

A permission 777 in your docker folders of your project can helps (of course, in local environments only), specially which has elasticsearch files (volumes and other configuration)


问:
is any methods for refreshing data in table in react js?
As I'm trying to refresh the page by using window.location.reload() method the page is reloading but it is redirecting from current page to home page.I have searched more number of methods like setInterval() but when we add,delete and edit the record after clicking the submit button the record in the table is not visible.so as i'm new to this react js,anyone please help me to overcome from this issue</p>

答:
The correct approach maybe must be store the data of your table like a state.

If you're using hooks:

```<code>const [dataTable, setDataTable] = useState(null)
</code>```

And after you add, edit or delete a record you should update your dataTable state with the new dataTable.

```<code>onDataTableChange = (data) => {
setDataTable(data) }
</code>```

This going to update your state and re-render with the new data.

Body:
The correct approach maybe must be store the data of your table like a state.

If you're using hooks:

const [dataTable, setDataTable] = useState(null)

And after you add, edit or delete a record you should update your dataTable state with the new dataTable.

onDataTableChange = (data) => {
setDataTable(data) }

This going to update your state and re-render with the new data.


问:
Hibernate: Need to save the same object twice within the transaction
I need to save the same object twice within transaction, but hibernate always have only one sql update, any way to do it?
Here is the code:

```<code>....
session.beginTransaction();
Student s = session.get(Student.class, id);

// (1) first save
s.setSequenceNum(10);
session.saveOrUpdate(s);

// (2) second save
s.setSequenceNum(9);
session.saveOrUpdate(s);  // save again

session.getTransaction().commit();
session.close();
</code>```

hibernate will ignore the first one, and only have one sql update for the second. How can i let hibernate do both of the two sql update? I need this because it is the requirement in our project.

答: Try session.flush() after the first update or set session.setFlushMode(FlushMode.Always) before the first update. Remember that setFlushmode will affect the whole session if it is being reused after the transaction</p>

Body:
I need to save the same object twice within transaction, but hibernate always have only one sql update, any way to do it?
Here is the code:

....
session.beginTransaction();
Student s = session.get(Student.class, id);

// (1) first save
s.setSequenceNum(10);
session.saveOrUpdate(s);

// (2) second save
s.setSequenceNum(9);
session.saveOrUpdate(s);  // save again

session.getTransaction().commit();
session.close();

hibernate will ignore the first one, and only have one sql update for the second. How can i let hibernate do both of the two sql update? I need this because it is the requirement in our project.


问:
How can we get the same output in c++?
I'm new to c++ and recently shifted from python. Can anyone explain me what should be the actual code in c++, if we want to print items of a list in for loop.
For example: in python. We do something like.

sample_list = ['you', 'are','awesome']
for i in sample_list:
    print(i)
```
<p>In C++ its something like.</p>
```for(initialisation, condition, updation )
{
Your code
}
```

But there is no update We just want to get items from a list.

How can I do same in C++?

答:
It looks like you're looking for a string array made with

```<code>#include <string>

int main() {
  std::string array[];
}
</code>```

Now all you need to do is run a for loop that prints the Ith member of the array with

```<code>#include <iostream>
#include <string>

int main() {
  std::string array[5];
  for(int i; i<5; i++) {
    std::cout << array[i] << std::endl;
  }
}
</code>```

Title: How can we get the same output in c++?

Body:
I'm new to c++ and recently shifted from python. Can anyone explain me what should be the actual code in c++, if we want to print items of a list in for loop.
For example: in python. We do something like.

sample_list = ['you', 'are','awesome']
for i in sample_list:
    print(i)

In C++ its something like.

for(initialisation, condition, updation )
{
Your code
}

But there is no update We just want to get items from a list.

How can I do same in C++?

Body:
It looks like you're looking for a string array made with

#include <string>

int main() {
  std::string array[];
}

Now all you need to do is run a for loop that prints the Ith member of the array with

#include <iostream>
#include <string>

int main() {
  std::string array[5];
  for(int i; i<5; i++) {
    std::cout << array[i] << std::endl;
  }
}


问:
DynamoDB gt() query on GSI
I am trying to get a gt() query working with a DynamoDB GSI

My Cloudformation is as follows -

Resources
  MyTable:
    Properties:
      AttributeDefinitions:
      - AttributeName: pk
        AttributeType: S
      - AttributeName: sk
        AttributeType: S
      - AttributeName: my_datetime_string
        AttributeType: S
      BillingMode: PAY_PER_REQUEST
      GlobalSecondaryIndexes:
      - IndexName: my_datetime_string-index
        KeySchema:
        - AttributeName: my_datetime_string
          KeyType: HASH
        Projection:
          ProjectionType: ALL
      KeySchema:
      - AttributeName: pk
        KeyType: HASH
      - AttributeName: sk
        KeyType: RANGE
      TableName:
        Fn::Sub: my-table-${AWS::StackName}-${AWS::Region}
    Type: AWS::DynamoDB::Table
```
<p>My query code is as follows (python) -</p>
<pre class="lang-py prettyprint-override"><code>tablename="whatever"
import boto3
table=boto3.resource("dynamodb").Table(tablename)
from datetime import datetime
timestamp="%s 00:00:00" % datetime.today().strftime("%Y-%m-%d")
from boto3.dynamodb.conditions import Key
expr=Key("my_datetime_string").gt(timestamp)
print (table.query(IndexName="my_datetime_string-index",
                   KeyConditionExpression=expr))
</code>```

I have some data in the table and have can see that it has a String type (my_datetime_string) -

{'Item': {'my_datetime_string': '2022-01-27 14:30:00', 'sk': 'HEAD', 'pk': 'EVENT#1293000'}, 'ResponseMetadata': {'RequestId': 'XXX', 'HTTPStatusCode': 200, 'HTTPHeaders': {'server': 'Server', 'date': 'Tue, 08 Feb 2022 10:54:15 GMT', 'content-type': 'application/x-amz-json-1.0', 'content-length': '522', 'connection': 'keep-alive', 'x-amzn-requestid': 'XXX', 'x-amz-crc32': '2080419831'}, 'RetryAttempts': 0}}
```
<p>But all I get from the query is -</p>
<pre class="lang-sh prettyprint-override"><code>An error occurred (ValidationException) when calling the Query operation: Query key condition not supported
</code>```

What am I missing here ? Surely GSI indexes support gt() queries for String types ? (or maybe not ??)

答:
my_datetime_string is your index's Partition Key (= Hash Key).  A Query must provide one-and-only-one Partition Key value.  This means that eq is a valid operator in Partition Key conditions, but gt is not.

If your table/index has a compound primary key, a query can apply a gt operation to the Sort Key (= Range Key) condition, which will return a range of values.

Title: DynamoDB gt() query on GSI

Body:
I am trying to get a gt() query working with a DynamoDB GSI

My Cloudformation is as follows -

Resources
  MyTable:
    Properties:
      AttributeDefinitions:
      - AttributeName: pk
        AttributeType: S
      - AttributeName: sk
        AttributeType: S
      - AttributeName: my_datetime_string
        AttributeType: S
      BillingMode: PAY_PER_REQUEST
      GlobalSecondaryIndexes:
      - IndexName: my_datetime_string-index
        KeySchema:
        - AttributeName: my_datetime_string
          KeyType: HASH
        Projection:
          ProjectionType: ALL
      KeySchema:
      - AttributeName: pk
        KeyType: HASH
      - AttributeName: sk
        KeyType: RANGE
      TableName:
        Fn::Sub: my-table-${AWS::StackName}-${AWS::Region}
    Type: AWS::DynamoDB::Table

My query code is as follows (python) -

tablename="whatever"
import boto3
table=boto3.resource("dynamodb").Table(tablename)
from datetime import datetime
timestamp="%s 00:00:00" % datetime.today().strftime("%Y-%m-%d")
from boto3.dynamodb.conditions import Key
expr=Key("my_datetime_string").gt(timestamp)
print (table.query(IndexName="my_datetime_string-index",
                   KeyConditionExpression=expr))

I have some data in the table and have can see that it has a String type (my_datetime_string) -

{'Item': {'my_datetime_string': '2022-01-27 14:30:00', 'sk': 'HEAD', 'pk': 'EVENT#1293000'}, 'ResponseMetadata': {'RequestId': 'XXX', 'HTTPStatusCode': 200, 'HTTPHeaders': {'server': 'Server', 'date': 'Tue, 08 Feb 2022 10:54:15 GMT', 'content-type': 'application/x-amz-json-1.0', 'content-length': '522', 'connection': 'keep-alive', 'x-amzn-requestid': 'XXX', 'x-amz-crc32': '2080419831'}, 'RetryAttempts': 0}}

But all I get from the query is -

An error occurred (ValidationException) when calling the Query operation: Query key condition not supported

What am I missing here ? Surely GSI indexes support gt() queries for String types ? (or maybe not ??)


问:
Firebase Text Recognition for Web
Is it possible to use Text Recognition (https://firebase.google.com/docs/ml/recognize-text) for web projects. I'd like it to run the built-in model through images uploaded to the Storage.</p>

答:
From the documentation:

Firebase Machine Learning is a mobile SDK that brings Google's machine learning expertise to Android and Apple apps in a powerful yet easy-to-use package.

So it seems that Firebase Machine Learning is only available for Android and iOS apps, and not for web apps.

Title: Firebase Text Recognition for Web


问:
Switch and Router modules missing from react-router-dom
Title of my question says it all. I've been trying to create a React app with several "pages" using react-router-dom. Basically what I've done is prompt "npx create-react-app", create a few JS page files just to test the thing and prompt a"npm install react-router-dom". Nothing else.

Now when I try to import the Switch module from react-router-dom, my IDE (I'm using Jetbrains Webstorm) doesn't find the dependency. I've checked manually by for the missing dependencies inside the module folder at node_modules, and the dependency is really not there.

I've read several tutorials on react-router-dom, and nobody says anything about Switch being deprecated or something like that, so that can't be the case.

I don't know if any other information would be of help, but feel free to point it out in case there's more info I can provide. Any help would be appreciated.

My package.json looks like this:

```<code>{
  "name": "react-router-test",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.5.0",
    "@testing-library/user-event": "^7.2.1",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "react-router-dom": "^5.1.2",
    "react-scripts": "3.4.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}
</code>```

答:
Updated your v5 of react-router-dom to v6 and replace:

```<code><Switch>
   <Route path={`${match.path}/me`}>
      <OwnUserProfile />
    </Route>
     <Route path={`${match.path}/:id`}>
        <UserProfile />
      </Route>
 </Switch>

</code>```

in V6 same example

```<code><Routes>
   <Route path="/" element={<Home />} />
   <Route path="users/*" element={<Users />} />
 </Routes>
</code>```

See the upgrading doc in react-routers

Body:
Title of my question says it all. I've been trying to create a React app with several "pages" using react-router-dom. Basically what I've done is prompt "npx create-react-app", create a few JS page files just to test the thing and prompt a"npm install react-router-dom". Nothing else.

Now when I try to import the Switch module from react-router-dom, my IDE (I'm using Jetbrains Webstorm) doesn't find the dependency. I've checked manually by for the missing dependencies inside the module folder at node_modules, and the dependency is really not there.

I've read several tutorials on react-router-dom, and nobody says anything about Switch being deprecated or something like that, so that can't be the case.

I don't know if any other information would be of help, but feel free to point it out in case there's more info I can provide. Any help would be appreciated.

My package.json looks like this:

{
  "name": "react-router-test",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.5.0",
    "@testing-library/user-event": "^7.2.1",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "react-router-dom": "^5.1.2",
    "react-scripts": "3.4.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

Body:
Updated your v5 of react-router-dom to v6 and replace:

<Switch>
   <Route path={`${match.path}/me`}>
      <OwnUserProfile />
    </Route>
     <Route path={`${match.path}/:id`}>
        <UserProfile />
      </Route>
 </Switch>

in V6 same example

<Routes>
   <Route path="/" element={<Home />} />
   <Route path="users/*" element={<Users />} />
 </Routes>

See the upgrading doc in react-routers


问:
Playing a MP3 using Windows Phone 7 and MediaElement
I'm trying to figure out how to play a MP3 of a GoogleVoice voicemail item.  To start, the MP3 isn't a .mp3 where you can just set an audio source to MediaElement.  The MP3 is served via an HTTP response.  Basically, I need a way to have MediaElement play this MP3.  It would be nice if I can just do a static URL to the file, but it seems I need to download or something first...

Below is as much information as I can dig up.  I can make the request via HTTPWebRequest, it's not handling the rest.  Before I go about downloading it all, I wanted to see what people suggest.

URL: https://www.google.com/voice/media/send_voicemail/gh8a7a5d649e0b3e182b7d353b1e3794aec89526

Fiddler Request:
GET https://www.google.com/voice/media/send_voicemail/gh8a7a5d649e0b3e182b7d353b1e3794aec89526 HTTP/1.1
Accept: text/html, application/xhtml+xml, /
Accept-Language: en-US
User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; InfoPath.3; .NET4.0C; .NET4.0E; Zune 4.7; MS-RTC LM 8)
Accept-Encoding: gzip, deflate
Host: www.google.com
Connection: Keep-Alive

Fiddler Response:
HTTP/1.1 200 OK
Content-Type: audio/mpeg
Cache-Control: must-revalidate
Expires: Fri, 01 Jan 1990 00:00:00 GMT
Pragma: no-cache, no-store
cookie:
Content-Length: 5120
Content-Disposition: attachment; filename="gh8a7a5d649e0b3e182b7d353b1e3794aec89526.mp3"
Content-Transfer-Encoding: binary
Accept-Ranges: bytes
Date: Fri, 17 Jun 2011 18:11:10 GMT
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block
Server: GSE

�� ��yz�CHwww�8��B�!9�F+�F�PIb���&+$@����L�0L�0ؠ�<�9���'4h���[l�S�[m���"�.... (note this is the 5120 bytes in the content length)

Thanks!

答:
I don't know if this is of any help, but for some content MediaElement assumes that correct file extension is in place in the URL. Also, I have seen somewhere that you could try adding the extension as query parameter to the requested URL (sorry, can't find it anymore). So, your URL could become:
       https://www.google.com/voice/media/send_voicemail/gh8a7a5d649e0b3e182b7d353b1e3794aec89526?ext=.mp3</p>


问:
How to create a queue in RabbitMQ upon startup
I am trying to start RMQ inside docker container, with precreated queue qwer.

Prior to this, I was using simple docker-compose.yml file:

```<code>rabbit:
    image: rabbitmq:management-alpine
    environment:
      RABBITMQ_DEFAULT_USER: guest
      RABBITMQ_DEFAULT_PASS: guest
</code>```

And it worked fine, except that it has no queues pre-created at start.
Now I've switched to custom image, with following Dockerfile:

```<code>FROM rabbitmq:management-alpine

ADD rabbitmq.conf /etc/rabbitmq/
ADD definitions.json /etc/rabbitmq/

RUN chown rabbitmq:rabbitmq /etc/rabbitmq/rabbitmq.conf /etc/rabbitmq/definitions.json
</code>```

where rabbitmq.conf is v3.7+ sysctl-styled config, with line:

```<code>management.load_definitions = /etc/rabbitmq/definitions.json
</code>```

and definitions.json contains attempt to create queue:

```<code>{
    "vhosts":[
        {"name":"/"}
    ],
    "queues":[
        {"name":"qwer","vhost":"/","durable":true,"auto_delete":false,"arguments":{}}
    ]
}
</code>```

Now it started to refuse login:

```<code>Error on AMQP connection <0.660.0> (172.18.0.6:48916 -> 172.18.0.10:5672, state: starting):
PLAIN login refused: user 'guest' - invalid credentials
</code>```

I thought that the task is somewhat simple, but configuration process of rabbit itself is most complex task, and documentation is somewhat unclear.

I was unable to figure out how should it work, even after 4 days of trials and googling..

Could you help me, how to write configuration file, in order to create a queue and preserve ability to connect and talk to it?

答:
You can predefine queues and exchanges without creating own rabbit-mq docker image.

Your docker-compose should look like this:

```<code>rabbit:
container_name: rabbitmq-preload-conf
image: rabbitmq:3-management
volumes:
  - ./init/rabbitmq.conf:/etc/rabbitmq/rabbitmq.conf:ro
  - ./init/definitions.json:/etc/rabbitmq/definitions.json:ro
ports:
  - "5672:5672"
  - "15672:15672"
</code>```

In this case rabbitmq.conf and definitions.json files should be in init folder in the same parent folder as docker-compose file

rabbitmq.conf file

```<code>management.load_definitions = /etc/rabbitmq/definitions.json
</code>```

definitions.json file

```<code>{
"queues": [
    {
        "name": "externally_configured_queue",
        "vhost": "/",
        "durable": true,
        "auto_delete": false,
        "arguments": {
            "x-queue-type": "classic"
        }
    }
],
"exchanges": [
    {
        "name": "externally_configured_exchange",
        "vhost": "/",
        "type": "direct",
        "durable": true,
        "auto_delete": false,
        "internal": false,
        "arguments": {}
    }
],
"bindings": [
    {
        "source": "externally_configured_exchange",
        "vhost": "/",
        "destination": "externally_configured_queue",
        "destination_type": "queue",
        "routing_key": "externally_configured_queue",
        "arguments": {}
    }
  ]
 }
</code>```

NOTE: After update in rabbit images, additional configuration may be required. If rabbit container failed to start with the configuration mentioned above (error message contains "Exception during startup:
exit:{error,{no_such_vhost,<<"/">>}}") following configuration should be added into definitions file:

```<code> "users": [
    {
      "name": "guest",
      "password_hash": "BMfxN8drrYcIqXZMr+pWTpDT0nMcOagMduLX0bjr4jwud/pN",
      "hashing_algorithm": "rabbit_password_hashing_sha256",
      "tags": [
        "administrator"
      ],
      "limits": {}
    }
  ],
  "vhosts": [
    {
      "name": "/"
    }
  ],
  "permissions": [
    {
      "user": "guest",
      "vhost": "/",
      "configure": ".*",
      "write": ".*",
      "read": ".*"
    }
  ]
</code>```

Using this additional configuration, default user will be guest with password guest.

Apart from queues, exchanges and bindings, definitions.json file can contain additional configuration

Body:
I am trying to start RMQ inside docker container, with precreated queue qwer.

Prior to this, I was using simple docker-compose.yml file:

rabbit:
    image: rabbitmq:management-alpine
    environment:
      RABBITMQ_DEFAULT_USER: guest
      RABBITMQ_DEFAULT_PASS: guest

And it worked fine, except that it has no queues pre-created at start.
Now I've switched to custom image, with following Dockerfile:

FROM rabbitmq:management-alpine

ADD rabbitmq.conf /etc/rabbitmq/
ADD definitions.json /etc/rabbitmq/

RUN chown rabbitmq:rabbitmq /etc/rabbitmq/rabbitmq.conf /etc/rabbitmq/definitions.json

where rabbitmq.conf is v3.7+ sysctl-styled config, with line:

management.load_definitions = /etc/rabbitmq/definitions.json

and definitions.json contains attempt to create queue:

{
    "vhosts":[
        {"name":"/"}
    ],
    "queues":[
        {"name":"qwer","vhost":"/","durable":true,"auto_delete":false,"arguments":{}}
    ]
}

Now it started to refuse login:

Error on AMQP connection <0.660.0> (172.18.0.6:48916 -> 172.18.0.10:5672, state: starting):
PLAIN login refused: user 'guest' - invalid credentials

I thought that the task is somewhat simple, but configuration process of rabbit itself is most complex task, and documentation is somewhat unclear.

I was unable to figure out how should it work, even after 4 days of trials and googling..

Could you help me, how to write configuration file, in order to create a queue and preserve ability to connect and talk to it?

Body:
You can predefine queues and exchanges without creating own rabbit-mq docker image.

Your docker-compose should look like this:

rabbit:
container_name: rabbitmq-preload-conf
image: rabbitmq:3-management
volumes:
  - ./init/rabbitmq.conf:/etc/rabbitmq/rabbitmq.conf:ro
  - ./init/definitions.json:/etc/rabbitmq/definitions.json:ro
ports:
  - "5672:5672"
  - "15672:15672"

In this case rabbitmq.conf and definitions.json files should be in init folder in the same parent folder as docker-compose file

rabbitmq.conf file

management.load_definitions = /etc/rabbitmq/definitions.json

definitions.json file

{
"queues": [
    {
        "name": "externally_configured_queue",
        "vhost": "/",
        "durable": true,
        "auto_delete": false,
        "arguments": {
            "x-queue-type": "classic"
        }
    }
],
"exchanges": [
    {
        "name": "externally_configured_exchange",
        "vhost": "/",
        "type": "direct",
        "durable": true,
        "auto_delete": false,
        "internal": false,
        "arguments": {}
    }
],
"bindings": [
    {
        "source": "externally_configured_exchange",
        "vhost": "/",
        "destination": "externally_configured_queue",
        "destination_type": "queue",
        "routing_key": "externally_configured_queue",
        "arguments": {}
    }
  ]
 }

NOTE: After update in rabbit images, additional configuration may be required. If rabbit container failed to start with the configuration mentioned above (error message contains "Exception during startup:
exit:{error,{no_such_vhost,<<"/">>}}") following configuration should be added into definitions file:

 "users": [
    {
      "name": "guest",
      "password_hash": "BMfxN8drrYcIqXZMr+pWTpDT0nMcOagMduLX0bjr4jwud/pN",
      "hashing_algorithm": "rabbit_password_hashing_sha256",
      "tags": [
        "administrator"
      ],
      "limits": {}
    }
  ],
  "vhosts": [
    {
      "name": "/"
    }
  ],
  "permissions": [
    {
      "user": "guest",
      "vhost": "/",
      "configure": ".*",
      "write": ".*",
      "read": ".*"
    }
  ]

Using this additional configuration, default user will be guest with password guest.

Apart from queues, exchanges and bindings, definitions.json file can contain additional configuration


问:
Compilation error: /usr/bin/ld: cannot find -lclntsh
While trying to compile a C program using make file, I am facing the following linking error described below.

I know this kind of issues are already discussed in many other posts, but I tried with solutions suggested in them but they all did not work.

/usr/bin/ld: cannot find -lclntsh

libclntsh.so and libclntsh.so.10.1 are  present in oracle path  /u01/app/oracle/product/10.2.0/lib and that is being given as -L option in make file. Still I am facing the issue:-

```<code>Linking yieldrpt ...
cc -v -g -D_HPUX_SOURCE -DPARETO -Wl,-aarchive -L/u01/app/oracle/product/10.2.0/lib/         yieldrpt.o  -lclntsh `cat /u01/app/oracle/product/10.2.0/lib/ldflags`   -lmalloc -ldl -lm   \
                -lmalloc -o yieldrpt
Using built-in specs.
Target: i386-redhat-linux
Configured with: ../configure --prefix=/usr --mandir=/usr/share/man --infodir=/usr/share/info --enable-shared --enable-threads=posix --enable-checking=release --with-system-zlib --enable-__cxa_atexit --disable-libunwind-exceptions --enable-libgcj-multifile --enable-languages=c,c++,objc,obj-c++,java,fortran,ada --enable-java-awt=gtk --disable-dssi --disable-plugin --with-java-home=/usr/lib/jvm/java-1.4.2-gcj-1.4.2.0/jre --with-cpu=generic --host=i386-redhat-linux
Thread model: posix
gcc version 4.1.2 20080704 (Red Hat 4.1.2-54)
/usr/libexec/gcc/i386-redhat-linux/4.1.2/collect2 --eh-frame-hdr -m elf_i386 --hash-style=gnu -dynamic-linker /lib/ld-linux.so.2 -o yieldrpt /usr/lib/gcc/i386-redhat-linux/4.1.2/../../../crt1.o /usr/lib/gcc/i386-redhat-linux/4.1.2/../../../crti.o /usr/lib/gcc/i386-redhat-linux/4.1.2/crtbegin.o -L/u01/app/oracle/product/10.2.0/lib/ -L/usr/lib/gcc/i386-redhat-linux/4.1.2 -L/usr/lib/gcc/i386-redhat-linux/4.1.2 -L/usr/lib/gcc/i386-redhat-linux/4.1.2/../../.. -aarchive yieldrpt.o -lclntsh -lnbeq10 -lnhost10 -lnus10 -lnldap10 -lldapclnt10 -lnsslb10 -lntcp10 -lntcps10 -lnsslb10 -lntcp10 -lntns10 -lmalloc -ldl -lm -lmalloc -lgcc --as-needed -lgcc_s --no-as-needed -lc -lgcc --as-needed -lgcc_s --no-as-needed /usr/lib/gcc/i386-redhat-linux/4.1.2/crtend.o     /usr/lib/gcc/i386-redhat-linux/4.1.2/../../../crtn.o
/usr/bin/ld: cannot find -lclntsh
collect2: ld returned 1 exit status
make: *** [yieldrpt] Error 1
</code>```

Please let me know if any other info is needed.
Thank you

答:
For me it was /usr/bin/ld: cannot find -lclntshcore. For some reason, the following symlink is missing.

libclntshcore.so -> /home/ubuntu/ora2pg/instantclient_12_2/libclntshcore.so.12.1

Body:
While trying to compile a C program using make file, I am facing the following linking error described below.

I know this kind of issues are already discussed in many other posts, but I tried with solutions suggested in them but they all did not work.

/usr/bin/ld: cannot find -lclntsh

libclntsh.so and libclntsh.so.10.1 are  present in oracle path  /u01/app/oracle/product/10.2.0/lib and that is being given as -L option in make file. Still I am facing the issue:-

Linking yieldrpt ...
cc -v -g -D_HPUX_SOURCE -DPARETO -Wl,-aarchive -L/u01/app/oracle/product/10.2.0/lib/         yieldrpt.o  -lclntsh `cat /u01/app/oracle/product/10.2.0/lib/ldflags`   -lmalloc -ldl -lm   \
                -lmalloc -o yieldrpt
Using built-in specs.
Target: i386-redhat-linux
Configured with: ../configure --prefix=/usr --mandir=/usr/share/man --infodir=/usr/share/info --enable-shared --enable-threads=posix --enable-checking=release --with-system-zlib --enable-__cxa_atexit --disable-libunwind-exceptions --enable-libgcj-multifile --enable-languages=c,c++,objc,obj-c++,java,fortran,ada --enable-java-awt=gtk --disable-dssi --disable-plugin --with-java-home=/usr/lib/jvm/java-1.4.2-gcj-1.4.2.0/jre --with-cpu=generic --host=i386-redhat-linux
Thread model: posix
gcc version 4.1.2 20080704 (Red Hat 4.1.2-54)
/usr/libexec/gcc/i386-redhat-linux/4.1.2/collect2 --eh-frame-hdr -m elf_i386 --hash-style=gnu -dynamic-linker /lib/ld-linux.so.2 -o yieldrpt /usr/lib/gcc/i386-redhat-linux/4.1.2/../../../crt1.o /usr/lib/gcc/i386-redhat-linux/4.1.2/../../../crti.o /usr/lib/gcc/i386-redhat-linux/4.1.2/crtbegin.o -L/u01/app/oracle/product/10.2.0/lib/ -L/usr/lib/gcc/i386-redhat-linux/4.1.2 -L/usr/lib/gcc/i386-redhat-linux/4.1.2 -L/usr/lib/gcc/i386-redhat-linux/4.1.2/../../.. -aarchive yieldrpt.o -lclntsh -lnbeq10 -lnhost10 -lnus10 -lnldap10 -lldapclnt10 -lnsslb10 -lntcp10 -lntcps10 -lnsslb10 -lntcp10 -lntns10 -lmalloc -ldl -lm -lmalloc -lgcc --as-needed -lgcc_s --no-as-needed -lc -lgcc --as-needed -lgcc_s --no-as-needed /usr/lib/gcc/i386-redhat-linux/4.1.2/crtend.o     /usr/lib/gcc/i386-redhat-linux/4.1.2/../../../crtn.o
/usr/bin/ld: cannot find -lclntsh
collect2: ld returned 1 exit status
make: *** [yieldrpt] Error 1

Please let me know if any other info is needed.
Thank you


问:
How to get a previous value after a mongo unwind

Is it possible to access the previous document after an $unwind and then $group them together in the new (cleaned up) object?

Using this Mongo aggregate: mongoplayground.net/p/IsM-h9DnhjJ I would like to get an average of all result stats and scores within a page, then an average of all the pages stats for a site.

Collections

I have three collections that are all related. Site > Page > Result (page result)

// sites
{
  _id: "si-site-a",
  teamId: "te-team-1",
  name: "Site a"
}
```
<pre class="lang-json prettyprint-override"><code>// pages
{
  _id: "pa-page-a",
  teamId: "te-team-1",
  siteId: "si-site-a",
  name: "Page A",
  status: "ok"
},
{
  _id: "pa-page-b",
  teamId: "te-team-1",
  siteId: "si-site-a",
  name: "Page B",
  status: "ok"
}
</code>```

// results
{
  _id: "re-result-1",
  pageId: "pa-page-a",
  siteId: "si-site-a",
  results: {
    scores: {
      performance: 0.75,
      accessibility: 0.98,
      "best-practices": 0.93,
      seo: 1,
      pwa: 0.36,
      ecoscore: 0.94
    },
    stats: {
      transferSize: 876995,
      co2grams: 0.11,
      pageLoadTime: 1722.284
    }
  },
  region: "gb1",
  timestamp: ISODate("2022-02-05T16:38:35.454Z"),
  status: "ok"
}
```
<h2>Desired output</h2>
<pre class="lang-json prettyprint-override"><code>  {
    _id: 'a',
    name: 'Site a',
    pages: [
      {
        _id: 'aa',
        name: 'Page a',
        status: 'ok',
        resultAverages: {
          ecoscore: 0.89,
          transferSize: 556081,
          co2grams: 0.19,
          pageLoadTime: 1011.7159999999999,
        },
      },
    ],
    pageAverages: {
          ecoscore: 0.89,
          transferSize: 556081,
          co2grams: 0.19,
          pageLoadTime: 1011.7159999999999,
    },
    comparedTo: {
          ecoscore: 0.89,
          transferSize: 556081,
          co2grams: 0.19,
          pageLoadTime: 1011.7159999999999,
    },
    percentageChange: {
          ecoscore: 0,
          transferSize: 0,
          co2grams: -0.19,
          pageLoadTime: 0.24,
    },

  },
</code>```

答:
You are actually on the right track of using sub-pipeline. You can compute the avg within result in the sub-pipeline first. Then store them inside individual result. After the sub-pipeline, do another $avg to compute the avg for the previous avg inside result to get the avg for pages.

db.sites.aggregate([
  {
    $lookup: {
      from: "pages",
      localField: "_id",
      foreignField: "siteId",
      as: "pages",
      pipeline: [
        {
          $lookup: {
            from: "result",
            localField: "_id",
            foreignField: "pageId",
            as: "results",
            pipeline: [
              {
                $match: {
                  timestamp: {
                    $gte: ISODate("2022-01-01"),
                    $lte: ISODate("2022-12-01")
                  },
                  status: "ok"
                }
              }
            ]
          }
        },
        {
          $project: {
            _id: 1,
            name: 1,
            status: 1,
            resultAverages: {
              ecoscore: {
                $avg: "$results.results.stats.ecosore"
              },
              transferSize: {
                $avg: "$results.results.stats.transferSize"
              },
              co2grams: {
                $avg: "$results.results.stats.co2grams"
              },
              pageLoadTime: {
                $avg: "$results.results.stats.pageLoadTime"
              }
            }
          }
        }
      ]
    }
  },
  {
    "$addFields": {
      pageAverages: {
        ecoscore: {
          $avg: "$pages.resultAverages.ecosore"
        },
        transferSize: {
          $avg: "$pages.resultAverages.transferSize"
        },
        co2grams: {
          $avg: "$pages.resultAverages.co2grams"
        },
        pageLoadTime: {
          $avg: "$pages.resultAverages.pageLoadTime"
        }
      }
    }
  }
])
```

Here is the Mongo playground for your reference.

Body:
Is it possible to access the previous document after an $unwind and then $group them together in the new (cleaned up) object?

Using this Mongo aggregate: mongoplayground.net/p/IsM-h9DnhjJ I would like to get an average of all result stats and scores within a page, then an average of all the pages stats for a site.

Collections

I have three collections that are all related. Site > Page > Result (page result)

// sites
{
  _id: "si-site-a",
  teamId: "te-team-1",
  name: "Site a"
}

// pages
{
  _id: "pa-page-a",
  teamId: "te-team-1",
  siteId: "si-site-a",
  name: "Page A",
  status: "ok"
},
{
  _id: "pa-page-b",
  teamId: "te-team-1",
  siteId: "si-site-a",
  name: "Page B",
  status: "ok"
}

// results
{
  _id: "re-result-1",
  pageId: "pa-page-a",
  siteId: "si-site-a",
  results: {
    scores: {
      performance: 0.75,
      accessibility: 0.98,
      "best-practices": 0.93,
      seo: 1,
      pwa: 0.36,
      ecoscore: 0.94
    },
    stats: {
      transferSize: 876995,
      co2grams: 0.11,
      pageLoadTime: 1722.284
    }
  },
  region: "gb1",
  timestamp: ISODate("2022-02-05T16:38:35.454Z"),
  status: "ok"
}

Desired output

  {
    _id: 'a',
    name: 'Site a',
    pages: [
      {
        _id: 'aa',
        name: 'Page a',
        status: 'ok',
        resultAverages: {
          ecoscore: 0.89,
          transferSize: 556081,
          co2grams: 0.19,
          pageLoadTime: 1011.7159999999999,
        },
      },
    ],
    pageAverages: {
          ecoscore: 0.89,
          transferSize: 556081,
          co2grams: 0.19,
          pageLoadTime: 1011.7159999999999,
    },
    comparedTo: {
          ecoscore: 0.89,
          transferSize: 556081,
          co2grams: 0.19,
          pageLoadTime: 1011.7159999999999,
    },
    percentageChange: {
          ecoscore: 0,
          transferSize: 0,
          co2grams: -0.19,
          pageLoadTime: 0.24,
    },

  },

Body:
You are actually on the right track of using sub-pipeline. You can compute the avg within result in the sub-pipeline first. Then store them inside individual result. After the sub-pipeline, do another $avg to compute the avg for the previous avg inside result to get the avg for pages.

db.sites.aggregate([
  {
    $lookup: {
      from: "pages",
      localField: "_id",
      foreignField: "siteId",
      as: "pages",
      pipeline: [
        {
          $lookup: {
            from: "result",
            localField: "_id",
            foreignField: "pageId",
            as: "results",
            pipeline: [
              {
                $match: {
                  timestamp: {
                    $gte: ISODate("2022-01-01"),
                    $lte: ISODate("2022-12-01")
                  },
                  status: "ok"
                }
              }
            ]
          }
        },
        {
          $project: {
            _id: 1,
            name: 1,
            status: 1,
            resultAverages: {
              ecoscore: {
                $avg: "$results.results.stats.ecosore"
              },
              transferSize: {
                $avg: "$results.results.stats.transferSize"
              },
              co2grams: {
                $avg: "$results.results.stats.co2grams"
              },
              pageLoadTime: {
                $avg: "$results.results.stats.pageLoadTime"
              }
            }
          }
        }
      ]
    }
  },
  {
    "$addFields": {
      pageAverages: {
        ecoscore: {
          $avg: "$pages.resultAverages.ecosore"
        },
        transferSize: {
          $avg: "$pages.resultAverages.transferSize"
        },
        co2grams: {
          $avg: "$pages.resultAverages.co2grams"
        },
        pageLoadTime: {
          $avg: "$pages.resultAverages.pageLoadTime"
        }
      }
    }
  }
])

Here is the Mongo playground for your reference.


问:
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

答:
is it pure luck?

Yes. The lifetime of the object to which the reference refers ends at the } after ref++;.

Trying to read the value of the object after that causes undefined behavior. Undefined behavior means that you have no guarantee how the program will behave, which includes the possibility of it seemingly working, but another run or compilation of the program may give you a different result.

Practically speaking, destroying a int object doesn't require the execution of any machine instructions and if the object has space allocated on the function's stack, there is a good possibility that the value will just be read from the location where the int object was located, with whatever value it had last. The compiler does not need to overwrite it.

But you can see undefined behavior in action if you compile with optimizations enabled. For example GCC 11.2 with -O2 on x86_64 produces the output

```<code>Value is 10
10
</code>```

but without optimization flags it produces

```<code>Value is 10
11
</code>```

(see https://godbolt.org/z/EqKG83c18).

But undefined behavior doesn't just mean that the value printed will be unspecified. The whole program has no behavior guarantees and it could also output nothing or garbage text or anything else.

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

Body:
is it pure luck?

Yes. The lifetime of the object to which the reference refers ends at the } after ref++;.

Trying to read the value of the object after that causes undefined behavior. Undefined behavior means that you have no guarantee how the program will behave, which includes the possibility of it seemingly working, but another run or compilation of the program may give you a different result.

Practically speaking, destroying a int object doesn't require the execution of any machine instructions and if the object has space allocated on the function's stack, there is a good possibility that the value will just be read from the location where the int object was located, with whatever value it had last. The compiler does not need to overwrite it.

But you can see undefined behavior in action if you compile with optimizations enabled. For example GCC 11.2 with -O2 on x86_64 produces the output

Value is 10
10

but without optimization flags it produces

Value is 10
11

(see https://godbolt.org/z/EqKG83c18).

But undefined behavior doesn't just mean that the value printed will be unspecified. The whole program has no behavior guarantees and it could also output nothing or garbage text or anything else.