问:
String manipulation, removing a single comma
UPDATE 1:

This is how I am attempting to build the string:

```<code>header('Content-type:application/json');

function getdata($the_query)
{
    $connection = mysql_connect('server', 'user', 'pass') or die (mysql_error());
    $db = mysql_select_db('db_name', $connection) or die (mysql_error());

    $results = mysql_query($the_query) or die(mysql_error());

    $the_data = "{
            \"rss\": {
                \"channels\" : [
                    {
                        \"title\" : \"".$title."\",
                        \"link\": \"http://www.mycompany.com/external.php\",
                        \"description\": \"company description goes here\",";

                        while($row = mysql_fetch_array($results))
                        {
                            extract($row);

                            $the_data .= "\"items\" : [
                                {
                                    \"title\": \"".$title."\",
                                    \"link\": \"".$link."\",
                                    \"guid\": \"".$link."\",
                                    \"pubDate\": \"".$date."\",
                                    \"description\": \"".$description."\"
                                } ],";
                        }

                    $the_data .= "} ]
                }
                 }";

    mysql_close($connection);

    return $the_data;
}
</code>```

ORIGINAL QUESTION:

I have a string similar to this:

```<code>$mystring = "{
      \"rss\": {
        \"channels\" : [
          {
            \"title" : \"title goes here\",
            \"link": \"link goes here\",
            \"description": \"description goes here\",
            \"items\" : [
              {
                \"title\": \"title goes here\",
                \"link\": \"url goes here\",
                \"guid\": \"id goes here\",
                \"pubDate\": \"data goes her\",
                \"description\": \"description goes here\"
              } ],
            \"items\" : [
              {
                \"title\": \"title goes here\",
                \"link\": \"url goes here\",
                \"guid\": \"id goes here\",
                \"pubDate\": \"data goes her\",
                \"description\": \"description goes here\"
              } ],
            \"items\" : [
              {
                \"title\": \"title goes here\",
                \"link\": \"url goes here\",
                \"guid\": \"id goes here\",
                \"pubDate\": \"data goes her\",
                \"description\": \"description goes here\"
              } ],
         } ]
      }
    }";
</code>```

How do I remove the last comma?

答:
I would try and make it correct when you generate it.

I am doing it the only way I know, i.e. adding to a string using .= then looping through a database to get the bit which loops

from this comment it looks like you are just building the string yourself.

While in your loop, check which element in the array you are on and don't add the comma (forgive pseudocode nature of example)

```<code>$string .= item[i];
if($iterator < ($numberofitems-1){$string .=",";}
</code>```

Obviously in your example above you will need to get the number of rows returned and check whether there are more to come on each loop.

Saying that, I would favour building the json with http://www.php.net/manual/en/function.json-encode.php

Body:
UPDATE 1:

This is how I am attempting to build the string:

header('Content-type:application/json');

function getdata($the_query)
{
    $connection = mysql_connect('server', 'user', 'pass') or die (mysql_error());
    $db = mysql_select_db('db_name', $connection) or die (mysql_error());

    $results = mysql_query($the_query) or die(mysql_error());

    $the_data = "{
            \"rss\": {
                \"channels\" : [
                    {
                        \"title\" : \"".$title."\",
                        \"link\": \"http://www.mycompany.com/external.php\",
                        \"description\": \"company description goes here\",";

                        while($row = mysql_fetch_array($results))
                        {
                            extract($row);

                            $the_data .= "\"items\" : [
                                {
                                    \"title\": \"".$title."\",
                                    \"link\": \"".$link."\",
                                    \"guid\": \"".$link."\",
                                    \"pubDate\": \"".$date."\",
                                    \"description\": \"".$description."\"
                                } ],";
                        }

                    $the_data .= "} ]
                }
                 }";

    mysql_close($connection);

    return $the_data;
}

ORIGINAL QUESTION:

I have a string similar to this:

$mystring = "{
      \"rss\": {
        \"channels\" : [
          {
            \"title" : \"title goes here\",
            \"link": \"link goes here\",
            \"description": \"description goes here\",
            \"items\" : [
              {
                \"title\": \"title goes here\",
                \"link\": \"url goes here\",
                \"guid\": \"id goes here\",
                \"pubDate\": \"data goes her\",
                \"description\": \"description goes here\"
              } ],
            \"items\" : [
              {
                \"title\": \"title goes here\",
                \"link\": \"url goes here\",
                \"guid\": \"id goes here\",
                \"pubDate\": \"data goes her\",
                \"description\": \"description goes here\"
              } ],
            \"items\" : [
              {
                \"title\": \"title goes here\",
                \"link\": \"url goes here\",
                \"guid\": \"id goes here\",
                \"pubDate\": \"data goes her\",
                \"description\": \"description goes here\"
              } ],
         } ]
      }
    }";

How do I remove the last comma?

Body:
I would try and make it correct when you generate it.

I am doing it the only way I know, i.e. adding to a string using .= then looping through a database to get the bit which loops

from this comment it looks like you are just building the string yourself.

While in your loop, check which element in the array you are on and don't add the comma (forgive pseudocode nature of example)

$string .= item[i];
if($iterator < ($numberofitems-1){$string .=",";}

Obviously in your example above you will need to get the number of rows returned and check whether there are more to come on each loop.

Saying that, I would favour building the json with http://www.php.net/manual/en/function.json-encode.php


来源: stackexchange

问:
How do I 'cast' someting in TypeScript?
I am new to React/Typescript. I have a function that takes a number and outputs a string, as such:

```<code>const getCurrentLevel = (wordCount: number): Level => {
  if (wordCount <= 3) {
    return 'Low';
  }

  if (wordCount <= 6) {
    return 'Med';
  }

  return 'High';
};
</code>```

I then call this function below:

```<code>let helperLevel = getCurrentLevel(numWords);
</code>```

And pass that to another component:

```<code><helperText level={helperLevel} />
</code>```

All this works fine, but I get a warning on compilation.

```<code>Cannot find name 'Level'.
</code>```

On the line:

```<code>const getCurrentLevel = (wordCount: number): Level => {
</code>```

I'm not sure what this means or now to fix it. As I understand, I must 'cast' this as "Level" as above. But I am not sure how to go about fixing this or what the error means.

Can anyone point me in the right direction?

答:
```<code>type Level = 'Low' | 'Med' | 'High'
</code>```

declare this line.

Added

(wordCount: number): Level => { } means it has one parameter as number type, it returns Level type.
In your case, you return 'High', 'Low' and 'Med' you can declare like above that.

ContentLicense: CC BY-SA 4.0

Title: How do I 'cast' someting in TypeScript?

Body:
I am new to React/Typescript. I have a function that takes a number and outputs a string, as such:

const getCurrentLevel = (wordCount: number): Level => {
  if (wordCount <= 3) {
    return 'Low';
  }

  if (wordCount <= 6) {
    return 'Med';
  }

  return 'High';
};

I then call this function below:

let helperLevel = getCurrentLevel(numWords);

And pass that to another component:

<helperText level={helperLevel} />

All this works fine, but I get a warning on compilation.

Cannot find name 'Level'.

On the line:

const getCurrentLevel = (wordCount: number): Level => {

I'm not sure what this means or now to fix it. As I understand, I must 'cast' this as "Level" as above. But I am not sure how to go about fixing this or what the error means.

Can anyone point me in the right direction?

Body:
type Level = 'Low' | 'Med' | 'High'

declare this line.

Added

(wordCount: number): Level => { } means it has one parameter as number type, it returns Level type.
In your case, you return 'High', 'Low' and 'Med' you can declare like above that.


问:
url parameter for django url pattern is not passed properly
An error occurred for the parameter being passed incorrectly

Is that the action setting is wrong?
Is the url parameter set incorrectly?
and page_user : {{page_user}} category_id : {{category_num}} is printed normally
I'm not sure if it's wrong with the view.

if you kow what is reson thanks for let me know

code:

```<code><form method="post" action={% url "wm:new_comment_for_skilpage" user_name=page_user category_id=category_num %}>{% csrf_token %}
..
</form>

</code>```

and url pattern is this

```<code>path('new_comment_for_skilpage/<str:user_name>/<int:category_id>/' , views.new_comment_for_skilpage, name="new_comment_for_skilpage"),

</code>```

view is this

```<code>def new_comment_for_skilpage(request, pk):

    user_name = request.GET.get('user_name')

    category_id = request.GET.get('category_id')

    if request.method == 'POST':

        comment_form = CommentForm(request.POST)

        if comment_form.is_valid():

            comment = comment_form.save(commit=False)

            comment.author = user_name

            comment.category_id = category_id

            comment.save()

            return redirect('/wm/myshortcut/'+user_name+"/"+category_id)

    else:

        return redirect('/wm/myshortcut/'+user_name+"/"+category_id)

</code>```

error:

```<code>TypeError: new_comment_for_skilpage() got an unexpected keyword argument 'user_name'

</code>```

答:
```<code>def new_comment_for_skilpage(request, user_name, category_id):

    user_name = request.GET.get('user_name')

    category_id = request.GET.get('category_id')

    if request.method == 'POST':

        comment_form = CommentForm(request.POST)

        if comment_form.is_valid():

            comment = comment_form.save(commit=False)

            comment.author = user_name

            comment.category_id = category_id

            comment.save()

            return redirect('/wm/myshortcut/'+user_name+"/"+category_id)

    else:

        return redirect('/wm/myshortcut/'+user_name+"/"+category_id)
</code>```

Body:
An error occurred for the parameter being passed incorrectly

Is that the action setting is wrong?
Is the url parameter set incorrectly?
and page_user : {{page_user}} category_id : {{category_num}} is printed normally
I'm not sure if it's wrong with the view.

if you kow what is reson thanks for let me know

code:

<form method="post" action={% url "wm:new_comment_for_skilpage" user_name=page_user category_id=category_num %}>{% csrf_token %}
..
</form>

and url pattern is this

path('new_comment_for_skilpage/<str:user_name>/<int:category_id>/' , views.new_comment_for_skilpage, name="new_comment_for_skilpage"),

view is this

def new_comment_for_skilpage(request, pk):

    user_name = request.GET.get('user_name')

    category_id = request.GET.get('category_id')

    if request.method == 'POST':

        comment_form = CommentForm(request.POST)

        if comment_form.is_valid():

            comment = comment_form.save(commit=False)

            comment.author = user_name

            comment.category_id = category_id

            comment.save()

            return redirect('/wm/myshortcut/'+user_name+"/"+category_id)

    else:

        return redirect('/wm/myshortcut/'+user_name+"/"+category_id)

error:

TypeError: new_comment_for_skilpage() got an unexpected keyword argument 'user_name'


问:
Could not run jasmine test case in docker container in Jenkins pipeline
I have been trying to run jasmine test for my UI code written in Angular 7 in a docker container which is build on node:10-alpine. I have tried to run installing chromium and puppeteer but I chrome headless seems not have been captured. I am getting below error:

WARN [launcher]: ChromeHeadless have not captured in 210000 ms, killing.

WARN [launcher]: ChromeHeadless was not killed in 2000 ms, sending SIGKILL.
WARN [launcher]: ChromeHeadless was not killed by SIGKILL in 2000 ms, > continuing.
npm ERR! code ELIFECYCLE
npm ERR! errno 1

I have tried below heck also:

increasing captureTimeout and browserNoActivityTimeout

added few more flags other than '--no-sandbox' as below

```<code>customLaunchers:

{
      ChromeHeadlessNoSandbox:{
        base: "ChromeHeadless",
        flags: [
          "--no-sandbox",
          "--no-proxy-server",
          "--disable-web-security",
          "--disable-gpu",
          "--disable-dev-shm-usage",
          '--no-proxy-server',
          '--proxy-bypass-list=*',
          '--window-size=1920,1080',
          '--remote-debugging-port=9222'
        ]
      }
    }
</code>```

I have also added

```<code>process.env.CHROME_BIN = require('puppeteer').executablePath();
</code>```

in karma config

But no luck at all. Could anyone please provide me best resolution? Thanks in advance?

答:
After struggling almost a week, I somehow figured out the fix. With minimal configuration in my customLaunchers with just "--no-sandbox" flag and without puppeteer, I was able to run my jasmine test case in the docker container by setting below environment variables properly:

```<code>CHROME_BIN=/usr/bin/chromium-browser and CHROME_PATH=/usr/lib/chromium/
</code>```

Below is the command I run in my terminal to check if test are executing successfully:

```<code>docker run -e CHROME_BIN=/usr/bin/chromium-browser -e CHROME_PATH=/usr/lib/chromium/ -v path-to-project:/usr/src/app -w /usr/src/app dockerImage sh -c "apk add chromium && npm install && npm rebuild node-sass && npm run test:ci"
</code>```

In my jenkins file I have added below lines to run the test cases in the Jenkins pipeline:

```<code>withEnv(["CHROME_BIN=/usr/bin/chromium-browser", "CHROME_PATH=/usr/lib/chromium/"]) {
   sh 'apk add chromium && npm install && npm run test:ci && npm run build'
}
</code>```

Body:
I have been trying to run jasmine test for my UI code written in Angular 7 in a docker container which is build on node:10-alpine. I have tried to run installing chromium and puppeteer but I chrome headless seems not have been captured. I am getting below error:

WARN [launcher]: ChromeHeadless have not captured in 210000 ms, killing.

WARN [launcher]: ChromeHeadless was not killed in 2000 ms, sending SIGKILL.
WARN [launcher]: ChromeHeadless was not killed by SIGKILL in 2000 ms, > continuing.
npm ERR! code ELIFECYCLE
npm ERR! errno 1

I have tried below heck also:

increasing captureTimeout and browserNoActivityTimeout

added few more flags other than '--no-sandbox' as below

customLaunchers:

{
      ChromeHeadlessNoSandbox:{
        base: "ChromeHeadless",
        flags: [
          "--no-sandbox",
          "--no-proxy-server",
          "--disable-web-security",
          "--disable-gpu",
          "--disable-dev-shm-usage",
          '--no-proxy-server',
          '--proxy-bypass-list=*',
          '--window-size=1920,1080',
          '--remote-debugging-port=9222'
        ]
      }
    }

I have also added

process.env.CHROME_BIN = require('puppeteer').executablePath();

in karma config

But no luck at all. Could anyone please provide me best resolution? Thanks in advance?

Body:
After struggling almost a week, I somehow figured out the fix. With minimal configuration in my customLaunchers with just "--no-sandbox" flag and without puppeteer, I was able to run my jasmine test case in the docker container by setting below environment variables properly:

CHROME_BIN=/usr/bin/chromium-browser and CHROME_PATH=/usr/lib/chromium/

Below is the command I run in my terminal to check if test are executing successfully:

docker run -e CHROME_BIN=/usr/bin/chromium-browser -e CHROME_PATH=/usr/lib/chromium/ -v path-to-project:/usr/src/app -w /usr/src/app dockerImage sh -c "apk add chromium && npm install && npm rebuild node-sass && npm run test:ci"

In my jenkins file I have added below lines to run the test cases in the Jenkins pipeline:

withEnv(["CHROME_BIN=/usr/bin/chromium-browser", "CHROME_PATH=/usr/lib/chromium/"]) {
   sh 'apk add chromium && npm install && npm run test:ci && npm run build'
}


问:
Else after return from first part of an if statement
The implementation of library's BigInteger.gcd(...) method begins with these statements:

```<code>public BigInteger gcd(BigInteger val) {
    if (val.signum == 0)
        return this.abs();
    else if (this.signum == 0)
        return val.abs();
    ...
}
</code>```

What is the purpose of the else keyword in this case? Is it just a remnant of an old code that the programmer has forgotten to delete or it impacts performance in some way?

I understand that, semantically, the versions with and without else are identical in this particular case. Quite often, however, I face the choice between

```<code><Some method signature>(...) {
    if (...) {
        <Short branch>
        return ...;
    } else {
        <Long branch>
        return ...;
    }
}
</code>```

and

```<code><Some method signature>(...) {
    if (...) {
        <Short branch>
        return ...;
    }
    <Long branch>
    return ...;
}
</code>```

Which option is better in terms of performance (note that this question is Java-specific)? If performance is almost identical in both cases, which one is better in terms of readability?

答:
On my machine, using java 1.8.0_172, the two versions produce identical bytecode. So this is optimized at compile-time itself. The JIT compiler would see the same input in both cases, so the runtime performance will be identical.

Else version:

```<code>public class MyTest {
    public static void main(String[] args) {
        if (args.length > 2) {
                System.out.println("More than 2");
                return;
        } else {
                System.out.println("Hello");
        }
    }
}
</code>```

No-else version:

```<code>public class MyTest {
    public static void main(String[] args) {
        if (args.length > 2) {
                System.out.println("More than 2");
                return;
        }
        System.out.println("Hello");
    }
}
</code>```

Then compile them with java MyTest.java, and then get the bytecode with javap -c MyTest, compare the bytecode from the two sources. They are identical. Both generate the following bytecode:

```<code>Compiled from "MyTest.java"
public class MyTest {
  public MyTest();
    Code:
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: return

  public static void main(java.lang.String[]);
    Code:
       0: aload_0
       1: arraylength
       2: iconst_2
       3: if_icmple     15
       6: getstatic     #2                  // Field java/lang/System.out:Ljava/io/PrintStream;
       9: ldc           #3                  // String More than 2
      11: invokevirtual #4                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V
      14: return
      15: getstatic     #2                  // Field java/lang/System.out:Ljava/io/PrintStream;
      18: ldc           #5                  // String Hello
      20: invokevirtual #4                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V
      23: return
}
</code>```

Now for readability, that is subjective of course. I prefer the version without the unnecessary else.

Body:
The implementation of library's BigInteger.gcd(...) method begins with these statements:

public BigInteger gcd(BigInteger val) {
    if (val.signum == 0)
        return this.abs();
    else if (this.signum == 0)
        return val.abs();
    ...
}

What is the purpose of the else keyword in this case? Is it just a remnant of an old code that the programmer has forgotten to delete or it impacts performance in some way?

I understand that, semantically, the versions with and without else are identical in this particular case. Quite often, however, I face the choice between

<Some method signature>(...) {
    if (...) {
        <Short branch>
        return ...;
    } else {
        <Long branch>
        return ...;
    }
}

and

<Some method signature>(...) {
    if (...) {
        <Short branch>
        return ...;
    }
    <Long branch>
    return ...;
}

Which option is better in terms of performance (note that this question is Java-specific)? If performance is almost identical in both cases, which one is better in terms of readability?

Body:
On my machine, using java 1.8.0_172, the two versions produce identical bytecode. So this is optimized at compile-time itself. The JIT compiler would see the same input in both cases, so the runtime performance will be identical.

Else version:

public class MyTest {
    public static void main(String[] args) {
        if (args.length > 2) {
                System.out.println("More than 2");
                return;
        } else {
                System.out.println("Hello");
        }
    }
}

No-else version:

public class MyTest {
    public static void main(String[] args) {
        if (args.length > 2) {
                System.out.println("More than 2");
                return;
        }
        System.out.println("Hello");
    }
}

Then compile them with java MyTest.java, and then get the bytecode with javap -c MyTest, compare the bytecode from the two sources. They are identical. Both generate the following bytecode:

Compiled from "MyTest.java"
public class MyTest {
  public MyTest();
    Code:
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: return

  public static void main(java.lang.String[]);
    Code:
       0: aload_0
       1: arraylength
       2: iconst_2
       3: if_icmple     15
       6: getstatic     #2                  // Field java/lang/System.out:Ljava/io/PrintStream;
       9: ldc           #3                  // String More than 2
      11: invokevirtual #4                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V
      14: return
      15: getstatic     #2                  // Field java/lang/System.out:Ljava/io/PrintStream;
      18: ldc           #5                  // String Hello
      20: invokevirtual #4                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V
      23: return
}

Now for readability, that is subjective of course. I prefer the version without the unnecessary else.


问:
Is it legal to use \\ in // C++ comment? (LaTeX equation in C++ comment)
For documentation purpose I need to add some LaTeX equations in my C++ comments, by example:

```<code>//
// \begin{eqnarray*}
//   y_1 &=& x_1 \\
//   y_2 &=& x_2
// \end{eqnarray*}
//
int main() {}
</code>```

With clang++ (version 9.0.1-10) I can compile my code without problem:

```<code>clang++ -Wall prog.cpp
</code>```

but with g++ (version 9.2.1)

```<code>g++ -Wall prog.cpp
</code>```

I get this warning:

```<code>prog.cpp:3:1: warning: multi-line comment [-Wcomment]
    3 | //   y_1 &=& x_1 \\
      | ^
</code>```

My question: which compiler is right? Can I legally use \\ inside C++ // comment?

答:
Such comments are legal, but they could have unexpected effects, hence the warning. The next line after the one with the backslash at the end is a continuation of the comment, regardless of the // at the beginning. So this

```<code>// \\
Hey dude!
int main () {}
</code>```

is a valid C++ program. And no, the backslash before the last one does not serve as an escape.

If you want to avoid the warning, put a LaTeX comment in the end of the line:

```<code>// y_1 &=& x_1 \\ % look ma, no warning
</code>```

Note that a simple space between the backslash and the newline doesn't necessarily fix the problem. GCC documentation says:

If there is white space between a backslash and the end of a line, that is still a continued line. However, as this is usually the result of an editing mistake, and many compilers will not accept it as a continued line, GCC will warn you about it.

Body:
For documentation purpose I need to add some LaTeX equations in my C++ comments, by example:

//
// \begin{eqnarray*}
//   y_1 &=& x_1 \\
//   y_2 &=& x_2
// \end{eqnarray*}
//
int main() {}

With clang++ (version 9.0.1-10) I can compile my code without problem:

clang++ -Wall prog.cpp

but with g++ (version 9.2.1)

g++ -Wall prog.cpp

I get this warning:

prog.cpp:3:1: warning: multi-line comment [-Wcomment]
    3 | //   y_1 &=& x_1 \\
      | ^

My question: which compiler is right? Can I legally use \\ inside C++ // comment?

Body:
Such comments are legal, but they could have unexpected effects, hence the warning. The next line after the one with the backslash at the end is a continuation of the comment, regardless of the // at the beginning. So this

// \\
Hey dude!
int main () {}

is a valid C++ program. And no, the backslash before the last one does not serve as an escape.

If you want to avoid the warning, put a LaTeX comment in the end of the line:

// y_1 &=& x_1 \\ % look ma, no warning

Note that a simple space between the backslash and the newline doesn't necessarily fix the problem. GCC documentation says:

If there is white space between a backslash and the end of a line, that is still a continued line. However, as this is usually the result of an editing mistake, and many compilers will not accept it as a continued line, GCC will warn you about it.


问:
How to session manually in a java project that connects to a JMS MQ with xml as payload and gets the response from the remote jms endpoint
I have been searching for Java code to send an XML payload to the JMS endpiont and also receive the response in XML format only. Everyone is writing the producer and consumer but nobody is giving code for existing jms endpoint with payload.

Plug In- Tibco EMS

```<code>Connection factory – com.tibco.tibjms.TibjmsConnectonfactory
Server URL - tcp://10.xxx.xx.xx:69999
User name – scott
Password - tiger
</code>```

XML payload:

<?xml version="1.0" encoding="UTF-8"?>
<MYServices>

        <version>1.0</version>

        <srv_req>
            <req_due_amount>
                <card_no>blablanumber</card_no>
            </req_due_amount>
        </srv_req>

</MYServices>
```

<p>JMS endpoint</p>

```jms://session_name::queue_name::request_topic
```

答:
```<code>    import javax.jms.*;
    import java.util.Enumeration;

    public class JMSExample{

protected static final String SERVICE_QUEUE = "QUEUE_NAME_THAT_IS_CREDTED_IN_SERVER_FOR_ACCEPTING";
static String serverUrl = "tcp://10.xxx.xxx.xxx:xxxxx";
static String userName = "UR_UserID";
static String password = "UR_Pass";

public static void sendTopicMessage(String topicName, String messageStr) {

    Connection connection = null;
    Session session = null;
    MessageProducer msgProducer = null;
    Destination destination = null;

    try {
        TextMessage msg;
        System.out.println("Publishing to destination '" + topicName
                + "'\n");
        ConnectionFactory factory = new com.tibco.tibjms.TibjmsConnectionFactory(serverUrl);
        connection = factory.createConnection(userName, password);
        connection.start();
        session = connection
                .createSession(false,javax.jms.Session.AUTO_ACKNOWLEDGE);
        TemporaryQueue tempQueue = session.createTemporaryQueue();

        TextMessage message_t = session.createTextMessage(messageStr);
        //This step is compulsory to get the reply from JMS server
        message_t.setJMSReplyTo(tempQueue);
        MessageProducer producer = session.createProducer(session.createQueue(SERVICE_QUEUE));
        producer.send(message_t);

        System.out.println("INFO::  The producer has sent the message"+message_t);
        Destination dest = tempQueue;

        MessageConsumer consumer = session.createConsumer(dest);
        Message replyMsg = consumer.receive();
        TextMessage tm = (TextMessage) replyMsg;
        System.out.println("INFO The response is "+ replyMsg);
        consumer.close();
        producer.close();
        session.close();
        connection.close();

    } catch (JMSException e) {
         System.out.println("Error :: there was exception"+e);
        e.printStackTrace();
    }
}

/*-----------------------------------------------------------------------
 * main
 *----------------------------------------------------------------------*/
public static void main(String[] args) {
    JMSExample5.sendTopicMessage(SERVICE_QUEUE,
            "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n" +
                    "<MYServices>\n" +
                    " <header>\n" +
                    "  <Version>1.0</Version>\n" +
                    "  <SrvType>OML</SrvType>\n" +
                    "  <SrvName>REQ_BALANCE_ENQUIRY</SrvName>\n" +
                    "  <SrcApp>BNK</SrcApp>\n" +
                    "  <OrgId>BLA</OrgId>\n" +
                    " </header>\n" +
                    " <body>\n" +
                    "  <srv_req>\n" +
                    "   <req_credit_card_balance_enquiry>\n" +
                    "    <card_no>12345678</card_no>\n" +
                    "   </req_credit_card_balance_enquiry>\n" +
                    "  </srv_req>\n" +
                    " </body>\n" +
                    "</MYServices>\n");
}
</code>```

<p>}</p>

Body:
I have been searching for Java code to send an XML payload to the JMS endpiont and also receive the response in XML format only. Everyone is writing the producer and consumer but nobody is giving code for existing jms endpoint with payload.

Plug In- Tibco EMS

Connection factory – com.tibco.tibjms.TibjmsConnectonfactory
Server URL - tcp://10.xxx.xx.xx:69999
User name – scott
Password - tiger

XML payload:

<?xml version="1.0" encoding="UTF-8"?>
<MYServices>

        <version>1.0</version>

        <srv_req>
            <req_due_amount>
                <card_no>blablanumber</card_no>
            </req_due_amount>
        </srv_req>

</MYServices>

JMS endpoint

jms://session_name::queue_name::request_topic

Body:
    import javax.jms.*;
    import java.util.Enumeration;

    public class JMSExample{

protected static final String SERVICE_QUEUE = "QUEUE_NAME_THAT_IS_CREDTED_IN_SERVER_FOR_ACCEPTING";
static String serverUrl = "tcp://10.xxx.xxx.xxx:xxxxx";
static String userName = "UR_UserID";
static String password = "UR_Pass";

public static void sendTopicMessage(String topicName, String messageStr) {

    Connection connection = null;
    Session session = null;
    MessageProducer msgProducer = null;
    Destination destination = null;

    try {
        TextMessage msg;
        System.out.println("Publishing to destination '" + topicName
                + "'\n");
        ConnectionFactory factory = new com.tibco.tibjms.TibjmsConnectionFactory(serverUrl);
        connection = factory.createConnection(userName, password);
        connection.start();
        session = connection
                .createSession(false,javax.jms.Session.AUTO_ACKNOWLEDGE);
        TemporaryQueue tempQueue = session.createTemporaryQueue();

        TextMessage message_t = session.createTextMessage(messageStr);
        //This step is compulsory to get the reply from JMS server
        message_t.setJMSReplyTo(tempQueue);
        MessageProducer producer = session.createProducer(session.createQueue(SERVICE_QUEUE));
        producer.send(message_t);

        System.out.println("INFO::  The producer has sent the message"+message_t);
        Destination dest = tempQueue;

        MessageConsumer consumer = session.createConsumer(dest);
        Message replyMsg = consumer.receive();
        TextMessage tm = (TextMessage) replyMsg;
        System.out.println("INFO The response is "+ replyMsg);
        consumer.close();
        producer.close();
        session.close();
        connection.close();

    } catch (JMSException e) {
         System.out.println("Error :: there was exception"+e);
        e.printStackTrace();
    }
}

/*-----------------------------------------------------------------------
 * main
 *----------------------------------------------------------------------*/
public static void main(String[] args) {
    JMSExample5.sendTopicMessage(SERVICE_QUEUE,
            "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n" +
                    "<MYServices>\n" +
                    " <header>\n" +
                    "  <Version>1.0</Version>\n" +
                    "  <SrvType>OML</SrvType>\n" +
                    "  <SrvName>REQ_BALANCE_ENQUIRY</SrvName>\n" +
                    "  <SrcApp>BNK</SrcApp>\n" +
                    "  <OrgId>BLA</OrgId>\n" +
                    " </header>\n" +
                    " <body>\n" +
                    "  <srv_req>\n" +
                    "   <req_credit_card_balance_enquiry>\n" +
                    "    <card_no>12345678</card_no>\n" +
                    "   </req_credit_card_balance_enquiry>\n" +
                    "  </srv_req>\n" +
                    " </body>\n" +
                    "</MYServices>\n");
}

}


问:
How to reduce a string containing the same substring repeated n times to a single instace of the substring
I have strings like 'ageage' or 'feetfeetfeet' or 'cmcmcmcmcm' and would like to reduce these to 'age', 'feet', and 'cm' respectively.

This is an intermediate step in normalization for matching across different data sources of certain classes of data fields that originally also contained numbers. The numeric parts have been removed into a separate string. All the unicode letters have been transliterated to  lowercase ASCII letters with:

public static function transliterate(string $value)
{
    $transliterator = Transliterator::createFromRules(
        ':: Any-Latin; :: Latin-ASCII; :: NFD; :: [:Nonspacing Mark:] Remove; :: Lower(); :: NFC;',
        Transliterator::FORWARD
    );
    return $transliterator->transliterate($value);
}
```

Also note that pluralization doesn't matter because while the examples I've provided are in English the project is normalizing mainly Turkish strings where such words would always be singular.

I expect this can be done with regex. Though I'm not entirely sure how

答:
This looks similar to finding longest common prefix which is also a suffix. Now, the length - longest prefix which is also a suffix is your answer. You can find the algorithm of building the prefix suffix table from this KMP pattern matching algorithm.

Time complexity is O(n) and space complexity is O(n).

Snippet:

```<code><?php

$str = "feetfeetfeet";
$length = strlen($str);

$prefix_suffix_table = array_fill(0, $length, 0);

$j = 0;
for($i = 1; $i < $length; ++$i){
    while($j > 0 && $str[$i] != $str[$j]){
        $j = $prefix_suffix_table[$j - 1];
    }

    if($str[$i] == $str[$j]){
        $prefix_suffix_table[$i] = ++$j;
    }
}

echo substr($str, 0, $length - end($prefix_suffix_table));
</code>```

Demo: http://sandbox.onlinephpfunctions.com/code/b401c75cde38a51a561b53bb0a6294eb615b208c

Note: If your string is malformed like xyz which doesn't have a repeating substring, you can just add an additional check using str_repeat() and throw an exception if required.

Body:
I have strings like 'ageage' or 'feetfeetfeet' or 'cmcmcmcmcm' and would like to reduce these to 'age', 'feet', and 'cm' respectively.

This is an intermediate step in normalization for matching across different data sources of certain classes of data fields that originally also contained numbers. The numeric parts have been removed into a separate string. All the unicode letters have been transliterated to  lowercase ASCII letters with:

public static function transliterate(string $value)
{
    $transliterator = Transliterator::createFromRules(
        ':: Any-Latin; :: Latin-ASCII; :: NFD; :: [:Nonspacing Mark:] Remove; :: Lower(); :: NFC;',
        Transliterator::FORWARD
    );
    return $transliterator->transliterate($value);
}

Also note that pluralization doesn't matter because while the examples I've provided are in English the project is normalizing mainly Turkish strings where such words would always be singular.

I expect this can be done with regex. Though I'm not entirely sure how

Body:
This looks similar to finding longest common prefix which is also a suffix. Now, the length - longest prefix which is also a suffix is your answer. You can find the algorithm of building the prefix suffix table from this KMP pattern matching algorithm.

Time complexity is O(n) and space complexity is O(n).

Snippet:

<?php

$str = "feetfeetfeet";
$length = strlen($str);

$prefix_suffix_table = array_fill(0, $length, 0);

$j = 0;
for($i = 1; $i < $length; ++$i){
    while($j > 0 && $str[$i] != $str[$j]){
        $j = $prefix_suffix_table[$j - 1];
    }

    if($str[$i] == $str[$j]){
        $prefix_suffix_table[$i] = ++$j;
    }
}

echo substr($str, 0, $length - end($prefix_suffix_table));

Demo: http://sandbox.onlinephpfunctions.com/code/b401c75cde38a51a561b53bb0a6294eb615b208c

Note: If your string is malformed like xyz which doesn't have a repeating substring, you can just add an additional check using str_repeat() and throw an exception if required.


问:
Azure How can I call Azure Private Endpoint (Azure Private Link service) by private IP inside of VNET
I created VNET in Azure. I put in one subset Azure Private Link which calls Azure Function outside of the VNET and in another one Virtual machine.
 When I tried to call private endpoint by private IP I got a 400 exception. And if I try to ping private IP from the VM it doest work.

But by URL it works well.

 Is it any way to call it by IP?

答:
I also face the same scenario and it seems it's expected behavior.

First of all, instead of Ping tool(using ICMP protocol) inside Azure VM, you could use PsPing tool(using TCP protocol) to test the networking connectivity.

It indicates the Azure function with port 443 with private endpoint is open and should be abled to accepted connection.

Azure function on Azure app service plan is multi-tenant, the same IP address is used for many web apps. Thus, we can not call each instance with it's IP address via the web browser. If you would like to call it with private IP, as a workaround, you could call it by Postman tool with adding your azure function host as the picture displayed.


问:
Radio button in ASP.net Core web application
I am trying to learn ASP.net Core (pretty new) and I am trying something like the below scenario.

Having multiple choice options (want to have radio buttons, option to select one for each section)
there can be only one right choice.
When we click submit after selecting one radio button per selection, I need to highlight the correct selections in green and incorrect in red.

I want to have an OnClick which would determine by some name or value which is correct on click and perform this action. I have checked a couple of options but they don't have all these combinations working correctly.

Please suggest the best options using ASP.net Core web application to perform this functionality.

答:
As others said, you can use jquery to complete.

Since you mentioned how to implement in core, I guess that your data comes from the model in the code behind, right?

So in my example, I use the model to pass the serial number of questions' index, option and correct answer.

Here is my code:

```<code>public class Question
    {
        public int QuestionNumber { set; get; }
        public IEnumerable<QuestionOption> Options { set; get; }
        public int RightAnswer { set; get; }
    }

    public class QuestionOption
    {
        public int Index { set; get; }
        public string Option { set; get; }

    }
</code>```

Controller:

```<code>  public IActionResult Index()
        {
            List<Question> questions = new List<Question>()
            {
                 new  Question(){
                  QuestionNumber=1, Options= new List<QuestionOption> {
                   new QuestionOption(){  Index=1, Option="A"},
                   new QuestionOption(){  Index=2, Option="B"},
                   new QuestionOption(){  Index=3, Option="C"},
                  },
                   RightAnswer = 2
                 },
                 new  Question(){
                  QuestionNumber=2, Options= new List<QuestionOption> {
                   new QuestionOption(){  Index=1, Option="Kity"},
                   new QuestionOption(){  Index=2, Option="Lily"},
                   new QuestionOption(){  Index=3, Option="Jack"},
                  },
                   RightAnswer = 1
                 },
                  new  Question(){
                  QuestionNumber=3, Options= new List<QuestionOption> {
                   new QuestionOption(){  Index=1, Option="FF"},
                   new QuestionOption(){  Index=2, Option="LL"},
                   new QuestionOption(){  Index=3, Option="OO"},
                  },
                   RightAnswer = 3
                 },
            };
            return View(questions);
        }
</code>```

Index:

```<code>@model IEnumerable<WebApplication_core_mvc.Models.Question>
@{
    ViewData["Title"] = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

@section Scripts{

    <script>

        function CheckAnswer() {
    var myArray = [];
    @foreach (var d in Model)
    {
        @:myArray.push("@d.QuestionNumber");
    }
            for (var i = 0; i < myArray.length; i++) {
                var right = $("input[type='hidden'][name=" + myArray[i] + "]").val();
                $("input[type='radio'][name=" + myArray[i] + "]").parent().removeClass("right");
                $("input[type='radio'][name=" + myArray[i] + "]").parent().removeClass("wrong");
                $("input[type='radio'][name=" + myArray[i] + "]").each(function () {
                    if ($(this).is(":checked")) {
                        if ($(this).val() == right) {
                            $(this).parent().addClass("right")
                        } else {
                            $(this).parent().addClass("wrong");
                        }
                    }
                });
            }

    }
    </script>

}

<style>
    .right {
        background-color: green;
    }

    .wrong {
        background-color: red;
    }
</style>

<p>Select an answer: </p>

@foreach (var item in Model)
{
    <div class="row">
        <label>Question @item.QuestionNumber :</label>
        <div class="col-md-10">
            @foreach (var option in item.Options)
            {
                <input type="radio" value="@option.Index" name="@item.QuestionNumber" /> @option.Option
            }
            <input type="hidden" value="@item.RightAnswer" name="@item.QuestionNumber" />
        </div>
    </div>
}

<input type="button" value="Check" onclick="CheckAnswer()" />
</code>```

Here is the test result:

Body:
As others said, you can use jquery to complete.

Since you mentioned how to implement in core, I guess that your data comes from the model in the code behind, right?

So in my example, I use the model to pass the serial number of questions' index, option and correct answer.

Here is my code:

public class Question
    {
        public int QuestionNumber { set; get; }
        public IEnumerable<QuestionOption> Options { set; get; }
        public int RightAnswer { set; get; }
    }

    public class QuestionOption
    {
        public int Index { set; get; }
        public string Option { set; get; }

    }

Controller:

  public IActionResult Index()
        {
            List<Question> questions = new List<Question>()
            {
                 new  Question(){
                  QuestionNumber=1, Options= new List<QuestionOption> {
                   new QuestionOption(){  Index=1, Option="A"},
                   new QuestionOption(){  Index=2, Option="B"},
                   new QuestionOption(){  Index=3, Option="C"},
                  },
                   RightAnswer = 2
                 },
                 new  Question(){
                  QuestionNumber=2, Options= new List<QuestionOption> {
                   new QuestionOption(){  Index=1, Option="Kity"},
                   new QuestionOption(){  Index=2, Option="Lily"},
                   new QuestionOption(){  Index=3, Option="Jack"},
                  },
                   RightAnswer = 1
                 },
                  new  Question(){
                  QuestionNumber=3, Options= new List<QuestionOption> {
                   new QuestionOption(){  Index=1, Option="FF"},
                   new QuestionOption(){  Index=2, Option="LL"},
                   new QuestionOption(){  Index=3, Option="OO"},
                  },
                   RightAnswer = 3
                 },
            };
            return View(questions);
        }

Index:

@model IEnumerable<WebApplication_core_mvc.Models.Question>
@{
    ViewData["Title"] = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

@section Scripts{

    <script>

        function CheckAnswer() {
    var myArray = [];
    @foreach (var d in Model)
    {
        @:myArray.push("@d.QuestionNumber");
    }
            for (var i = 0; i < myArray.length; i++) {
                var right = $("input[type='hidden'][name=" + myArray[i] + "]").val();
                $("input[type='radio'][name=" + myArray[i] + "]").parent().removeClass("right");
                $("input[type='radio'][name=" + myArray[i] + "]").parent().removeClass("wrong");
                $("input[type='radio'][name=" + myArray[i] + "]").each(function () {
                    if ($(this).is(":checked")) {
                        if ($(this).val() == right) {
                            $(this).parent().addClass("right")
                        } else {
                            $(this).parent().addClass("wrong");
                        }
                    }
                });
            }

    }
    </script>

}

<style>
    .right {
        background-color: green;
    }

    .wrong {
        background-color: red;
    }
</style>

<p>Select an answer: </p>

@foreach (var item in Model)
{
    <div class="row">
        <label>Question @item.QuestionNumber :</label>
        <div class="col-md-10">
            @foreach (var option in item.Options)
            {
                <input type="radio" value="@option.Index" name="@item.QuestionNumber" /> @option.Option
            }
            <input type="hidden" value="@item.RightAnswer" name="@item.QuestionNumber" />
        </div>
    </div>
}

<input type="button" value="Check" onclick="CheckAnswer()" />

Here is the test result:


问:
Can an Activity access a Fragment to know if a button has been pressed?
The Objective: I'm trying to make a notepad application. What my app does is, a button is pressed to create a new note. This pops up a fragment in which the user types his note. Within the same fragment, I have another button that signifies when the user is done typing.

Question 1: Is there a way by which pressing the other button in the Fragment could trigger a method in my Activity?

Question 2: Would this cause the app to become too bloated? Should I keep the button within my activity itself?

Thank you for your help.

答:
Question 1: Is there a way by which pressing the other button in the Fragment could trigger a method in my Activity?

Sure, the simplest way to do it is:

```<code>override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    val binding = MyFragmentBinding.bind(view) // viewBinding enabled

    binding.myButton.setOnClickListener {
        (requireActivity() as MyActivity).doSomething() // <--
    }
}
</code>```

However, if this Fragment can be used in different Activity instances, then it should expose a Listener with which it exposes its potential events, and doesn't need to know the actual Activity instance it is talking to.

```<code>interface ActionHandler {
    fun onMyButtonClicked()
}

lateinit var actionHandler: ActionHandler

override fun onAttach(context: Context) {
    super.onAttach(context)
    actionHandler = context as ActionHandler
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    val binding = MyFragmentBinding.bind(view) // viewBinding enabled

    binding.myButton.setOnClickListener {
        actionHandler.onMyButtonClicked()
    }
}
</code>```

This way, your Fragment will always have a listener to talk to even after config changes / process death, which seems to not be the case for most other answers here.

Question 2: Would this cause the app to become too bloated? Should I keep the button within my activity itself?

This depends on whether the button actually belongs in the Activity, though it probably doesn't. Most modern apps are written as single-Activity anyway, and unless the view is shared among all screens, it's put inside a Fragment, possibly maybe even using <include tags from a common layout resource.

Body:
Question 1: Is there a way by which pressing the other button in the Fragment could trigger a method in my Activity?

Sure, the simplest way to do it is:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    val binding = MyFragmentBinding.bind(view) // viewBinding enabled

    binding.myButton.setOnClickListener {
        (requireActivity() as MyActivity).doSomething() // <--
    }
}

However, if this Fragment can be used in different Activity instances, then it should expose a Listener with which it exposes its potential events, and doesn't need to know the actual Activity instance it is talking to.

interface ActionHandler {
    fun onMyButtonClicked()
}

lateinit var actionHandler: ActionHandler

override fun onAttach(context: Context) {
    super.onAttach(context)
    actionHandler = context as ActionHandler
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    val binding = MyFragmentBinding.bind(view) // viewBinding enabled

    binding.myButton.setOnClickListener {
        actionHandler.onMyButtonClicked()
    }
}

This way, your Fragment will always have a listener to talk to even after config changes / process death, which seems to not be the case for most other answers here.

Question 2: Would this cause the app to become too bloated? Should I keep the button within my activity itself?

This depends on whether the button actually belongs in the Activity, though it probably doesn't. Most modern apps are written as single-Activity anyway, and unless the view is shared among all screens, it's put inside a Fragment, possibly maybe even using <include tags from a common layout resource.


问:
(intermediate value)}.then is not a function
I am trying to generate a backup from my REST API made with node js, but when trying to execute the code that generates the backup file, it throws me that it is not a function .then(dump => { fs.writeFileSync, this is the code with the error

var mysqlDump = require('mysqldump');
var fs = require('fs');

const dump = mysqlDump({
    host: 'localhost',
    user: 'root',
    password: '',
    database: 'demo',
    tables:['sales_orders'], // only these tables
   // where: {'estado': 'id < 1000'}, // Only test players with id < 1000
    //ifNotExist:true, // Create table if not exist
}.then(dump => {
    fs.writeFileSync('test.sql', dump); // Create data.sql file with dump result

}));

module.exports = dump;```

答:
You have a closing ')' at the wrong place:

Your Code

```<code>var mysqlDump = require('mysqldump');
var fs = require('fs');

const dump = mysqlDump({
    host: 'localhost',
    user: 'root',
    password: '',
    database: 'demo',
    tables:['sales_orders'], // only these tables
   // where: {'estado': 'id < 1000'}, // Only test players with id < 1000
    //ifNotExist:true, // Create table if not exist
}.then(dump => {     //missing at this line
    fs.writeFileSync('test.sql', dump); // Create data.sql file with dump result

}));                 //extra at this line

module.exports = dump;
</code>```

Corrected code block

```<code>var mysqlDump = require('mysqldump');
var fs = require('fs');

const dump = mysqlDump({
    host: 'localhost',
    user: 'root',
    password: '',
    database: 'demo',
    tables:['sales_orders'], // only these tables
   // where: {'estado': 'id < 1000'}, // Only test players with id < 1000
    //ifNotExist:true, // Create table if not exist
}).then(dump => {
    fs.writeFileSync('test.sql', dump); // Create data.sql file with dump result

});

module.exports = dump;
</code>```

To avoid this type of problems, use VS code with linting extentions to highlight code inconsistencies.

Body:
You have a closing ')' at the wrong place:

Your Code

var mysqlDump = require('mysqldump');
var fs = require('fs');

const dump = mysqlDump({
    host: 'localhost',
    user: 'root',
    password: '',
    database: 'demo',
    tables:['sales_orders'], // only these tables
   // where: {'estado': 'id < 1000'}, // Only test players with id < 1000
    //ifNotExist:true, // Create table if not exist
}.then(dump => {     //missing at this line
    fs.writeFileSync('test.sql', dump); // Create data.sql file with dump result

}));                 //extra at this line

module.exports = dump;

Corrected code block

var mysqlDump = require('mysqldump');
var fs = require('fs');

const dump = mysqlDump({
    host: 'localhost',
    user: 'root',
    password: '',
    database: 'demo',
    tables:['sales_orders'], // only these tables
   // where: {'estado': 'id < 1000'}, // Only test players with id < 1000
    //ifNotExist:true, // Create table if not exist
}).then(dump => {
    fs.writeFileSync('test.sql', dump); // Create data.sql file with dump result

});

module.exports = dump;

To avoid this type of problems, use VS code with linting extentions to highlight code inconsistencies.


问:
Calling helper function to reverse lists, then zipping lists in Haskell
I'm new to Haskell and I've been trying for hours to get these two functions to work together to produce a zipped reverse list using recursion and without built-in functions.

Here's the helper function to reverse the lists:

```<code>reverseList :: [x] -> [x]
reverseList  [] = []
reverseList  xs = last xs : reverseList (init xs)
</code>```

Then here's the zipper function

```<code>ZipRevLists2 :: [x] -> [y] -> [(x, y)]
ZipRevLists2 _ [] = []
ZipRevLists2 [] _ = []
ZipRevLists2 (x:xs) = reverseList xs
ZipRevLists2 (y:ys) = reverseList ys
ZipRevLists2 (x:xs) (y:ys) = (x,y) : ZipRev2Lists xs ys
</code>```

I'm trying to learn from learnyouahaskell.com but the only examples are in "ghci>" and not really function form.

答:
Thanks, I finally got it!

The Zip function

```<code>zip' :: [x] -> [y] -> [(x,y)]
zip' _ [] = []
zip' [] _ = []
zip' (x:xs) (y:ys) = (x,y):zip' xs ys
</code>```

and the main function

```<code>zipRevLists2 :: [Int] -> [Char] -> [(Int,Char)]
zipRevLists2 _ [] = []
zipRevLists2 [] _ = []
zipRevLists2 (x:xs) (y:ys) = zip' (reverseList (x:xs))  (reverseList (y:ys))
</code>```

Body:
I'm new to Haskell and I've been trying for hours to get these two functions to work together to produce a zipped reverse list using recursion and without built-in functions.

Here's the helper function to reverse the lists:

reverseList :: [x] -> [x]
reverseList  [] = []
reverseList  xs = last xs : reverseList (init xs)

Then here's the zipper function

ZipRevLists2 :: [x] -> [y] -> [(x, y)]
ZipRevLists2 _ [] = []
ZipRevLists2 [] _ = []
ZipRevLists2 (x:xs) = reverseList xs
ZipRevLists2 (y:ys) = reverseList ys
ZipRevLists2 (x:xs) (y:ys) = (x,y) : ZipRev2Lists xs ys

I'm trying to learn from learnyouahaskell.com but the only examples are in "ghci>" and not really function form.

Body:
Thanks, I finally got it!

The Zip function

zip' :: [x] -> [y] -> [(x,y)]
zip' _ [] = []
zip' [] _ = []
zip' (x:xs) (y:ys) = (x,y):zip' xs ys

and the main function

zipRevLists2 :: [Int] -> [Char] -> [(Int,Char)]
zipRevLists2 _ [] = []
zipRevLists2 [] _ = []
zipRevLists2 (x:xs) (y:ys) = zip' (reverseList (x:xs))  (reverseList (y:ys))


问:
Heroku rails console automatically exits
I'm running a simple rails active query command on 300,000 records.

Why does the heroku console automatically exit?

```<code>def is_number? string
  true if Float(string) rescue false
end
documents = []
DocumentText.all.each do |t|
  if is_number?(t.src)
    documents << t
  end
end
</code>```

答:
try to avoid loading lot of data on repl by</p>

```<code>DocumentText.select('src').each do |t|
    if is_number?(t.src)
        documents << t
    end
end;nil
</code>```

Body:
I'm running a simple rails active query command on 300,000 records.

Why does the heroku console automatically exit?

def is_number? string
  true if Float(string) rescue false
end
documents = []
DocumentText.all.each do |t|
  if is_number?(t.src)
    documents << t
  end
end

Body:
try to avoid loading lot of data on repl by

DocumentText.select('src').each do |t|
    if is_number?(t.src)
        documents << t
    end
end;nil


问:
Receive Response from pop navigator in Flutter
Here is a simple example of code that navigator push for a form called. and pop for an answer.
my goal is to make a pop of an object, not a string, but keeping it that simple still doesn't work.

main.dart:

```<code>import 'package:flutter/material.dart';

import 'answer.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final appTitle = 'Form Validation Demo';

    return MaterialApp(
      title: appTitle,
      home: Scaffold(
        appBar: AppBar(
          title: Text(appTitle),
        ),
        body: ShowData(),
      ),
    );
  }
}

// Create a Form widget.
class MyCustomForm extends StatefulWidget {
  @override
  MyCustomFormState createState() {
    return MyCustomFormState();
  }
}

// Create a corresponding State class.
// This class holds data related to the form.
class MyCustomFormState extends State<MyCustomForm> {
  // Create a global key that uniquely identifies the Form widget
  // and allows validation of the form.
  //
  // Note: This is a GlobalKey<FormState>,
  // not a GlobalKey<MyCustomFormState>.
  final _formKey = GlobalKey<FormState>();
  final myController = TextEditingController();
  String stateData;
  @override
  void dispose() {
    // Clean up the controller when the widget is disposed.
    myController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // Build a Form widget using the _formKey created above.
    return Scaffold(
      body: Form(
        key: _formKey,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            TextFormField(
              controller: myController,
              validator: (value) {
                if (value.isEmpty) {
                  return 'Please enter some text';
                }
                return null;
              },
              onSaved: (value){
                stateData = value;
              },
            ),
            Padding(
              padding: const EdgeInsets.symmetric(vertical: 16.0),
              child: RaisedButton(
                onPressed: () {
                  // Validate returns true if the form is valid, or false
                  // otherwise.
                  if (_formKey.currentState.validate()) {
                    _formKey.currentState.save();
                    // If the form is valid, display a Snackbar.
                    Navigator.pop(context,stateData);
//                  Scaffold.of(context)
//                      .showSnackBar(SnackBar(content: Text(myController.text)));
//                    myController.text = 'look at me';
                  }
                },
                child: Text('Submit'),
              ),
            ),
          ],
        ),
      ),
    );
  }
</code>```

}

answer.dart:

```<code>import 'package:flutter/material.dart';

import 'main.dart';

class ShowData extends StatefulWidget {

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

class _ShowDataState extends State<ShowData> {
  String data = 'start';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        floatingActionButton: FloatingActionButton(onPressed: (){
          String holder =  getFormData(context);
          setState(() {
            data = holder;
          });
        },
        elevation: 4,

        ),
        body:Text(data,style: TextStyle(fontSize: 80),));
  }

  String getFormData(BuildContext context) {
    final Future<String> answer =  Navigator.push(context,MaterialPageRoute(builder: (context)=>MyCustomForm()));
    answer.then((String value) {
        return value != null? value: 'empty';
      }
    );
  }
}
</code>```

when returning from the form error message is :

'package:flutter/src/widgets/text.dart': Failed assertion: line ...
  pos... 'data!=null': A non-null String must be provided to a Text
  widget.

答:
Add await to receive the result from Future and return the value;

```<code>   Future<String> getFormData(BuildContext context) async {
    final result = await Navigator.push(
        context, MaterialPageRoute(builder: (context) => MyCustomForm()));
    return Future.value(result);
  }
</code>```

Modify the FloatingActionButton onPressed code to receive Future String

```<code>onPressed: () async {
            final value = await getFormData(context);
            setState(() {
              data = value;
            });
          },
</code>```

Body:
Here is a simple example of code that navigator push for a form called. and pop for an answer.
my goal is to make a pop of an object, not a string, but keeping it that simple still doesn't work.

main.dart:

import 'package:flutter/material.dart';

import 'answer.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final appTitle = 'Form Validation Demo';

    return MaterialApp(
      title: appTitle,
      home: Scaffold(
        appBar: AppBar(
          title: Text(appTitle),
        ),
        body: ShowData(),
      ),
    );
  }
}

// Create a Form widget.
class MyCustomForm extends StatefulWidget {
  @override
  MyCustomFormState createState() {
    return MyCustomFormState();
  }
}

// Create a corresponding State class.
// This class holds data related to the form.
class MyCustomFormState extends State<MyCustomForm> {
  // Create a global key that uniquely identifies the Form widget
  // and allows validation of the form.
  //
  // Note: This is a GlobalKey<FormState>,
  // not a GlobalKey<MyCustomFormState>.
  final _formKey = GlobalKey<FormState>();
  final myController = TextEditingController();
  String stateData;
  @override
  void dispose() {
    // Clean up the controller when the widget is disposed.
    myController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // Build a Form widget using the _formKey created above.
    return Scaffold(
      body: Form(
        key: _formKey,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            TextFormField(
              controller: myController,
              validator: (value) {
                if (value.isEmpty) {
                  return 'Please enter some text';
                }
                return null;
              },
              onSaved: (value){
                stateData = value;
              },
            ),
            Padding(
              padding: const EdgeInsets.symmetric(vertical: 16.0),
              child: RaisedButton(
                onPressed: () {
                  // Validate returns true if the form is valid, or false
                  // otherwise.
                  if (_formKey.currentState.validate()) {
                    _formKey.currentState.save();
                    // If the form is valid, display a Snackbar.
                    Navigator.pop(context,stateData);
//                  Scaffold.of(context)
//                      .showSnackBar(SnackBar(content: Text(myController.text)));
//                    myController.text = 'look at me';
                  }
                },
                child: Text('Submit'),
              ),
            ),
          ],
        ),
      ),
    );
  }

}

answer.dart:

import 'package:flutter/material.dart';

import 'main.dart';

class ShowData extends StatefulWidget {

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

class _ShowDataState extends State<ShowData> {
  String data = 'start';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        floatingActionButton: FloatingActionButton(onPressed: (){
          String holder =  getFormData(context);
          setState(() {
            data = holder;
          });
        },
        elevation: 4,

        ),
        body:Text(data,style: TextStyle(fontSize: 80),));
  }

  String getFormData(BuildContext context) {
    final Future<String> answer =  Navigator.push(context,MaterialPageRoute(builder: (context)=>MyCustomForm()));
    answer.then((String value) {
        return value != null? value: 'empty';
      }
    );
  }
}

when returning from the form error message is :

'package:flutter/src/widgets/text.dart': Failed assertion: line ...
  pos... 'data!=null': A non-null String must be provided to a Text
  widget.

Body:
Add await to receive the result from Future and return the value;

   Future<String> getFormData(BuildContext context) async {
    final result = await Navigator.push(
        context, MaterialPageRoute(builder: (context) => MyCustomForm()));
    return Future.value(result);
  }

Modify the FloatingActionButton onPressed code to receive Future String

onPressed: () async {
            final value = await getFormData(context);
            setState(() {
              data = value;
            });
          },


问:
How to create Hermes session manually in a java project when importing a SOAP project that connects to a JMS MQ
I have created a SoapUI project that connects with a message queue and sends a JMS message onto it. In order to connect with the MQ, I have used the HERMES tool that SoapUI provides. Currently I am using Hermes v1.14.

I've created the required session and the appropriate queues at Hermes' end and sent the JMS message after following the steps as shown here : https://www.soapui.org/documentation/jms/config.html, https://www.soapui.org/jms/working-with-jms-messages.html

This all works fine.

Now I am trying to incorporate this SOAPUI project into a Java project in which I will provide the project XML and run all the required Test Cases. I am unable to create the HERMES session and queues, etc. via Java code. Below are some code snippets from the class. Am I on the right path? Looking for some help to configure this.

```<code>TestRunner runner = null;
SoapUI.setSoapUICore(new StandaloneSoapUICore(true));
WsdlProject project = new WsdlProject("C:\\My Directory\\CustomerTest-soapui-project.xml");
List<TestSuite> suiteList = project.getTestSuiteList();

String defaultHermesJMSPath= HermesUtils.defaultHermesJMSPath();
System.out.println("defaultHermesJMSPath- "+defaultHermesJMSPath);

String soapUiHome = System.getProperty("soapui.home");
System.out.println("soapUiHome - "+soapUiHome);

//System.setProperty("soapui.home", "C:\\Program Files\\SmartBear\\SoapUI-5.2.1\\bin");

TestRunner runner = project.getTestSuiteByName("Private Individual").getTestCaseByName(
"TEST CASE CONTAINING GROOVY SCRIPT TEST STEPTHAT CONNECTS TO HERMES").run
(new PropertiesMap(), false);
</code>```

Output:

```<code>defaultHermesJMSPath - null
soapuiHome - null
</code>```

P.S. I have included a number of JARs for this which are :

Any help would be appreciated.

答:
It is simple only thing is you should create temporary queues to get the response </p>

```<code>    import javax.jms.*;
    import java.util.Enumeration;

    public class JMSExample5 {

protected static final String SERVICE_QUEUE = "QUEUE_NAME_THAT_IS_CREDTED_IN_SERVER_FOR_ACCEPTING";
static String serverUrl = "tcp://10.xxx.xxx.xxx:xxxxx";
static String userName = "UR_UserID";
static String password = "UR_Pass";

public static void sendTopicMessage(String topicName, String messageStr) {

    Connection connection = null;
    Session session = null;
    MessageProducer msgProducer = null;
    Destination destination = null;

    try {
        TextMessage msg;
        System.out.println("Publishing to destination '" + topicName
                + "'\n");
        ConnectionFactory factory = new com.tibco.tibjms.TibjmsConnectionFactory(serverUrl);
        connection = factory.createConnection(userName, password);
        connection.start();
        session = connection
                .createSession(false,javax.jms.Session.AUTO_ACKNOWLEDGE);
        TemporaryQueue tempQueue = session.createTemporaryQueue();

        TextMessage message_t = session.createTextMessage(messageStr);
        //This step is compulsory to get the reply from JMS server
        message_t.setJMSReplyTo(tempQueue);
        MessageProducer producer = session.createProducer(session.createQueue(SERVICE_QUEUE));
        producer.send(message_t);

        System.out.println("INFO::  The producer has sent the message"+message_t);
        Destination dest = tempQueue;

        MessageConsumer consumer = session.createConsumer(dest);
        Message replyMsg = consumer.receive();
        TextMessage tm = (TextMessage) replyMsg;
        System.out.println("INFO The response is "+ replyMsg);
        consumer.close();
        producer.close();
        session.close();
        connection.close();

    } catch (JMSException e) {
         System.out.println("Error :: there was exception"+e);
        e.printStackTrace();
    }
}

/*-----------------------------------------------------------------------
 * main
 *----------------------------------------------------------------------*/
public static void main(String[] args) {
    JMSExample5.sendTopicMessage(SERVICE_QUEUE,
            "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n" +
                    "<MYServices>\n" +
                    " <header>\n" +
                    "  <Version>1.0</Version>\n" +
                    "  <SrvType>OML</SrvType>\n" +
                    "  <SrvName>REQ_BALANCE_ENQUIRY</SrvName>\n" +
                    "  <SrcApp>BNK</SrcApp>\n" +
                    "  <OrgId>BLA</OrgId>\n" +
                    " </header>\n" +
                    " <body>\n" +
                    "  <srv_req>\n" +
                    "   <req_credit_card_balance_enquiry>\n" +
                    "    <card_no>12345678</card_no>\n" +
                    "   </req_credit_card_balance_enquiry>\n" +
                    "  </srv_req>\n" +
                    " </body>\n" +
                    "</MYServices>\n");
}
</code>```

<p>}</p>

ContentLicense: CC BY-SA 3.0

Body:
I have created a SoapUI project that connects with a message queue and sends a JMS message onto it. In order to connect with the MQ, I have used the HERMES tool that SoapUI provides. Currently I am using Hermes v1.14.

I've created the required session and the appropriate queues at Hermes' end and sent the JMS message after following the steps as shown here : https://www.soapui.org/documentation/jms/config.html, https://www.soapui.org/jms/working-with-jms-messages.html

This all works fine.

Now I am trying to incorporate this SOAPUI project into a Java project in which I will provide the project XML and run all the required Test Cases. I am unable to create the HERMES session and queues, etc. via Java code. Below are some code snippets from the class. Am I on the right path? Looking for some help to configure this.

TestRunner runner = null;
SoapUI.setSoapUICore(new StandaloneSoapUICore(true));
WsdlProject project = new WsdlProject("C:\\My Directory\\CustomerTest-soapui-project.xml");
List<TestSuite> suiteList = project.getTestSuiteList();

String defaultHermesJMSPath= HermesUtils.defaultHermesJMSPath();
System.out.println("defaultHermesJMSPath- "+defaultHermesJMSPath);

String soapUiHome = System.getProperty("soapui.home");
System.out.println("soapUiHome - "+soapUiHome);

//System.setProperty("soapui.home", "C:\\Program Files\\SmartBear\\SoapUI-5.2.1\\bin");

TestRunner runner = project.getTestSuiteByName("Private Individual").getTestCaseByName(
"TEST CASE CONTAINING GROOVY SCRIPT TEST STEPTHAT CONNECTS TO HERMES").run
(new PropertiesMap(), false);

Output:

defaultHermesJMSPath - null
soapuiHome - null

P.S. I have included a number of JARs for this which are :

Any help would be appreciated.

Body:
It is simple only thing is you should create temporary queues to get the response

    import javax.jms.*;
    import java.util.Enumeration;

    public class JMSExample5 {

protected static final String SERVICE_QUEUE = "QUEUE_NAME_THAT_IS_CREDTED_IN_SERVER_FOR_ACCEPTING";
static String serverUrl = "tcp://10.xxx.xxx.xxx:xxxxx";
static String userName = "UR_UserID";
static String password = "UR_Pass";

public static void sendTopicMessage(String topicName, String messageStr) {

    Connection connection = null;
    Session session = null;
    MessageProducer msgProducer = null;
    Destination destination = null;

    try {
        TextMessage msg;
        System.out.println("Publishing to destination '" + topicName
                + "'\n");
        ConnectionFactory factory = new com.tibco.tibjms.TibjmsConnectionFactory(serverUrl);
        connection = factory.createConnection(userName, password);
        connection.start();
        session = connection
                .createSession(false,javax.jms.Session.AUTO_ACKNOWLEDGE);
        TemporaryQueue tempQueue = session.createTemporaryQueue();

        TextMessage message_t = session.createTextMessage(messageStr);
        //This step is compulsory to get the reply from JMS server
        message_t.setJMSReplyTo(tempQueue);
        MessageProducer producer = session.createProducer(session.createQueue(SERVICE_QUEUE));
        producer.send(message_t);

        System.out.println("INFO::  The producer has sent the message"+message_t);
        Destination dest = tempQueue;

        MessageConsumer consumer = session.createConsumer(dest);
        Message replyMsg = consumer.receive();
        TextMessage tm = (TextMessage) replyMsg;
        System.out.println("INFO The response is "+ replyMsg);
        consumer.close();
        producer.close();
        session.close();
        connection.close();

    } catch (JMSException e) {
         System.out.println("Error :: there was exception"+e);
        e.printStackTrace();
    }
}

/*-----------------------------------------------------------------------
 * main
 *----------------------------------------------------------------------*/
public static void main(String[] args) {
    JMSExample5.sendTopicMessage(SERVICE_QUEUE,
            "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n" +
                    "<MYServices>\n" +
                    " <header>\n" +
                    "  <Version>1.0</Version>\n" +
                    "  <SrvType>OML</SrvType>\n" +
                    "  <SrvName>REQ_BALANCE_ENQUIRY</SrvName>\n" +
                    "  <SrcApp>BNK</SrcApp>\n" +
                    "  <OrgId>BLA</OrgId>\n" +
                    " </header>\n" +
                    " <body>\n" +
                    "  <srv_req>\n" +
                    "   <req_credit_card_balance_enquiry>\n" +
                    "    <card_no>12345678</card_no>\n" +
                    "   </req_credit_card_balance_enquiry>\n" +
                    "  </srv_req>\n" +
                    " </body>\n" +
                    "</MYServices>\n");
}

}


问:
Is there any grid like tadvgrid of delphi in c#?
Is there any grid like tadvgrid of delphi in c# ?(which supports right to left completely)

There are several grid components for desktop application development like xtragrid but they doesn't support rtl.

any suggestion?
thanks in advance

答:
You can utilize DataGridView, it is DataAware and you can customize its rendering
It is also RTL compatible</p>


问:
Making VS Code Remote extension work with GLIBC 2.17 installed in non standard locations
I'm trying to use VSCode Remote extension to connect to a remote host that runs on RHEL/CentOS 6, but it fails to connect since CentOS 6 ships with GLIBC 2.12 and GLIBCXX 3.4.1. As mentioned in this post, in order to get the extension to work, the workaround is to install GLIBC>=2.17 and GLIBCXX>=3.4.18.

Unfortunately, I don't have sudo access for the server, so I won't be able to update these libraries using the bash script provided in the link. Also, in this SO post, the author says not to update the system GLIBC since it can break down system applications. That being said, I've tried something different --  I extracted those rpm packages, as described in this blog, inside my home folder. I've then updated the env variables PATH and LD_LIBRARY_PATH in ~/.bash_profile to point to these new locations. But the node binary (in VS Code Remote) still can't find these libraries.

Is there a way to let the node binary know where to look for these libraries? More precisely, can someone explain how I can make this extension work without sudo access?

答:
I've got it to work by installing gcc and glibc using Linuxbrew. See this post for more details: https://github.com/microsoft/vscode-remote-release/issues/103#issuecomment-546551293.

Couple of things to take note of:

Node binary versions in VS Code Server may vary between commits. In the GitHub comment above, the author uses node@10 -- you may replace it with node@12; everything would still work.

Make sure glibc and gcc are properly installed using linuxbrew. This step is key.


问:
Renaming bunch of files that has single quotes in Python
I'm using the following code to rename some files in a directory, it works fine, except files that contain single quotes(') and they will not change.

```<code>for folder, dirs, files in os.walk(rootdir):
    for file in files:
        os.rename(file, file[7:])
</code>```

any help is appreciated.

答:
This can be done pretty easily:

```<code>for folder, dirs, files in os.walk(rootdir):
    for file in files:
        if "'" in file:
            os.rename(file, file.replace("'", ""))
</code>```

This will only rename files that contain a ', and will rename those with the original name, but with the single quotes removed via the replace call. Hope that helps, happy coding!

Body:
I'm using the following code to rename some files in a directory, it works fine, except files that contain single quotes(') and they will not change.

for folder, dirs, files in os.walk(rootdir):
    for file in files:
        os.rename(file, file[7:])

any help is appreciated.

Body:
This can be done pretty easily:

for folder, dirs, files in os.walk(rootdir):
    for file in files:
        if "'" in file:
            os.rename(file, file.replace("'", ""))

This will only rename files that contain a ', and will rename those with the original name, but with the single quotes removed via the replace call. Hope that helps, happy coding!


问:
Android Fatal signal 11 (SIGSEGV) Roulette Tutorial
I'm new and beginner actually to Android thing, and I followed this tutorial This Roulette I followed it and done everything exact same as the tutorial... But that tutorial is one year old.. Right now am using Android Studio latest version based on JDK Java 8..

This is my gradle build

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 28

    defaultConfig {
        applicationId "com.example.sixgroup"
        minSdkVersion 26
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

    implementation 'com.jakewharton:butterknife:10.2.1'
    annotationProcessor 'com.jakewharton:butterknife-compiler:10.2.1'
}
</code>```

My Code:

```<code>*************

import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.Random;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends AppCompatActivity {

    // sectors of our wheel (look at the image to see the sectors)
    private static final String[] sectors = { "32 red", "15 black",
            "19 red", "4 black", "21 red", "2 black", "25 red", "17 black", "34 red",
            "6 black", "27 red","13 black", "36 red", "11 black", "30 red", "8 black",
            "23 red", "10 black", "5 red", "24 black", "16 red", "33 black",
            "1 red", "20 black", "14 red", "31 black", "9 red", "22 black",
            "18 red", "29 black", "7 red", "28 black", "12 red", "35 black",
            "3 red", "26 black", "zero"
    };
    @BindView(R.id.spinBtn)
    Button spinBtn;
    @BindView(R.id.resultTv)
    TextView resultTv;
    @BindView(R.id.wheel)
    ImageView wheel;
    // We create a Random instance to make our wheel spin randomly
    private static final Random RANDOM = new Random();
    private int degree = 0;
    // We have 37 sectors on the wheel, we divide 360 by this value to have angle for each sector
    // we divide by 2 to have a half sector
    private static final float HALF_SECTOR = 360f / 37f / 2f;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
    }

    @OnClick(R.id.spinBtn)
    public void spin(View v) {

        // we calculate random angle for rotation of our wheel
        degree = RANDOM.nextInt(360) + 720;
        int degreeOld = degree % 360;
        // rotation effect on the center of the wheel
        RotateAnimation rotateAnim = new RotateAnimation(degreeOld, degree,
                RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f);
        rotateAnim.setDuration(3600);
        rotateAnim.setFillAfter(true);
        rotateAnim.setInterpolator(new DecelerateInterpolator());
        rotateAnim.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                // we empty the result text view when the animation start
                resultTv.setText("");
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                // we display the correct sector pointed by the triangle at the end of the rotate animation
                resultTv.setText(getSector(360 - (degree % 360)));
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

        // we start the animation
        wheel.startAnimation(rotateAnim);
    }

    private String getSector(int degrees) {
        int i = 0;
        String text = null;

        do {
            // start and end of each sector on the wheel
            float start = HALF_SECTOR * ((i * 2) + 1);
            float end = HALF_SECTOR * ((i * 2) + 3);

            if (degrees >= start && degrees < end) {
                // degrees is in [start;end[
                // so text is equals to sectors[i];
                text = sectors[i];
            }

            i++;
            // now we can test our Android Roulette Game :)
            // That's all !
            // In the second part, you will learn how to add some bets on the table to play to the Roulette Game :)
            // Subscribe and stay tuned !

        } while (text == null  &&  i < sectors.length);
            return text;
    }
}
**************
</code>```

Everything update.. So am not sure why am getting

A/libc: Fatal signal 11 (SIGSEGV), code 1, fault addr 0x68 in tid 12075 (xample.sixgroup)

The log:

```<code>2020-05-30 18:02:43.851 25578-25578/com.example.sixgroup I/zygote64:     at void com.example.sixgroup.MainActivity.onCreate(android.os.Bundle) (MainActivity.java:46)
2020-05-30 18:02:43.851 25578-25578/com.example.sixgroup I/zygote64:     at void android.app.Activity.performCreate(android.os.Bundle) (Activity.java:7183)
2020-05-30 18:02:43.851 25578-25578/com.example.sixgroup I/zygote64:     at void android.app.Instrumentation.callActivityOnCreate(android.app.Activity, android.os.Bundle) (Instrumentation.java:1220)
2020-05-30 18:02:43.851 25578-25578/com.example.sixgroup I/zygote64:     at android.app.Activity android.app.ActivityThread.performLaunchActivity(android.app.ActivityThread$ActivityClientRecord, android.content.Intent) (ActivityThread.java:2910)
2020-05-30 18:02:43.851 25578-25578/com.example.sixgroup I/zygote64:     at void android.app.ActivityThread.handleLaunchActivity(android.app.ActivityThread$ActivityClientRecord, android.content.Intent, java.lang.String) (ActivityThread.java:3032)
2020-05-30 18:02:43.851 25578-25578/com.example.sixgroup I/zygote64:     at void android.app.ActivityThread.-wrap11(android.app.ActivityThread, android.app.ActivityThread$ActivityClientRecord, android.content.Intent, java.lang.String) (ActivityThread.java:-1)
2020-05-30 18:02:43.851 25578-25578/com.example.sixgroup I/zygote64:     at void android.app.ActivityThread$H.handleMessage(android.os.Message) (ActivityThread.java:1696)
2020-05-30 18:02:43.851 25578-25578/com.example.sixgroup I/zygote64:     at void android.os.Handler.dispatchMessage(android.os.Message) (Handler.java:105)
2020-05-30 18:02:43.851 25578-25578/com.example.sixgroup I/zygote64:     at void android.os.Looper.loop() (Looper.java:164)
2020-05-30 18:02:43.851 25578-25578/com.example.sixgroup I/zygote64:     at void android.app.ActivityThread.main(java.lang.String[]) (ActivityThread.java:6944)
2020-05-30 18:02:43.851 25578-25578/com.example.sixgroup I/zygote64:     at java.lang.Object java.lang.reflect.Method.invoke(java.lang.Object, java.lang.Object[]) (Method.java:-2)
2020-05-30 18:02:43.851 25578-25578/com.example.sixgroup I/zygote64:     at void com.android.internal.os.Zygote$MethodAndArgsCaller.run() (Zygote.java:327)
2020-05-30 18:02:43.851 25578-25578/com.example.sixgroup I/zygote64:     at void com.android.internal.os.ZygoteInit.main(java.lang.String[]) (ZygoteInit.java:1374)
2020-05-30 18:02:44.048 25578-25578/com.example.sixgroup A/libc: Fatal signal 11 (SIGSEGV), code 1, fault addr 0x68 in tid 25578 (xample.sixgroup)
</code>```

答:
Ohkay guys, I don't know and am not sure what was the problem actually... But what I have done is removing the dependence(ButterKnife) and adding my own code inside OnCreate.. This made it work??!!! First in the log it was same but giving [-2] which is impossible for a String Area.. This could the possible problem.

Thank you

Body:
I'm new and beginner actually to Android thing, and I followed this tutorial This Roulette I followed it and done everything exact same as the tutorial... But that tutorial is one year old.. Right now am using Android Studio latest version based on JDK Java 8..

This is my gradle build

apply plugin: 'com.android.application'

android {
    compileSdkVersion 28

    defaultConfig {
        applicationId "com.example.sixgroup"
        minSdkVersion 26
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

    implementation 'com.jakewharton:butterknife:10.2.1'
    annotationProcessor 'com.jakewharton:butterknife-compiler:10.2.1'
}

My Code:

*************

import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.Random;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends AppCompatActivity {

    // sectors of our wheel (look at the image to see the sectors)
    private static final String[] sectors = { "32 red", "15 black",
            "19 red", "4 black", "21 red", "2 black", "25 red", "17 black", "34 red",
            "6 black", "27 red","13 black", "36 red", "11 black", "30 red", "8 black",
            "23 red", "10 black", "5 red", "24 black", "16 red", "33 black",
            "1 red", "20 black", "14 red", "31 black", "9 red", "22 black",
            "18 red", "29 black", "7 red", "28 black", "12 red", "35 black",
            "3 red", "26 black", "zero"
    };
    @BindView(R.id.spinBtn)
    Button spinBtn;
    @BindView(R.id.resultTv)
    TextView resultTv;
    @BindView(R.id.wheel)
    ImageView wheel;
    // We create a Random instance to make our wheel spin randomly
    private static final Random RANDOM = new Random();
    private int degree = 0;
    // We have 37 sectors on the wheel, we divide 360 by this value to have angle for each sector
    // we divide by 2 to have a half sector
    private static final float HALF_SECTOR = 360f / 37f / 2f;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
    }

    @OnClick(R.id.spinBtn)
    public void spin(View v) {

        // we calculate random angle for rotation of our wheel
        degree = RANDOM.nextInt(360) + 720;
        int degreeOld = degree % 360;
        // rotation effect on the center of the wheel
        RotateAnimation rotateAnim = new RotateAnimation(degreeOld, degree,
                RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f);
        rotateAnim.setDuration(3600);
        rotateAnim.setFillAfter(true);
        rotateAnim.setInterpolator(new DecelerateInterpolator());
        rotateAnim.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                // we empty the result text view when the animation start
                resultTv.setText("");
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                // we display the correct sector pointed by the triangle at the end of the rotate animation
                resultTv.setText(getSector(360 - (degree % 360)));
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

        // we start the animation
        wheel.startAnimation(rotateAnim);
    }

    private String getSector(int degrees) {
        int i = 0;
        String text = null;

        do {
            // start and end of each sector on the wheel
            float start = HALF_SECTOR * ((i * 2) + 1);
            float end = HALF_SECTOR * ((i * 2) + 3);

            if (degrees >= start && degrees < end) {
                // degrees is in [start;end[
                // so text is equals to sectors[i];
                text = sectors[i];
            }

            i++;
            // now we can test our Android Roulette Game :)
            // That's all !
            // In the second part, you will learn how to add some bets on the table to play to the Roulette Game :)
            // Subscribe and stay tuned !

        } while (text == null  &&  i < sectors.length);
            return text;
    }
}
**************

Everything update.. So am not sure why am getting

A/libc: Fatal signal 11 (SIGSEGV), code 1, fault addr 0x68 in tid 12075 (xample.sixgroup)

The log:

2020-05-30 18:02:43.851 25578-25578/com.example.sixgroup I/zygote64:     at void com.example.sixgroup.MainActivity.onCreate(android.os.Bundle) (MainActivity.java:46)
2020-05-30 18:02:43.851 25578-25578/com.example.sixgroup I/zygote64:     at void android.app.Activity.performCreate(android.os.Bundle) (Activity.java:7183)
2020-05-30 18:02:43.851 25578-25578/com.example.sixgroup I/zygote64:     at void android.app.Instrumentation.callActivityOnCreate(android.app.Activity, android.os.Bundle) (Instrumentation.java:1220)
2020-05-30 18:02:43.851 25578-25578/com.example.sixgroup I/zygote64:     at android.app.Activity android.app.ActivityThread.performLaunchActivity(android.app.ActivityThread$ActivityClientRecord, android.content.Intent) (ActivityThread.java:2910)
2020-05-30 18:02:43.851 25578-25578/com.example.sixgroup I/zygote64:     at void android.app.ActivityThread.handleLaunchActivity(android.app.ActivityThread$ActivityClientRecord, android.content.Intent, java.lang.String) (ActivityThread.java:3032)
2020-05-30 18:02:43.851 25578-25578/com.example.sixgroup I/zygote64:     at void android.app.ActivityThread.-wrap11(android.app.ActivityThread, android.app.ActivityThread$ActivityClientRecord, android.content.Intent, java.lang.String) (ActivityThread.java:-1)
2020-05-30 18:02:43.851 25578-25578/com.example.sixgroup I/zygote64:     at void android.app.ActivityThread$H.handleMessage(android.os.Message) (ActivityThread.java:1696)
2020-05-30 18:02:43.851 25578-25578/com.example.sixgroup I/zygote64:     at void android.os.Handler.dispatchMessage(android.os.Message) (Handler.java:105)
2020-05-30 18:02:43.851 25578-25578/com.example.sixgroup I/zygote64:     at void android.os.Looper.loop() (Looper.java:164)
2020-05-30 18:02:43.851 25578-25578/com.example.sixgroup I/zygote64:     at void android.app.ActivityThread.main(java.lang.String[]) (ActivityThread.java:6944)
2020-05-30 18:02:43.851 25578-25578/com.example.sixgroup I/zygote64:     at java.lang.Object java.lang.reflect.Method.invoke(java.lang.Object, java.lang.Object[]) (Method.java:-2)
2020-05-30 18:02:43.851 25578-25578/com.example.sixgroup I/zygote64:     at void com.android.internal.os.Zygote$MethodAndArgsCaller.run() (Zygote.java:327)
2020-05-30 18:02:43.851 25578-25578/com.example.sixgroup I/zygote64:     at void com.android.internal.os.ZygoteInit.main(java.lang.String[]) (ZygoteInit.java:1374)
2020-05-30 18:02:44.048 25578-25578/com.example.sixgroup A/libc: Fatal signal 11 (SIGSEGV), code 1, fault addr 0x68 in tid 25578 (xample.sixgroup)


问:
How to intentionally delete a boost::shared_ptr?
I have many boost::shared_ptr<MyClass> objects, and at some point I intentionally want to delete some of them to free some memory. (I know at that point that I will never need the pointed-to MyClass objects anymore.) How can I do that?

I guess you can't just call delete() with the raw pointer that I get with get().

I've seen a function get_deleter(shared_ptr<T> const & p) in boost::shared_ptr, but I'm not sure how to use it, and also it says experimental right next to it. (I think I have Boost 1.38.)

Maybe just assign a new empty boost::shared_ptr to the variable? That should throw away the old value and delete it.

答:
You just do

```<code>ptr.reset();
</code>```

See the shared_ptr manual. It is equivalent to

```<code>shared_ptr<T>().swap(ptr)
</code>```

You call reset on every smart pointer that should not reference the object anymore. The last such reset (or any other action that causes the reference count drop to zero, actually) will cause the object to be free'ed using the deleter automatically.

Maybe you are interested in the Smart Pointer Programming Techniques. It has an entry about delayed deallocation.

Body:
You just do

ptr.reset();

See the shared_ptr manual. It is equivalent to

shared_ptr<T>().swap(ptr)

You call reset on every smart pointer that should not reference the object anymore. The last such reset (or any other action that causes the reference count drop to zero, actually) will cause the object to be free'ed using the deleter automatically.

Maybe you are interested in the Smart Pointer Programming Techniques. It has an entry about delayed deallocation.

OwnerDisplayName: litb

LastEditorDisplayName: litb