问:
ASCII files, how to deal with separator in quoted string?
I have an ASCII file (csv, for instance) that uses , as separator, however this char is also present in quoted strings:

```<code>3,       "hh,1,foo",            foo
"5,,,5", "1,2,3d,,,something ", foo2
test,    "col3",                foo3
</code>```

To avoid such ambiguity I want to replace the , separator by the ; one. How to do that with command line? (under linux).

UPDATE/extra question:

There are at least two options using sed or awk.

My extra question is which one is the fastest? (this can be important for big csv files).

答:
You can use awk command to do a search/replace only inside the " quoted parts.

The first step is to replace the , by _

```<code>cat demo.txt | awk 'BEGIN{FS=OFS="\""} {for(i=2;i<NF;i+=2)gsub(",","_",$i)} 1'
</code>```

which gives

```<code>3,       "hh_1_foo",            foo
"5___5", "1_2_3d___something ", foo2
test,    "col3",                foo3
</code>```

Then replace the , by ; with the more usual tr command.

```<code>tr ',' ';'
</code>```

The last step uses awk again in a "reverse" way to replace the temporary _ placeholder into the initial , character.

Putting everything together we have:

```<code>cat demo.txt |
awk 'BEGIN{FS=OFS="\""} {for(i=2;i<NF;i+=2)gsub(",","_",$i)} 1' |
tr ',' ';' |
awk 'BEGIN{FS=OFS="\""} {for(i=2;i<NF;i+=2)gsub("_",",",$i)} 1'
</code>```

which gives

```<code>3;       "hh,1,foo";            foo
"5,,,5"; "1,2,3d,,,something "; foo2
test;    "col3";                foo3
</code>```

as expected.

UPDATE: the fastest solution?

I use the 3 answers I got to bench them on a 206Mb csv file (with several runs to take care of cache effect...), here are the typical results I get:

1/ My initial answer:

```<code>time cat avec_vapeur.csv | awk 'BEGIN{FS=OFS="\""} {for(i=2;i<NF;i+=2)gsub(",","_",$i)} 1' |  tr ',' ';' |  awk 'BEGIN{FS=OFS="\""} {for(i=2;i<NF;i+=2)gsub("_",",",$i)} 1'  > /dev/null

real    0m2.488s
user    0m5.025s
sys     0m0.242s
</code>```

2/ The alternative awk based solution: ravindersingh13

```<code>time cat avec_vapeur.csv | awk -F"\"" '{for(i=1;i<=NF;i+=2){gsub(/,/,";",$i)}} 1' OFS="\"" > /dev/null

real    0m4.705s
user    0m4.631s
sys     0m0.111s
</code>```

3/ The sed based solution: sjsam

```<code>time cat avec_vapeur.csv | sed -E 's/,([[:space:]]*")/;\1/g;s/("[[:space:]]*),/\1;/g' > /dev/null

real    0m0.174s
user    0m0.118s
sys     0m0.130s
</code>```

-> The clear winner is the sed based solution!

The last answer I got: inian

```<code>time cat avec_vapeur.csv |  awk -v OFS=';' 'BEGIN{FPAT = "([^,]+)|([[:space:]]*\"[^\"]+\")"}{$1=$1}1' > /dev/null

real    0m37.507s
user    0m37.463s
sys     0m0.122s
</code>```

which is also the slowest I tested (no judgement here, just done these tests for fun!)

update: I initially misread =inian=, sorry. If I understand you well, I add

```<code>LC_ALL=C
</code>```

to speed up things.

Now I get:

```<code>3,       "hh_1_foo",            foo
"5___5", "1_2_3d___something ", foo2
test,    "col3",                foo3
</code>```0

which is faster but not as fast as the sed solution.

Now game is over, no more bench from me (I have to work a little bit too)

Last words for the winner, perl solution: sjsam

```<code>3,       "hh_1_foo",            foo
"5___5", "1_2_3d___something ", foo2
test,    "col3",                foo3
</code>```1

which is even slightly faster than the sed one (at least with my tests)!

Body:
I have an ASCII file (csv, for instance) that uses , as separator, however this char is also present in quoted strings:

3,       "hh,1,foo",            foo
"5,,,5", "1,2,3d,,,something ", foo2
test,    "col3",                foo3

To avoid such ambiguity I want to replace the , separator by the ; one. How to do that with command line? (under linux).

UPDATE/extra question:

There are at least two options using sed or awk.

My extra question is which one is the fastest? (this can be important for big csv files).

Body:
You can use awk command to do a search/replace only inside the " quoted parts.

The first step is to replace the , by _

cat demo.txt | awk 'BEGIN{FS=OFS="\""} {for(i=2;i<NF;i+=2)gsub(",","_",$i)} 1'

which gives

3,       "hh_1_foo",            foo
"5___5", "1_2_3d___something ", foo2
test,    "col3",                foo3

Then replace the , by ; with the more usual tr command.

tr ',' ';'

The last step uses awk again in a "reverse" way to replace the temporary _ placeholder into the initial , character.

Putting everything together we have:

cat demo.txt |
awk 'BEGIN{FS=OFS="\""} {for(i=2;i<NF;i+=2)gsub(",","_",$i)} 1' |
tr ',' ';' |
awk 'BEGIN{FS=OFS="\""} {for(i=2;i<NF;i+=2)gsub("_",",",$i)} 1'

which gives

3;       "hh,1,foo";            foo
"5,,,5"; "1,2,3d,,,something "; foo2
test;    "col3";                foo3

as expected.

UPDATE: the fastest solution?

I use the 3 answers I got to bench them on a 206Mb csv file (with several runs to take care of cache effect...), here are the typical results I get:

1/ My initial answer:

time cat avec_vapeur.csv | awk 'BEGIN{FS=OFS="\""} {for(i=2;i<NF;i+=2)gsub(",","_",$i)} 1' |  tr ',' ';' |  awk 'BEGIN{FS=OFS="\""} {for(i=2;i<NF;i+=2)gsub("_",",",$i)} 1'  > /dev/null

real    0m2.488s
user    0m5.025s
sys     0m0.242s

2/ The alternative awk based solution: ravindersingh13

time cat avec_vapeur.csv | awk -F"\"" '{for(i=1;i<=NF;i+=2){gsub(/,/,";",$i)}} 1' OFS="\"" > /dev/null

real    0m4.705s
user    0m4.631s
sys     0m0.111s

3/ The sed based solution: sjsam

time cat avec_vapeur.csv | sed -E 's/,([[:space:]]*")/;\1/g;s/("[[:space:]]*),/\1;/g' > /dev/null

real    0m0.174s
user    0m0.118s
sys     0m0.130s

-> The clear winner is the sed based solution!

The last answer I got: inian

time cat avec_vapeur.csv |  awk -v OFS=';' 'BEGIN{FPAT = "([^,]+)|([[:space:]]*\"[^\"]+\")"}{$1=$1}1' > /dev/null

real    0m37.507s
user    0m37.463s
sys     0m0.122s

which is also the slowest I tested (no judgement here, just done these tests for fun!)

update: I initially misread =inian=, sorry. If I understand you well, I add

LC_ALL=C

to speed up things.

Now I get:

real    0m20.268s
user    0m20.008s
sys     0m0.087s

which is faster but not as fast as the sed solution.

Now game is over, no more bench from me (I have to work a little bit too)

Last words for the winner, perl solution: sjsam

time cat avec_vapeur.csv | perl -ane  's/,(\s*"[^"]*"\s*),/;$1;/g;print' > /dev/null

real    0m0.134s
user    0m0.096s
sys     0m0.104s

which is even slightly faster than the sed one (at least with my tests)!


来源: stackexchange

问:
Use RegExp in Awk
I have CSV file:

```<code><iframe src="https://localhost/get/44bc40f3bc04f65b7a35"></iframe>|name_1
<iframe src="https://localhost/get/5db0d477d707121934ff"></iframe>|name_2
<iframe src="https://localhost/get/6c95bd2b32ed45989c61"></iframe>|name_3
<iframe src="https://localhost/get/0a9c4655800e8a7b9ea2"></iframe>|name_4
<iframe src="https://localhost/get/754953b57a32e2841bda"></iframe>|name_5
</code>```

and want use RegExp and Awk (or Gawk) to make this CSV file like this:

```<code>44bc40f3bc04f65b7a35|name_1
5db0d477d707121934ff|name_2
6c95bd2b32ed45989c61|name_3
0a9c4655800e8a7b9ea2|name_4
754953b57a32e2841bda|name_5
</code>```

I have worked RegExp in Grep

```<code>$ grep -Po "[A-Za-z]*+\d++\w++" example.txt
44bc40f3bc04f65b7a35
5db0d477d707121934ff
6c95bd2b32ed45989c61
0a9c4655800e8a7b9ea2
754953b57a32e2841bda
</code>```

but this RegExp not work in Awk. I think i'm not correct use regexp in Awk or this type of RegExp not worked in Awk.

```<code>$ awk -F "|" 'match($1, /[A-Za-z]*+\d++\w++/, a) {print a[0]"|"$2}' example.txt
db0d477d707121934ff|name_2
bd2b32ed45989c61|name_3
bda|name_5
</code>```

Just Awk work fine:

```<code>$ awk -F "|" '{print $1"|"$2}' example.txt
<iframe src="https://localhost/get/44bc40f3bc04f65b7a35"></iframe>|name_1
<iframe src="https://localhost/get/5db0d477d707121934ff"></iframe>|name_2
<iframe src="https://localhost/get/6c95bd2b32ed45989c61"></iframe>|name_3
<iframe src="https://localhost/get/0a9c4655800e8a7b9ea2"></iframe>|name_4
<iframe src="https://localhost/get/754953b57a32e2841bda"></iframe>|name_5
</code>```

答:
Here is another solution:

```<code>awk -F"[/\">|]" 'BEGIN{ OFS = "|" }{ print $6, $11 }' yourfile
</code>```

With the -F option in the beginning the Field Separator can be /, ", > and |. After that is done you can just print the fields $6 and $11 which contain your desired output together with the output field separator.

Output:

```<code>44bc40f3bc04f65b7a35|name_1
5db0d477d707121934ff|name_2
6c95bd2b32ed45989c61|name_3
0a9c4655800e8a7b9ea2|name_4
754953b57a32e2841bda|name_5
</code>```

ContentLicense: CC BY-SA 3.0

Title: Use RegExp in Awk

Body:
I have CSV file:

|name_1
|name_2
|name_3
|name_4
|name_5

and want use RegExp and Awk (or Gawk) to make this CSV file like this:

44bc40f3bc04f65b7a35|name_1
5db0d477d707121934ff|name_2
6c95bd2b32ed45989c61|name_3
0a9c4655800e8a7b9ea2|name_4
754953b57a32e2841bda|name_5

I have worked RegExp in Grep

$ grep -Po "[A-Za-z]*+\d++\w++" example.txt
44bc40f3bc04f65b7a35
5db0d477d707121934ff
6c95bd2b32ed45989c61
0a9c4655800e8a7b9ea2
754953b57a32e2841bda

but this RegExp not work in Awk. I think i'm not correct use regexp in Awk or this type of RegExp not worked in Awk.

$ awk -F "|" 'match($1, /[A-Za-z]*+\d++\w++/, a) {print a[0]"|"$2}' example.txt
db0d477d707121934ff|name_2
bd2b32ed45989c61|name_3
bda|name_5

Just Awk work fine:

$ awk -F "|" '{print $1"|"$2}' example.txt
|name_1
|name_2
|name_3
|name_4
|name_5

Body:
Here is another solution:

awk -F"[/\">|]" 'BEGIN{ OFS = "|" }{ print $6, $11 }' yourfile

With the -F option in the beginning the Field Separator can be /, ", > and |. After that is done you can just print the fields $6 and $11 which contain your desired output together with the output field separator.

Output:

44bc40f3bc04f65b7a35|name_1
5db0d477d707121934ff|name_2
6c95bd2b32ed45989c61|name_3
0a9c4655800e8a7b9ea2|name_4
754953b57a32e2841bda|name_5


问:
How do you properly include a resource folder in a JAR artifact in IntelliJ IDEA?
I have a project that reads graphics and sound effects from a folder labeled res. This folder is at the same directory level as the src folder. I have res marked as Resources Root.

I configured my artifact to include res as a Content Directory by way of
Project Structure -> Artifacts -> Add (Alt + Insert) -> JAR

Then, in the output layout tab, I pressed the Add dropdown box -> Directory Content -> res

When I run the project in Intellij, it finds the resources just fine. Here is a code snippet showing how I access the resources:

```<code>public static final Sfx VOID_SOUND = new Sfx(TinySound.loadSound(new File("res/audio/sfx/void_sound.wav")));
</code>```

However, when I build the standalone artifact, then run the jar, it looks for the resource by prepending the parent directory of my machine to the file path, all the way to root. Here is how the terminal output looks:

```<code>/home/user/Demo/res/audio/sfx/void_sound.wav (No such file or directory)
Error getting resource stream!
</code>```

Is there a way to configure the artifact build to where it looks in the proper place? I want the resources included inside the jar file so it acts as a standalone jar with no external dependencies.

答:
All the files from resource/source folders inside your module's Content root are included into artifact on artifact build. You can explore the artifact content produced (the artifact is placed into a directory specified in Output directory field in Artifct's Generat Settings) yourself.

Make sure you are specifying the correct directory for the file. E.g. if the res folder is marked as the module's resource root the file path name in the artifact will start from the sub-folder inside the res directory, that is audio/sfx/void_sound.wav.

Body:
I have a project that reads graphics and sound effects from a folder labeled res. This folder is at the same directory level as the src folder. I have res marked as Resources Root.

I configured my artifact to include res as a Content Directory by way of
Project Structure -> Artifacts -> Add (Alt + Insert) -> JAR

Then, in the output layout tab, I pressed the Add dropdown box -> Directory Content -> res

When I run the project in Intellij, it finds the resources just fine. Here is a code snippet showing how I access the resources:

public static final Sfx VOID_SOUND = new Sfx(TinySound.loadSound(new File("res/audio/sfx/void_sound.wav")));

However, when I build the standalone artifact, then run the jar, it looks for the resource by prepending the parent directory of my machine to the file path, all the way to root. Here is how the terminal output looks:

/home/user/Demo/res/audio/sfx/void_sound.wav (No such file or directory)
Error getting resource stream!

Is there a way to configure the artifact build to where it looks in the proper place? I want the resources included inside the jar file so it acts as a standalone jar with no external dependencies.


问:
send message to set of channels in non-deterministic order
I'm building a Promela model in which one process send a request to N other processes, waits for the replies, and then computes a value. Basically a typical map-reduce style execution flow. Currently my model sends requests in a fixed order. I'd like to generalize this to send a non-deterministic order. I've looked at the select statement, but that appears to select a single element non-deterministically.

Is there a good pattern for achieving this? Here the basic structure of what I'm working with:

```<code>#define NUM_OBJECTS 2
chan obj_req[NUM_OBJECTS] = [0] of { mtype, chan };
</code>```

This is the object process that responds to msgtype messages with some value that it computes.

```<code>proctype Object(chan request) {
  chan reply;

end:
  do
  :: request ? msgtype(reply) ->
    int value = 23
    reply ! value
  od;
}
</code>```

This is the client. It sends a request to each of the objects in order 0, 1, 2, ..., and collects all the responses and reduces the values.

```<code>proctype Client() {
  chan obj_reply = [0] of { int };
  int value

  // WOULD LIKE NON-DETERMINISM HERE
  for (i in obj_req) {
    obj_req[i] ! msgtype(obj_reply)
    obj_reply ? value
    // do something with value
  }
}
</code>```

And I start up the system like this

```<code>init {
  atomic {
    run Object(obj_req[0]);
    run Object(obj_req[1]);
    run Client();
  }
}
</code>```

答:
From your question I gather that you want to assign a task to a given process in a randomised order, as opposed to simply assign a random task to an ordered sequence of processes.

All in all, the solution for both approaches is very similar. I don't know whether the one I am going to propose is the most elegant approach, though.

#define NUM_OBJECTS 10

mtype = { ASSIGN_TASK };
chan obj_req[NUM_OBJECTS] = [0] of { mtype, chan, int };

init
{
    byte i;
    for (i in obj_req) {
        run Object(i, obj_req[i]);
    }
    run Client();
};

proctype Client ()
{
    byte i, id;
    int value;
    byte map[NUM_OBJECTS];
    int data[NUM_OBJECTS];
    chan obj_reply = [NUM_OBJECTS] of { byte, int };

    d_step {
        for (i in obj_req) {
            map[i] = i;
        }
    }

    // scramble task assignment map
    for (i in obj_req) {
        byte j;
        select(j : 0 .. (NUM_OBJECTS - 1));
        byte tmp = map[i];
        map[i] = map[j];
        map[j] = tmp;
    }

    // assign tasks
    for (i in obj_req) {
        obj_req[map[i]] ! ASSIGN_TASK(obj_reply, data[i]);
    }

    // out-of-order wait of data
    for (i in obj_req) {
        obj_reply ? id(value);
        printf("Object[%d]: end!\n", id, value);
    }

    printf("client ends\n");
};

proctype Object(byte id; chan request)
{
  chan reply;
  int in_data;

end:
  do
    :: request ? ASSIGN_TASK(reply, in_data) ->
        printf("Object[%d]: start!\n", id)
        reply ! id(id)
  od;
};
```

<p>The idea is have an <code>array</code> which acts like a <code>map</code> from the set of indexes to the starting position (or, equivalently, to the assigned task).
The <code>map</code> is then <em>scrambled</em> through a finite number of <code>swap</code> operations. After that, each <code>object</code> is assigned its own task in <em>parallel</em>, so they can all start <em>more-or-less</em> at the same time.</p>

<hr>

<p>In the following <em>output example</em>, you can see that:</p>

<ul>
<li>Objects are being assigned a task in a <em>random</em> order</li>
<li>Objects <em>can</em> complete the task in a different <em>random</em> order</li>
</ul>

<pre class="lang-sh prettyprint-override"><code>~$ spin test.pml
              Object[1]: start!
                                              Object[9]: start!
          Object[0]: start!
                                  Object[6]: start!
                  Object[2]: start!
                                          Object[8]: start!
                          Object[4]: start!
                              Object[5]: start!
                      Object[3]: start!
                                      Object[7]: start!
                                                  Object[1]: end!
                                                  Object[9]: end!
                                                  Object[0]: end!
                                                  Object[6]: end!
                                                  Object[2]: end!
                                                  Object[4]: end!
                                                  Object[8]: end!
                                                  Object[5]: end!
                                                  Object[3]: end!
                                                  Object[7]: end!
                                                  client ends
      timeout
#processes: 11
...
</code>```

If one wants to assign a random task to each object rather than starting them randomly, then it suffices to change:

```<code>        obj_req[map[i]] ! ASSIGN_TASK(obj_reply, data[i]);
</code>```

into:

```<code>        obj_req[i] ! ASSIGN_TASK(obj_reply, data[map[i]]);
</code>```

Obviously, data should be initialised to some meaningful content first.

Body:
I'm building a Promela model in which one process send a request to N other processes, waits for the replies, and then computes a value. Basically a typical map-reduce style execution flow. Currently my model sends requests in a fixed order. I'd like to generalize this to send a non-deterministic order. I've looked at the select statement, but that appears to select a single element non-deterministically.

Is there a good pattern for achieving this? Here the basic structure of what I'm working with:

#define NUM_OBJECTS 2
chan obj_req[NUM_OBJECTS] = [0] of { mtype, chan };

This is the object process that responds to msgtype messages with some value that it computes.

proctype Object(chan request) {
  chan reply;

end:
  do
  :: request ? msgtype(reply) ->
    int value = 23
    reply ! value
  od;
}

This is the client. It sends a request to each of the objects in order 0, 1, 2, ..., and collects all the responses and reduces the values.

proctype Client() {
  chan obj_reply = [0] of { int };
  int value

  // WOULD LIKE NON-DETERMINISM HERE
  for (i in obj_req) {
    obj_req[i] ! msgtype(obj_reply)
    obj_reply ? value
    // do something with value
  }
}

And I start up the system like this

init {
  atomic {
    run Object(obj_req[0]);
    run Object(obj_req[1]);
    run Client();
  }
}

Body:
From your question I gather that you want to assign a task to a given process in a randomised order, as opposed to simply assign a random task to an ordered sequence of processes.

All in all, the solution for both approaches is very similar. I don't know whether the one I am going to propose is the most elegant approach, though.

#define NUM_OBJECTS 10

mtype = { ASSIGN_TASK };
chan obj_req[NUM_OBJECTS] = [0] of { mtype, chan, int };

init
{
    byte i;
    for (i in obj_req) {
        run Object(i, obj_req[i]);
    }
    run Client();
};

proctype Client ()
{
    byte i, id;
    int value;
    byte map[NUM_OBJECTS];
    int data[NUM_OBJECTS];
    chan obj_reply = [NUM_OBJECTS] of { byte, int };

    d_step {
        for (i in obj_req) {
            map[i] = i;
        }
    }

    // scramble task assignment map
    for (i in obj_req) {
        byte j;
        select(j : 0 .. (NUM_OBJECTS - 1));
        byte tmp = map[i];
        map[i] = map[j];
        map[j] = tmp;
    }

    // assign tasks
    for (i in obj_req) {
        obj_req[map[i]] ! ASSIGN_TASK(obj_reply, data[i]);
    }

    // out-of-order wait of data
    for (i in obj_req) {
        obj_reply ? id(value);
        printf("Object[%d]: end!\n", id, value);
    }

    printf("client ends\n");
};

proctype Object(byte id; chan request)
{
  chan reply;
  int in_data;

end:
  do
    :: request ? ASSIGN_TASK(reply, in_data) ->
        printf("Object[%d]: start!\n", id)
        reply ! id(id)
  od;
};

The idea is have an array which acts like a map from the set of indexes to the starting position (or, equivalently, to the assigned task).
The map is then scrambled through a finite number of swap operations. After that, each object is assigned its own task in parallel, so they can all start more-or-less at the same time.

In the following output example, you can see that:

Objects are being assigned a task in a random order

Objects can complete the task in a different random order

~$ spin test.pml
              Object[1]: start!
                                              Object[9]: start!
          Object[0]: start!
                                  Object[6]: start!
                  Object[2]: start!
                                          Object[8]: start!
                          Object[4]: start!
                              Object[5]: start!
                      Object[3]: start!
                                      Object[7]: start!
                                                  Object[1]: end!
                                                  Object[9]: end!
                                                  Object[0]: end!
                                                  Object[6]: end!
                                                  Object[2]: end!
                                                  Object[4]: end!
                                                  Object[8]: end!
                                                  Object[5]: end!
                                                  Object[3]: end!
                                                  Object[7]: end!
                                                  client ends
      timeout
#processes: 11
...

If one wants to assign a random task to each object rather than starting them randomly, then it suffices to change:

        obj_req[map[i]] ! ASSIGN_TASK(obj_reply, data[i]);

into:

        obj_req[i] ! ASSIGN_TASK(obj_reply, data[map[i]]);

Obviously, data should be initialised to some meaningful content first.


问:
Dockerfile ADD failed : No Source files were specified
I have a python project created in eclipse. I am creating for first time a Dockerfile.The Docker build always fails showing this

ADD failed: no source files were specified

I am copying the project directory and adding pydev packages with python modules using ADD command.Below is the python project structure. How to ADD all modules in Dockerfile?

```<code>-Myproject_rootdirectory
  -- Client
    - __init__.py
    - Main.py

  --Subscriber1
   - domain1
     - __init__.py
     - d2.py
  - domain2
     - __init__.py
     - d2.py
  - __init__.py

 --Subscriber2
   - domain3
     - __init__.py
     - d3.py
   - domain4
     - __init__.py
     - d4.py
   - __init__.py
</code>```

答:
It generally is recommended to use COPY before ADD, because it serves a lesser purpose and is somewhat more lightweight.

To copy your whole directory into the image, just add the following line after editing:

```<code> COPY . /path/to/dir/in/image
</code>```

Some helpful links to start writing dockerfiles:

Reference

Best Practices

Postgresql example

Body:
I have a python project created in eclipse. I am creating for first time a Dockerfile.The Docker build always fails showing this

ADD failed: no source files were specified

I am copying the project directory and adding pydev packages with python modules using ADD command.Below is the python project structure. How to ADD all modules in Dockerfile?

-Myproject_rootdirectory
  -- Client
    - __init__.py
    - Main.py

  --Subscriber1
   - domain1
     - __init__.py
     - d2.py
  - domain2
     - __init__.py
     - d2.py
  - __init__.py

 --Subscriber2
   - domain3
     - __init__.py
     - d3.py
   - domain4
     - __init__.py
     - d4.py
   - __init__.py

Body:
It generally is recommended to use COPY before ADD, because it serves a lesser purpose and is somewhat more lightweight.

To copy your whole directory into the image, just add the following line after editing:

 COPY . /path/to/dir/in/image

Some helpful links to start writing dockerfiles:

Reference

Best Practices

Postgresql example


问:
Error:Could not find any matches for com.opentok.android:opentok-accelerator-core:1.0.+
I am integrating video calling functionality in my app using opentok sdk.
I have followed this this and i have successfully integrated.
All were working fine untill today i got this error

```<code>Error:Could not find any matches for com.opentok.android:opentok-accelerator-core:1.0.+ as no versions of com.opentok.android:opentok-accelerator-core are available.
Required by:
    project :app
</code>```

Can anyone tell me what this error is all about?
 I have tried cleaning,building and Invalid Caches/Restart but nothing works

答:
It seems that there is a problem with the maven url  'http://tokbox.bintray.com/maven'

Why you don't integrate the module   Using the repository

Clone the accelerator core android repository.

Start Android Studio and open your project.

From your project, right-click the app name and select New >
Module > Import Gradle Project.

Navigate to the directory in which you cloned OpenTok Accelerator
Core Android, select accelerator-core, and click Finish.

Open the build.gradle file for the app and ensure the following
lines have been added to the dependencies section:

compile project(':accelerator-core-android')

Updated: Or you can integrate this jar (jar of opentok library)

Body:
I am integrating video calling functionality in my app using opentok sdk.
I have followed this this and i have successfully integrated.
All were working fine untill today i got this error

Error:Could not find any matches for com.opentok.android:opentok-accelerator-core:1.0.+ as no versions of com.opentok.android:opentok-accelerator-core are available.
Required by:
    project :app

Can anyone tell me what this error is all about?
 I have tried cleaning,building and Invalid Caches/Restart but nothing works


问:
Check variable equality against a list of values
I'm checking a variable, say foo, for equality to a number of values. For example,

```<code>if( foo == 1 || foo == 3 || foo == 12 ) {
    // ...
}
</code>```

The point is that it is rather much code for such a trivial task. I came up with the following:

```<code>if( foo in {1: 1, 3: 1, 12: 1} ) {
    // ...
}
</code>```

but also this does not completely appeal to me, because I have to give redundant values to the items in the object.

Does anyone know a decent way of doing an equality check against multiple values?

答:
This is easily extendable and readable:

```<code>switch (foo) {
    case 1:
    case 3:
    case 12:
        // ...
        break

    case 4:
    case 5:
    case 6:
        // something else
        break
}
</code>```

But not necessarily easier :)

Body:
I'm checking a variable, say foo, for equality to a number of values. For example,

if( foo == 1 || foo == 3 || foo == 12 ) {
    // ...
}

The point is that it is rather much code for such a trivial task. I came up with the following:

if( foo in {1: 1, 3: 1, 12: 1} ) {
    // ...
}

but also this does not completely appeal to me, because I have to give redundant values to the items in the object.

Does anyone know a decent way of doing an equality check against multiple values?

Body:
This is easily extendable and readable:

switch (foo) {
    case 1:
    case 3:
    case 12:
        // ...
        break

    case 4:
    case 5:
    case 6:
        // something else
        break
}

But not necessarily easier :)

ContentLicense: CC BY-SA 2.5


问:
Structured Data (schema.org) - openingHours for EducationalOrganization
I'm just about to expand my templates with schema.org attributes and have the following question. With which property can I specify the opening hours for the type EducationalOrganization? Unfortunately, the openingHours property is not available here. In addition, there is no type similar to the EducationalOrganization type.

Here is the current state of my code:

```<code><div itemscope itemtype="http://schema.org/EducationalOrganization" class="ce_text address block">
    <div class="text_container">
        <p>
            <span>
                <strong itemprop="name"><?php echo $this->field('company')->value(); ?></strong><br>
            </span>
        <p itemscope itemtype="http://schema.org/PostalAddress" itemprop="address">
            <span itemprop="streetAddress">
                <?php echo $this->field('street')->value(); ?><br>
            </span>
            <span itemprop="postalCode">
                <?php echo $this->field('zipcode')->value(); ?>
            </span>
            <span itemprop="addressLocality">
                <?php echo $this->field('place')->value(); ?>
            </span>
        </p>
        <p>
            Aus dem Ausland: <span itemprop="telephone"><?php echo $this->field('phone_foreign')->value(); ?></span><br>
            Fax: <span itemprop="telephone"><?php echo $this->field('fax')->value(); ?></span>
        </p>
        <p itemscope itemtype="??????"> <!-- What type can I use here? -->
            <strong>Öffnungszeiten:</strong><br>
            Montag bis Donnerstag: <meta itemprop="openingHours" content="Mo-Th 08:00-18:00"><?php echo $this->field('mothu')->value(); ?><br>
            Freitag: <meta itemprop="openingHours" content="Fr 08:00-15:00"><?php echo $this->field('fri')->value(); ?>
        </p> <!-- Öffnungszeiten Ende -->
    </div>
</div>
</code>```

What type can I use in this case to use the itemprop="openingHours" property or is there another workarount, if this is not possible?

UPDATE:

I have chosen this solution in the meantime. It is read out cleanly by Google and makes more sense in the case of our company.

```<code>    <div itemscope itemtype="http://schema.org/Service">
        <strong>Öffnungszeiten:</strong><br>
        Montag bis Donnerstag: <?php echo $this->field('mothu')->value(); ?><br>
        Freitag: <?php echo $this->field('fri')->value(); ?>
        <div itemprop="hoursAvailable" itemscope itemtype="http://schema.org/OpeningHoursSpecification">
            <link itemprop="dayOfWeek" href="http://schema.org/Monday" />
            <time itemprop="opens" content="08:00:00"></time>
            <time itemprop="closes" content="18:00:00"></time>
        </div>
        <div itemprop="hoursAvailable" itemscope itemtype="http://schema.org/OpeningHoursSpecification">
            <link itemprop="dayOfWeek" href="http://schema.org/Tuesday" />
            <time itemprop="opens" content="08:00:00"></time>
            <time itemprop="closes" content="18:00:00"></time>
        </div>
        <div itemprop="hoursAvailable" itemscope itemtype="http://schema.org/OpeningHoursSpecification">
            <link itemprop="dayOfWeek" href="http://schema.org/Wednesday" />
            <time itemprop="opens" content="08:00:00"></time>
            <time itemprop="closes" content="18:00:00"></time>
        </div>
        <div itemprop="hoursAvailable" itemscope itemtype="http://schema.org/OpeningHoursSpecification">
            <link itemprop="dayOfWeek" href="http://schema.org/Thursday" />
            <time itemprop="opens" content="08:00:00"></time>
            <time itemprop="closes" content="18:00:00"></time>
        </div>
        <div itemprop="hoursAvailable" itemscope itemtype="http://schema.org/OpeningHoursSpecification">
            <link itemprop="dayOfWeek" href="http://schema.org/Friday" />
            <time itemprop="opens" content="08:00:00"></time>
            <time itemprop="closes" content="15:00:00"></time>
        </div>
    </div>
</code>```

答:
Try CivicStructure or GovernmentOffice.

For Educational Organisations such as school, university there is no need to scope the opening hours. Maybe your organisation is not Educational and you can use another scope for your organisation.

Body:
I'm just about to expand my templates with schema.org attributes and have the following question. With which property can I specify the opening hours for the type EducationalOrganization? Unfortunately, the openingHours property is not available here. In addition, there is no type similar to the EducationalOrganization type.

Here is the current state of my code:

                <?php echo $this->field('company')->value(); ?>

                <?php echo $this->field('street')->value(); ?>

                <?php echo $this->field('zipcode')->value(); ?>

                <?php echo $this->field('place')->value(); ?>

            Aus dem Ausland: <?php echo $this->field('phone_foreign')->value(); ?>

            Fax: <?php echo $this->field('fax')->value(); ?>

            Öffnungszeiten:

            Montag bis Donnerstag: <meta itemprop="openingHours" content="Mo-Th 08:00-18:00"><?php echo $this->field('mothu')->value(); ?>

            Freitag: <meta itemprop="openingHours" content="Fr 08:00-15:00"><?php echo $this->field('fri')->value(); ?>

What type can I use in this case to use the itemprop="openingHours" property or is there another workarount, if this is not possible?

UPDATE:

I have chosen this solution in the meantime. It is read out cleanly by Google and makes more sense in the case of our company.

        Öffnungszeiten:

        Montag bis Donnerstag: <?php echo $this->field('mothu')->value(); ?>

        Freitag: <?php echo $this->field('fri')->value(); ?>

            <link itemprop="dayOfWeek" href="http://schema.org/Monday" />
            <time itemprop="opens" content="08:00:00"></time>
            <time itemprop="closes" content="18:00:00"></time>

            <link itemprop="dayOfWeek" href="http://schema.org/Tuesday" />
            <time itemprop="opens" content="08:00:00"></time>
            <time itemprop="closes" content="18:00:00"></time>

            <link itemprop="dayOfWeek" href="http://schema.org/Wednesday" />
            <time itemprop="opens" content="08:00:00"></time>
            <time itemprop="closes" content="18:00:00"></time>

            <link itemprop="dayOfWeek" href="http://schema.org/Thursday" />
            <time itemprop="opens" content="08:00:00"></time>
            <time itemprop="closes" content="18:00:00"></time>

            <link itemprop="dayOfWeek" href="http://schema.org/Friday" />
            <time itemprop="opens" content="08:00:00"></time>
            <time itemprop="closes" content="15:00:00"></time>


问:
How to extract lines that are within radius of cartesian coordinates
I have a data file that has the format of the following:

```<code>ATOM      4  N   ASP A   1     105.665  49.507  41.867  1.00 71.64           N
ATOM      5  CA  ASP A   1     105.992  48.589  42.982  1.00 70.20           C
ATOM      6  C   ASP A   1     107.024  49.191  43.936  1.00 69.70           C
</code>```

In row 1 the numbers (105.665, 49.507, and 41.867) are the columns of the coordinates (x,y,z). How do I extract the entire line with coordinates that are within a specified radius and output them in another file? The equation to correlate the coordinates to the radius is:

radius= SQRT(x^2 + y^2 +z^2)

Body:
I have a data file that has the format of the following:

ATOM      4  N   ASP A   1     105.665  49.507  41.867  1.00 71.64           N
ATOM      5  CA  ASP A   1     105.992  48.589  42.982  1.00 70.20           C
ATOM      6  C   ASP A   1     107.024  49.191  43.936  1.00 69.70           C

In row 1 the numbers (105.665, 49.507, and 41.867) are the columns of the coordinates (x,y,z). How do I extract the entire line with coordinates that are within a specified radius and output them in another file? The equation to correlate the coordinates to the radius is:

radius= SQRT(x^2 + y^2 +z^2)

Body:
I think you mean this:

awk -v R=124.44 '($7^2)+($8^2)+($9^2) < R^2' YourFile

Change the R=124.44 to match your radius.

Sample Output

ATOM      4  N   ASP A   1     105.665  49.507  41.867  1.00 71.64           N
ATOM      5  CA  ASP A   1     105.992  48.589  42.982  1.00 70.20           C


问:
ckecking and unchecking checkbox in dat.gui
I have a checkbox named autorotation.I want to mark that checkbox to false when user click any where in the scene...

```<code>controller = new function() {
    this.autorotation=true;
}
var gui = new dat.GUI();
f1 = gui.addFolder('Sphere');
autorotation=controller.autorotation;
q=f1.add(controller, 'autorotation').listen().onChange( function()
{
    autorotation=controller.autorotation;

});

function onDocumentMouseDown(event)
{
    controller.autorotation=false;
    //stop autorotation and uncheck the box.
    //user may check the box for rotation manually by clicking on checkbox.
}
</code>```

This code works.I want to mark uncheck through code.Controller.autorotation=false mark check box to false but does not stops auto rotation.If i stop rotation by autorotation=false.Then i have to click two times on checkbox to check it to true

答:
Your code works fine. You just didn't add an event listener to an object you want to get clicks.

Just for example, I added a canvas element and added the onDocumentMouseDown on its mouse down event.

From my point of view, there's no need to have that autorotation variable, as you already have contorller.autorotation, which you can easily to refer to.

controller = new function() {
    this.autorotation=true;
}
var gui = new dat.GUI();
f1 = gui.addFolder('Sphere');
q=f1.add(controller, 'autorotation').listen().onChange( function()
{
    autorotation=controller.autorotation;

});

scene.addEventListener("mousedown", onDocumentMouseDown, false);
function onDocumentMouseDown(event)
{
    controller.autorotation=false;
    //stop autorotation and uncheck the box.
    //user may check the box for rotation manually by clicking on checkbox.
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/dat-gui/0.6.5/dat.gui.min.js"></script>
<canvas id="scene" style="border:1px solid red;background-color:aqua;"></canvas></code>```

Body:
I have a checkbox named autorotation.I want to mark that checkbox to false when user click any where in the scene...

controller = new function() {
    this.autorotation=true;
}
var gui = new dat.GUI();
f1 = gui.addFolder('Sphere');
autorotation=controller.autorotation;
q=f1.add(controller, 'autorotation').listen().onChange( function()
{
    autorotation=controller.autorotation;

});

function onDocumentMouseDown(event)
{
    controller.autorotation=false;
    //stop autorotation and uncheck the box.
    //user may check the box for rotation manually by clicking on checkbox.
}

This code works.I want to mark uncheck through code.Controller.autorotation=false mark check box to false but does not stops auto rotation.If i stop rotation by autorotation=false.Then i have to click two times on checkbox to check it to true

Body:
Your code works fine. You just didn't add an event listener to an object you want to get clicks.

Just for example, I added a canvas element and added the onDocumentMouseDown on its mouse down event.

From my point of view, there's no need to have that autorotation variable, as you already have contorller.autorotation, which you can easily to refer to.

controller = new function() {
    this.autorotation=true;
}
var gui = new dat.GUI();
f1 = gui.addFolder('Sphere');
q=f1.add(controller, 'autorotation').listen().onChange( function()
{
    autorotation=controller.autorotation;

});

scene.addEventListener("mousedown", onDocumentMouseDown, false);
function onDocumentMouseDown(event)
{
    controller.autorotation=false;
    //stop autorotation and uncheck the box.
    //user may check the box for rotation manually by clicking on checkbox.
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/dat-gui/0.6.5/dat.gui.min.js"></script>
<canvas id="scene" style="border:1px solid red;background-color:aqua;"></canvas>


问:
Using C++11 variadic templates to initialize Enum To String Map
I think its possible to use Variadic template arguments introduced in C++11 for initializing a map which the keys are ints and values are string notation of given arguments.

If its possible i could simply create a map from Enum name to its string representation like this :

```<code>auto map = EnumStringMap<EnumType::Type1, EnumType::Type2>();
</code>```

I can initialize a list with enum int representations via this template

```<code>template<typename... Ts> auto enumList(Ts... args){
    QList<int> res = {args...};
    return res;
}

auto enums =  enumList<int, int>(Enums::Enum1, Enums::Enum2);
</code>```

I think it should be possible with STRINGFY C macro to get string representation of expression

```<code>#define STRINGIFY(x) #x
#define TOSTRING(x) STRINGIFY(x)
</code>```

But i can't figure out how to convert type name or type value to its string representation, so is it possible at all?
My goal is to produce a map of  which hold the string representation of enumrations in compile time.

The approaches like MOC used by qt isn't right for me, because i should enclose the enums in QObject which is heavy and non copyable.

答:
The macros are handled by the preprocessor, before any C++ compilation. Therefore you cannot use a macro inside a function to retrieve the C++ name of an enum value.

Most solutions are based on macro used at the point where the enum is defined. There are many implementation available on the Internet and it generally do something like that:

```<code>#define MY_ENUM(a, b, c) enum a {b , c} \
Map<a, string> mymap = {{b, STRINGIFY(b)}, {b, STRINGIFY(b)}};

MY_ENUM(Color, Red, Blue)
MY_ENUM(Align, Left, Right)
</code>```

Another approach is using meta compilers, that will process the C++ code to generate more code. This is what Qt does with its moc, and since you tagged your question with Qt, it might be the best way to go for you..

```<code>class FooBar : public QObject {
  Q_OBJECT
public:
  enum Action { Open, Save, New, Copy, Cut, Paste, Undo, Redo, Delete };
  Q_ENUM(Action) // Not Q_ENUMS !!!

  static QString convert(Action a) {
    auto metaEnum = QMetaEnum::fromType<Action>();
    return metaEnum.valueToKey(a);
  }
};
</code>```

This has some constraints, like the fact that the enum must be defined in a QObject (or a Q_GADGET). You can find out more in Qt documentation. For how it is done you can see Woboq article.

Body:
I think its possible to use Variadic template arguments introduced in C++11 for initializing a map which the keys are ints and values are string notation of given arguments.

If its possible i could simply create a map from Enum name to its string representation like this :

auto map = EnumStringMap<EnumType::Type1, EnumType::Type2>();

I can initialize a list with enum int representations via this template

template<typename... Ts> auto enumList(Ts... args){
    QList<int> res = {args...};
    return res;
}

auto enums =  enumList<int, int>(Enums::Enum1, Enums::Enum2);

I think it should be possible with STRINGFY C macro to get string representation of expression

#define STRINGIFY(x) #x
#define TOSTRING(x) STRINGIFY(x)

But i can't figure out how to convert type name or type value to its string representation, so is it possible at all?
My goal is to produce a map of  which hold the string representation of enumrations in compile time.

The approaches like MOC used by qt isn't right for me, because i should enclose the enums in QObject which is heavy and non copyable.

Body:
The macros are handled by the preprocessor, before any C++ compilation. Therefore you cannot use a macro inside a function to retrieve the C++ name of an enum value.

Most solutions are based on macro used at the point where the enum is defined. There are many implementation available on the Internet and it generally do something like that:

#define MY_ENUM(a, b, c) enum a {b , c} \
Map<a, string> mymap = {{b, STRINGIFY(b)}, {b, STRINGIFY(b)}};

MY_ENUM(Color, Red, Blue)
MY_ENUM(Align, Left, Right)

Another approach is using meta compilers, that will process the C++ code to generate more code. This is what Qt does with its moc, and since you tagged your question with Qt, it might be the best way to go for you..

class FooBar : public QObject {
  Q_OBJECT
public:
  enum Action { Open, Save, New, Copy, Cut, Paste, Undo, Redo, Delete };
  Q_ENUM(Action) // Not Q_ENUMS !!!

  static QString convert(Action a) {
    auto metaEnum = QMetaEnum::fromType<Action>();
    return metaEnum.valueToKey(a);
  }
};

This has some constraints, like the fact that the enum must be defined in a QObject (or a Q_GADGET). You can find out more in Qt documentation. For how it is done you can see Woboq article.


问:
Cannot update data in MySQL Database using mysqli
Hello can someone assist me im failing to update the data in my mysql database</p>

```<code><?php
    require "connection.php";

    $item_name = "cheese";
    $item_code = 123;
    $item_description = "cheese is good";
    $item_unit_price  = 235;

    $mysql_query = "UPDATE Stock SET item_code = '$item_code',item_description = '$item_description',item_unit_price = '$item_unit_price' where item_name='$item_name')";

    //execute the query
    $result = mysqli_query($conn,$mysql_query);

    if($conn->query($mysql_query) ===TRUE){

    echo "Stock Item Updated Successfully";

    }else{

        echo 'Error'.$mysql_query."<br>".$conn->error;
    }

    $conn->close();

    ?>
</code>```

答:
Try this..!!</p>

```<code><?php
    $item_name = "cheese";
    $item_code = 123;
    $item_description = "cheese is good";
    $item_unit_price  = 235;

    $mysql_query = "UPDATE Stock SET item_code = '$item_code',item_description = '$item_description',item_unit_price = '$item_unit_price' where item_name='$item_name'";
    //execute the query
    $result = mysqli_query($conn , $mysql_query);
    if($result){
    echo "Stock Item Updated Successfully";
    }else{
        die('Invalid query: ' . mysqli_error($conn));
    }

    $conn->close();

?>
</code>```

Body:
Hello can someone assist me im failing to update the data in my mysql database

<?php
    require "connection.php";

    $item_name = "cheese";
    $item_code = 123;
    $item_description = "cheese is good";
    $item_unit_price  = 235;

    $mysql_query = "UPDATE Stock SET item_code = '$item_code',item_description = '$item_description',item_unit_price = '$item_unit_price' where item_name='$item_name')";

    //execute the query
    $result = mysqli_query($conn,$mysql_query);

    if($conn->query($mysql_query) ===TRUE){

    echo "Stock Item Updated Successfully";

    }else{

        echo 'Error'.$mysql_query."
".$conn->error;
    }

    $conn->close();

    ?>

Body:
Try this..!!

<?php
    $item_name = "cheese";
    $item_code = 123;
    $item_description = "cheese is good";
    $item_unit_price  = 235;

    $mysql_query = "UPDATE Stock SET item_code = '$item_code',item_description = '$item_description',item_unit_price = '$item_unit_price' where item_name='$item_name'";
    //execute the query
    $result = mysqli_query($conn , $mysql_query);
    if($result){
    echo "Stock Item Updated Successfully";
    }else{
        die('Invalid query: ' . mysqli_error($conn));
    }

    $conn->close();

?>


问:
Howto update the JavaDoc of a function in IntelliJ
I have a function A(int x) with my JavaDoc
/**
* @param a
*/

Now I add a new parameter to A -> A(int x, int y).

Is there a shortkey to update the JavaDoc or do I have to do it myself by adding the line manually ?

答:
in the link above Mark McDonald  mentions the option of:

For anyone else searching for how to get IntelliJ to update javadoc after a code change, you can set this in Settings -> IDE Settings -> Keymap.


问:
Running aiohttp server using gunicorn
I am trying to run a aiohttp based server using Gunicorn.

Here is the command:

```<code>gunicorn aiohttpdemo_polls:app --bind 127.0.0.1:8080
</code>```

It returns:

```<code>Failed to find application: 'aiohttpdemo_polls'
</code>```

But when I am running it using python -m like below:

```<code>python -m aiohttpdemo_polls
</code>```

It works fine. The code can be found from here which is a demo app in the aiohttp repo.
Also tried it like below:

```<code>gunicorn aiohttpdemo_polls.main:app --bind 127.0.0.1:8080
</code>```

But its also not running the server. It returns

```<code>Failed to find application: 'aiohttpdemo_polls.main'
</code>```

Any idea where to look further for fixing the issue?

答:
The demo does not support gunicorn yet.

I filed an issue: https://github.com/aio-libs/aiohttp-demos/issues/10

Thanks for report.

Title: Running aiohttp server using gunicorn

Body:
I am trying to run a aiohttp based server using Gunicorn.

Here is the command:

gunicorn aiohttpdemo_polls:app --bind 127.0.0.1:8080

It returns:

Failed to find application: 'aiohttpdemo_polls'

But when I am running it using python -m like below:

python -m aiohttpdemo_polls

It works fine. The code can be found from here which is a demo app in the aiohttp repo.
Also tried it like below:

gunicorn aiohttpdemo_polls.main:app --bind 127.0.0.1:8080

But its also not running the server. It returns

Failed to find application: 'aiohttpdemo_polls.main'

Any idea where to look further for fixing the issue?


问:
ScrollBar in DataGridView
I have a winform in vs2008 that contains a DataGridView. The datagrid contains a list with several columns. These are fixed width, exept one that I have set up to take whatever space is left and fill the width of the view. The winform is resizeable in all directions.

The issue I am trying to solve is that when I increase the vertical size of the window the scrollbar disappears and the columns snap to the right to fill the extra space. What I would like to happen is that the vertical scrollBar never disappears. Setting ScrollBars to vertical in the properties of the DataGridView does not do this.

Is this at all possible to achieve? And, if so, how do I get the vertical scrollbar to always be visible?

答:
Try subclassing the DataGridView and handling the VerticalScrollBar's VisibleChanged event. You should be able to set the Visible property to True in there, overriding the default behaviour.

Something like this, I think...

```<code>public class SubclassedDataGridView : DataGridView
    {
        public SubclassedDataGridView (): base()
        {
            VerticalScrollBar.VisibleChanged += new EventHandler(VerticalScrollBar_VisibleChanged);
        }

        void VerticalScrollBar_VisibleChanged(object sender, EventArgs e)
        {
            VerticalScrollBar.Visible = true;
        }
     }
</code>```

OwnerDisplayName: Sakkle

Title: ScrollBar in DataGridView

LastEditorDisplayName: Sakkle

Body:
Try subclassing the DataGridView and handling the VerticalScrollBar's VisibleChanged event. You should be able to set the Visible property to True in there, overriding the default behaviour.

Something like this, I think...

public class SubclassedDataGridView : DataGridView
    {
        public SubclassedDataGridView (): base()
        {
            VerticalScrollBar.VisibleChanged += new EventHandler(VerticalScrollBar_VisibleChanged);
        }

        void VerticalScrollBar_VisibleChanged(object sender, EventArgs e)
        {
            VerticalScrollBar.Visible = true;
        }
     }

OwnerDisplayName: gkrogers


问:
NSXMLParser example
I have an XML like this

```<code><IS>
    <Value>
        <Signature>-804</Signature>
        <Amount>139</Amount>
    </Value>
    <Value>
        <Signature>-845</Signature>
        <Amount>639466</Amount>
    </Value>
    <Value>
        <Signature>-811</Signature>
        <Amount>16438344</Amount>
    </Value>
    <Value>
        <Signature>-1115</Signature>
        <Amount>-159733</Amount>
    </Value>
</IS>
</code>```

Now I want to parse only specific values from this.
For example, how do I get the  value for the node having corresponding signature as -804

Please help me..

I know the basics of NSXMLParser, but do not know how to acheive conditional parsing.

Thank you.

答:
You may want to look into using TouchXML - https://github.com/mrevilme/TouchXML which offers some nice XML handling features including the use of XPATH which makes what you are trying to do much simpler.

A hypothetical example based on your model:

```<code>//first, load an XML document
CXMLDocument *xmlDoc = [[CXMLDocument alloc] initWithXMLString:someXMLString options:0 error:&error];

//get node
CXMLNode *amountNode = [xmlDoc nodeForXPath:@"//Value[@Signature='-804']/Amount" error:&error];

//or get actual value of node
NSSString *amountString =  = [[xmlDoc nodeForXPath:@"//Value[@Signature='-804']/Amount" error:&error] stringValue];
</code>```

Note: None of these exapmles are tested.

I have found TouchXML very useful and compact.

Hope this helps.

Title: NSXMLParser example

Body:
I have an XML like this

<IS>
    <Value>
        <Signature>-804</Signature>
        <Amount>139</Amount>
    </Value>
    <Value>
        <Signature>-845</Signature>
        <Amount>639466</Amount>
    </Value>
    <Value>
        <Signature>-811</Signature>
        <Amount>16438344</Amount>
    </Value>
    <Value>
        <Signature>-1115</Signature>
        <Amount>-159733</Amount>
    </Value>
</IS>

Now I want to parse only specific values from this.
For example, how do I get the  value for the node having corresponding signature as -804

Please help me..

I know the basics of NSXMLParser, but do not know how to acheive conditional parsing.

Thank you.

Body:
You may want to look into using TouchXML - https://github.com/mrevilme/TouchXML which offers some nice XML handling features including the use of XPATH which makes what you are trying to do much simpler.

A hypothetical example based on your model:

//first, load an XML document
CXMLDocument *xmlDoc = [[CXMLDocument alloc] initWithXMLString:someXMLString options:0 error:&error];

//get node
CXMLNode *amountNode = [xmlDoc nodeForXPath:@"//Value[@Signature='-804']/Amount" error:&error];

//or get actual value of node
NSSString *amountString =  = [[xmlDoc nodeForXPath:@"//Value[@Signature='-804']/Amount" error:&error] stringValue];

Note: None of these exapmles are tested.

I have found TouchXML very useful and compact.

Hope this helps.


问:
AsynchronousServerSocketChannel concurrent accepting
In the example of official doc,seems that we should accept connection one by one.This makes me confused,so I read the source code of sun.nio.ch.UnixAsynchronousServerSocketChannelImpl ,in the line 269 there is a comment check and set flag to prevent concurrent accepting,So could someone tell me why should prevent current accepting?
 Is this a OS's limit or there is no need to accept connection currently.Thanks in advance.

答: You are conflating concurrency with asynchronicity. When you accept a connection via async I/O you should immediately schedule another asynchronous accept().


问:
Representation with, scale_fill_gradientn ggplot2, constant gradient
I have the following code to create a polar plot with ggplot2 but I am not be able to maintain the same scale color-values when I run the same code with other data.

There are 3 different variables to represent, one is the orientation:

```<code>plot.new()
ggplot(NS_Enero, aes(x = wd, y = ws, fill = manganese, size = manganese)) +
  coord_polar() +
  geom_point(shape = 21, show.legend = TRUE) +
  scale_size(range = c(3,12),
             labels = c("50", "150", "450", "1350", "4050"),
             breaks = c(50, 150, 450, 1350, 4050),
             name = expression(paste(PM[10]~bound~Mn~(ng/m^3)))) +
  scale_fill_gradientn(colours = c("darkblue","blue", "yellow", "orange", "red"),
                       space = "Lab",
                       guide = "legend",
                       values = rescale(c(0, 150, 450, 1350, 4401),
                                        from = c(0, 4401)),
                       labels = c("50", "150", "450", "1350", "4050"),
                       breaks = c(50, 150, 450, 1350, 4050),
                       name = expression(paste(PM[10]~bound~Mn~(ng/m^3)))) +
  scale_x_continuous(limits= c(0,360),
                     breaks= c(0, 90, 180, 270),
                     labels = c("N","E","S","W"),
                     name = "") +
  scale_y_continuous(name = "Distance (m)",
                     position = "left") +
  theme_linedraw() +
  theme(axis.text.x = element_text(size = 12),
        axis.text.y = element_text(size = 8)) +
  ggtitle("                 NS_Enero")
</code>```

When I try to run the same code with different data the output plot change the values of the scale, I have tried a lot of tips that I found in other questions, but I can't solve the problem with the scale representation. I think that the problem is in the values from scale_fill_gradientn...

Output 1:

Output 2 (different data):

The final result is ok but I want that the values of the scale range (size and color) to be constant in all the plots that I run with different range of data. The same values of size and color for values between 0 to 4050.

Thank you very much for your help.

答:
Finally, adding limits it worked.

This is the final code:

```<code>#Tamaño y color
plot.new()
ggplot(NS_Junio, aes(x = wd, y = ws, fill = manganese, size = manganese)) +
  coord_polar() +
  geom_point(shape = 21, show.legend = TRUE) +
  scale_size(range = c(3,12),
             labels = c("50", "150", "450", "1350", "4050"),
             breaks = c(50, 150, 450, 1350, 4050),
             limits = c(1,4050),
             name = expression(paste(PM[10]~bound~Mn~(ng/m^3)))) +
  scale_fill_gradientn(colours = c("darkblue","blue", "yellow", "orange", "red"),
                       space = "Lab",
                       guide = "legend",
                       values = rescale(c(0, 150, 450, 1350, 4401),
                                        from = c(0, 4401)),
                       labels = c("50", "150", "450", "1350", "4050"),
                       breaks = c(50, 150, 450, 1350, 4050),
                       limits = c(1,4050),
                       name = expression(paste(PM[10]~bound~Mn~(ng/m^3)))) +
  scale_x_continuous(limits= c(0,360),
                     breaks= c(0, 90, 180, 270),
                     labels = c("N","E","S","W"),
                     name = "") +
  scale_y_continuous(name = "Distance (m)",
                     position = "left") +
  theme_linedraw() +
  theme(axis.text.x = element_text(size = 12),
        axis.text.y = element_text(size = 8)) +
  ggtitle("                 NS_Enero")
</code>```

Body:
I have the following code to create a polar plot with ggplot2 but I am not be able to maintain the same scale color-values when I run the same code with other data.

There are 3 different variables to represent, one is the orientation:

plot.new()
ggplot(NS_Enero, aes(x = wd, y = ws, fill = manganese, size = manganese)) +
  coord_polar() +
  geom_point(shape = 21, show.legend = TRUE) +
  scale_size(range = c(3,12),
             labels = c("50", "150", "450", "1350", "4050"),
             breaks = c(50, 150, 450, 1350, 4050),
             name = expression(paste(PM[10]~bound~Mn~(ng/m^3)))) +
  scale_fill_gradientn(colours = c("darkblue","blue", "yellow", "orange", "red"),
                       space = "Lab",
                       guide = "legend",
                       values = rescale(c(0, 150, 450, 1350, 4401),
                                        from = c(0, 4401)),
                       labels = c("50", "150", "450", "1350", "4050"),
                       breaks = c(50, 150, 450, 1350, 4050),
                       name = expression(paste(PM[10]~bound~Mn~(ng/m^3)))) +
  scale_x_continuous(limits= c(0,360),
                     breaks= c(0, 90, 180, 270),
                     labels = c("N","E","S","W"),
                     name = "") +
  scale_y_continuous(name = "Distance (m)",
                     position = "left") +
  theme_linedraw() +
  theme(axis.text.x = element_text(size = 12),
        axis.text.y = element_text(size = 8)) +
  ggtitle("                 NS_Enero")

When I try to run the same code with different data the output plot change the values of the scale, I have tried a lot of tips that I found in other questions, but I can't solve the problem with the scale representation. I think that the problem is in the values from scale_fill_gradientn...

Output 1:

Output 2 (different data):

The final result is ok but I want that the values of the scale range (size and color) to be constant in all the plots that I run with different range of data. The same values of size and color for values between 0 to 4050.

Thank you very much for your help.

Body:
Finally, adding limits it worked.

This is the final code:

#Tamaño y color
plot.new()
ggplot(NS_Junio, aes(x = wd, y = ws, fill = manganese, size = manganese)) +
  coord_polar() +
  geom_point(shape = 21, show.legend = TRUE) +
  scale_size(range = c(3,12),
             labels = c("50", "150", "450", "1350", "4050"),
             breaks = c(50, 150, 450, 1350, 4050),
             limits = c(1,4050),
             name = expression(paste(PM[10]~bound~Mn~(ng/m^3)))) +
  scale_fill_gradientn(colours = c("darkblue","blue", "yellow", "orange", "red"),
                       space = "Lab",
                       guide = "legend",
                       values = rescale(c(0, 150, 450, 1350, 4401),
                                        from = c(0, 4401)),
                       labels = c("50", "150", "450", "1350", "4050"),
                       breaks = c(50, 150, 450, 1350, 4050),
                       limits = c(1,4050),
                       name = expression(paste(PM[10]~bound~Mn~(ng/m^3)))) +
  scale_x_continuous(limits= c(0,360),
                     breaks= c(0, 90, 180, 270),
                     labels = c("N","E","S","W"),
                     name = "") +
  scale_y_continuous(name = "Distance (m)",
                     position = "left") +
  theme_linedraw() +
  theme(axis.text.x = element_text(size = 12),
        axis.text.y = element_text(size = 8)) +
  ggtitle("                 NS_Enero")


问:
Trying to get the value from sweetalert
I'm trying to get the return value in sweetalert but I got this

```<code>Promise {<pending>}
  >__proto_:Promise
  [[PromiseStatus]]: "resolved"
  [[PromiseValue]]:true
</code>```

from this code

```<code>var ret = swal({
  title: "Conflict",
  text: "You have the same schedule with "+response.data.title,
  icon: "warning",
  buttons: {
    cancel: {
      text: "Save Anyway",
      value: true,
      visible: true
    },
    confirm: {
      text: "Cancel",
      value: null
    }
  }
})
.then((value) => {
  if (value == true) {
    return true;
  } else {
    return false;
  }
});

console.log(ret); // Nag stop ko ani kay wala ko kabalo pa sa promise
</code>```

What I want is to get to get the boolean value from the sweetalert. I'm trying this for hours but no luck.

I also tried this

```<code>console.log(ret.resolved);
console.log(ret.PromiseStatus);
</code>```

and similar other but, got undefined Has anyone tried what I did?

答:
The Promise object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value.

A Promise is in one of these states:

pending: initial state, neither fulfilled nor rejected.

fulfilled: meaning that the operation completed successfully.

rejected: meaning that the operation failed.

Promise.resolve(value)
Returns a Promise object that is resolved with the given value.

If the value is a thenable (i.e. has a then method), the returned promise will "follow" that thenable, adopting its eventual state; otherwise the returned promise will be fulfilled with the value.

Generally, if you don't know if a value is a promise or not, Promise.resolve(value) it instead and work with the return value as a promise.

An example for what you are trying to achieve, using the static Promise.resolve method

```<code>Promise.resolve('Success').then(function(value) {
  console.log(value); // "Success"
}, function(value) {
  // not called
});
</code>```

Sources: Mozilla documentation

Title: Trying to get the value from sweetalert

Body:
I'm trying to get the return value in sweetalert but I got this

Promise {<pending>}
  >__proto_:Promise
  [[PromiseStatus]]: "resolved"
  [[PromiseValue]]:true

from this code

var ret = swal({
  title: "Conflict",
  text: "You have the same schedule with "+response.data.title,
  icon: "warning",
  buttons: {
    cancel: {
      text: "Save Anyway",
      value: true,
      visible: true
    },
    confirm: {
      text: "Cancel",
      value: null
    }
  }
})
.then((value) => {
  if (value == true) {
    return true;
  } else {
    return false;
  }
});

console.log(ret); // Nag stop ko ani kay wala ko kabalo pa sa promise

What I want is to get to get the boolean value from the sweetalert. I'm trying this for hours but no luck.

I also tried this

console.log(ret.resolved);
console.log(ret.PromiseStatus);

and similar other but, got undefined Has anyone tried what I did?

Body:
The Promise object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value.

A Promise is in one of these states:

pending: initial state, neither fulfilled nor rejected.

fulfilled: meaning that the operation completed successfully.

rejected: meaning that the operation failed.

Promise.resolve(value)
Returns a Promise object that is resolved with the given value.

If the value is a thenable (i.e. has a then method), the returned promise will "follow" that thenable, adopting its eventual state; otherwise the returned promise will be fulfilled with the value.

Generally, if you don't know if a value is a promise or not, Promise.resolve(value) it instead and work with the return value as a promise.

An example for what you are trying to achieve, using the static Promise.resolve method

Promise.resolve('Success').then(function(value) {
  console.log(value); // "Success"
}, function(value) {
  // not called
});

Sources: Mozilla documentation


问:
Changing imageview present in recently clicked listitem in android ListView
Here I am trying to make a music streaming app which works using an API, and I have utilized the MusicPlayer class available in Android. Here what I am trying to do is to get the response from the API in a listview and then click on any item in the listview to stream that particular song. The songs are present on a server and I am getting the correct responses from the server and music streaming is also implemented correctly according to me. The music progress is shown with the help of a SeekBar and I am 100% sure it is also working as I wanted it to be.

The new thing which I added to it recently is that, whenever I click on a particular song item from list, the headphone icon present on left of that item changes to play icon as shown in the screenshot attached below

Screenshot of the app from my phone

Here, play icon on left of songs show that they are recently played, but I want play icon only on those songs which is currently playing, not on recently played songs too.

But I cannot figure out way to do this, I have tried some things like

Storing the clicked item position somewhere in the class, to use it later.

Searching on internet, a way to modify only those list item which are not clicked in listview.

Modifying the image resource of the  recently clicked item when stop icon is clicked.

But 3rd one didn't work, and haven't found a way to achieve the 1st and 2nd one..

Code snippet of ListView implementation

```<code>        CustomSongList adapter = new CustomSongList(Songs.this, songdetails);
        list = (ListView) findViewById(R.id.list);

        list.setAdapter(adapter);
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                url = songdetails.get(position).getUrl(); // your URl
                pos = position;
                ImageView listenImage = (ImageView) view.findViewById(R.id.musicicon);
                listenImage.setImageResource(R.drawable.play);   /* I am changing icon from headphone icon to play icon here*/

                if (mediaPlayer != null) {
                    mediaPlayer.stop();
                }

                mediaPlayer = new MediaPlayer();
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                try {
                    mediaPlayer.setDataSource(url);
                    mediaPlayer.prepare();
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (SecurityException e) {
                    e.printStackTrace();
                } catch (IllegalStateException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                mediaFileLengthInMilliseconds = mediaPlayer.getDuration();// gets the song length in milliseconds from URL
                mediaPlayer.start();
                imPlay.setVisibility(View.INVISIBLE);
                imPause.setVisibility(View.VISIBLE);
                primarySeekBarProgressUpdater();
            }
        });
</code>```

Here is a code snippet of ListView Adapter class.

```<code>public View getView(int position, View view, ViewGroup parent) {
    LayoutInflater inflater = context.getLayoutInflater();

    View rowView = inflater.inflate(R.layout.songlist_item, null, true);

    TextView Title = (TextView) rowView.findViewById(R.id.title);
    TextView Singer = (TextView) rowView.findViewById(R.id.singer);
    TextView Duration = (TextView) rowView.findViewById(R.id.duration);

    Title.setText(songlist.get(position).getTitle());
    Singer.setText("Singer : " + songlist.get(position).getSinger());
    Duration.setText("Duration : " + songlist.get(position).getDuration()+" mins");
    return rowView;
}
</code>```

And this is the snippet of songs layout file

```<code><ListView
    android:id="@+id/list"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_above="@+id/seekBar"
    android:layout_below="@+id/songheading"
    android:layout_margin="10dp"
    android:background="@android:color/transparent"
    android:cacheColorHint="@android:color/transparent"
    android:divider="@drawable/transperent_color"
    android:dividerHeight="5dip" />

<SeekBar
    android:id="@+id/seekBar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_above="@+id/buttonPlay" />

<ImageView
    android:id="@+id/buttonPlay"
    android:layout_width="50dp"
    android:layout_height="50dp"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:background="@drawable/play" />

<ImageView
    android:id="@+id/buttonPause"
    android:layout_width="50dp"
    android:layout_height="50dp"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:background="@drawable/pause" />

<ImageView
    android:id="@+id/buttonStop"
    android:layout_width="60dp"
    android:layout_height="60dp"
    android:layout_alignParentBottom="true"
    android:layout_alignParentEnd="true"
    android:background="@drawable/stop" />
</code>```

The headphone icon set for each item of listview is done by following code snippet

```<code> <ImageView
    android:id="@+id/musicicon"
    android:layout_width="50dp"
    android:layout_height="50dp"
    android:contentDescription="@string/app_name"
    android:gravity="center"
    android:layout_marginTop="10dp"
    android:src="@drawable/listen_icon" />
</code>```

Edit

Applied the solution given by @KalaBalik

thanks @KalaBalik for posting the steps to mark the song, but I have applied your steps step by step, and what I found is that my app now doesn't show the list itself, when loading is complete, here is the screenshot

And here are the edits performed by me on the code as you said

Code snippet of listview

```<code><ListView
    android:id="@+id/list"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_above="@+id/seekBar"
    android:layout_below="@+id/songheading"
    android:layout_margin="10dp"
    android:background="@android:color/transparent"
    android:cacheColorHint="@android:color/transparent"
    android:choiceMode="singleChoice"                       // -----here
    android:divider="@drawable/transperent_color"
    android:dividerHeight="5dip" />
</code>```

CheckedTextView implementation

```<code><CheckedTextView
        android:id="@+id/tvChecked"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:drawableStart="@drawable/playing" />
</code>```

Compound drawable for checkedTextview,

playing.xml

```<code><selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/play" android:state_checked="true" />
<item android:drawable="@drawable/listen_icon" />
</code>```

SpannableStringBuilder implementation

```<code>String finalString = title + "\n" + singer + "\n" + duration;
    SpannableStringBuilder sb = new SpannableStringBuilder();
    Typeface exoMedium = Typeface.createFromAsset(context.getAssets(), "fonts/Exo-Medium.ttf");
    TypefaceSpan exoMediumSpan = new CustomTypeFaceSpan("", exoMedium);
    sb.setSpan(exoMediumSpan, finalString.indexOf(title), title.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    sb.setSpan(new ForegroundColorSpan(Color.BLUE), finalString.indexOf(singer), singer.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    sb.setSpan(new ForegroundColorSpan(Color.CYAN), finalString.indexOf(duration), duration.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
</code>```

I have created a CustomTypeFaceSpan using this link

setting SpannableStringBuilder in checkedTextView  holder.checkedTextView.setText(sb);  here I Used ViewHolder pattern

and setting listview checked true when item clicked

```<code>list.setAdapter(adapter);
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                list.setItemChecked(position, true);
</code>```

But result is in the screenshot above, tell me where I have done something wrong.

答:
The code you linked does not contain all the changes I proposed. For example, songlist_item does not reference the selector. Most importantly, I do not want to deal with the details of MediaPlayer prepare callbacks. Therefore I made a minimal, yet complete and verifiable example of your problem. Please test and understand the code separately and then weave it into your project.

MainActivity:

```<code>public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final ListView listView = findViewById(R.id.list);
        ArrayList<String> songdetails = new ArrayList<>();
        songdetails.add("Song1");
        songdetails.add("Song2");
        songdetails.add("Song3");
        CustomArrayAdapter adapter = new CustomArrayAdapter(this, R.layout.listitem, songdetails);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                listView.setItemChecked(i, true);
                // the selected song can be found at position i of songdetails
                // start playing the selected song here
            }
        });
    }
}
</code>```

CustomArrayAdapter:

```<code>public class CustomArrayAdapter extends ArrayAdapter<String> {

    private final Activity context;
    private final int resource;
    private ArrayList<String> songlist;

    CustomArrayAdapter(Activity context, int resource, ArrayList<String> songlist) {
        super(context, resource);
        this.context = context;
        this.resource = resource;
        this.songlist = songlist;
    }

    @Override
    public int getCount() {
        return songlist.size();
    }

    @NonNull
    @Override
    public View getView(int position, View convertView, @NonNull ViewGroup parent) {
        final ViewHolder holder;
        String song = songlist.get(position);

        LayoutInflater inflater = context.getLayoutInflater();
        if (convertView == null) {
            convertView = inflater.inflate(resource, parent, false);
            holder = new ViewHolder(convertView);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        holder.checkedTextView.setText(song);

        return convertView;
    }

    static class ViewHolder {
        final CheckedTextView checkedTextView;

        private ViewHolder(View convertView) {
            checkedTextView = convertView.findViewById(R.id.tvChecked);
        }
    }
}
</code>```

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/list"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:choiceMode="singleChoice" />
</code>```

listitem.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/tvChecked"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:drawableStart="@drawable/checkedstatelist" />
</code>```

And checkedstatelist.xml (residing in res/drawable/):

```<code><?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@android:drawable/ic_media_play" android:state_checked="true" />
    <item android:drawable="@android:drawable/ic_media_pause" android:state_checked="false" />
</selector>
</code>```

And this is the result:

Body:
Here I am trying to make a music streaming app which works using an API, and I have utilized the MusicPlayer class available in Android. Here what I am trying to do is to get the response from the API in a listview and then click on any item in the listview to stream that particular song. The songs are present on a server and I am getting the correct responses from the server and music streaming is also implemented correctly according to me. The music progress is shown with the help of a SeekBar and I am 100% sure it is also working as I wanted it to be.

The new thing which I added to it recently is that, whenever I click on a particular song item from list, the headphone icon present on left of that item changes to play icon as shown in the screenshot attached below

Screenshot of the app from my phone

Here, play icon on left of songs show that they are recently played, but I want play icon only on those songs which is currently playing, not on recently played songs too.

But I cannot figure out way to do this, I have tried some things like

Storing the clicked item position somewhere in the class, to use it later.

Searching on internet, a way to modify only those list item which are not clicked in listview.

Modifying the image resource of the  recently clicked item when stop icon is clicked.

But 3rd one didn't work, and haven't found a way to achieve the 1st and 2nd one..

Code snippet of ListView implementation

        CustomSongList adapter = new CustomSongList(Songs.this, songdetails);
        list = (ListView) findViewById(R.id.list);

        list.setAdapter(adapter);
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                url = songdetails.get(position).getUrl(); // your URl
                pos = position;
                ImageView listenImage = (ImageView) view.findViewById(R.id.musicicon);
                listenImage.setImageResource(R.drawable.play);   /* I am changing icon from headphone icon to play icon here*/

                if (mediaPlayer != null) {
                    mediaPlayer.stop();
                }

                mediaPlayer = new MediaPlayer();
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                try {
                    mediaPlayer.setDataSource(url);
                    mediaPlayer.prepare();
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (SecurityException e) {
                    e.printStackTrace();
                } catch (IllegalStateException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                mediaFileLengthInMilliseconds = mediaPlayer.getDuration();// gets the song length in milliseconds from URL
                mediaPlayer.start();
                imPlay.setVisibility(View.INVISIBLE);
                imPause.setVisibility(View.VISIBLE);
                primarySeekBarProgressUpdater();
            }
        });

Here is a code snippet of ListView Adapter class.

public View getView(int position, View view, ViewGroup parent) {
    LayoutInflater inflater = context.getLayoutInflater();

    View rowView = inflater.inflate(R.layout.songlist_item, null, true);

    TextView Title = (TextView) rowView.findViewById(R.id.title);
    TextView Singer = (TextView) rowView.findViewById(R.id.singer);
    TextView Duration = (TextView) rowView.findViewById(R.id.duration);

    Title.setText(songlist.get(position).getTitle());
    Singer.setText("Singer : " + songlist.get(position).getSinger());
    Duration.setText("Duration : " + songlist.get(position).getDuration()+" mins");
    return rowView;
}

And this is the snippet of songs layout file

<ListView
    android:id="@+id/list"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_above="@+id/seekBar"
    android:layout_below="@+id/songheading"
    android:layout_margin="10dp"
    android:background="@android:color/transparent"
    android:cacheColorHint="@android:color/transparent"
    android:divider="@drawable/transperent_color"
    android:dividerHeight="5dip" />

<SeekBar
    android:id="@+id/seekBar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_above="@+id/buttonPlay" />

<ImageView
    android:id="@+id/buttonPlay"
    android:layout_width="50dp"
    android:layout_height="50dp"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:background="@drawable/play" />

<ImageView
    android:id="@+id/buttonPause"
    android:layout_width="50dp"
    android:layout_height="50dp"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:background="@drawable/pause" />

<ImageView
    android:id="@+id/buttonStop"
    android:layout_width="60dp"
    android:layout_height="60dp"
    android:layout_alignParentBottom="true"
    android:layout_alignParentEnd="true"
    android:background="@drawable/stop" />

The headphone icon set for each item of listview is done by following code snippet

 <ImageView
    android:id="@+id/musicicon"
    android:layout_width="50dp"
    android:layout_height="50dp"
    android:contentDescription="@string/app_name"
    android:gravity="center"
    android:layout_marginTop="10dp"
    android:src="@drawable/listen_icon" />

Edit

Applied the solution given by @KalaBalik

thanks @KalaBalik for posting the steps to mark the song, but I have applied your steps step by step, and what I found is that my app now doesn't show the list itself, when loading is complete, here is the screenshot

And here are the edits performed by me on the code as you said

Code snippet of listview

<ListView
    android:id="@+id/list"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_above="@+id/seekBar"
    android:layout_below="@+id/songheading"
    android:layout_margin="10dp"
    android:background="@android:color/transparent"
    android:cacheColorHint="@android:color/transparent"
    android:choiceMode="singleChoice"                       // -----here
    android:divider="@drawable/transperent_color"
    android:dividerHeight="5dip" />

CheckedTextView implementation

<CheckedTextView
        android:id="@+id/tvChecked"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:drawableStart="@drawable/playing" />

Compound drawable for checkedTextview,

playing.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/play" android:state_checked="true" />
<item android:drawable="@drawable/listen_icon" />

SpannableStringBuilder implementation

String finalString = title + "\n" + singer + "\n" + duration;
    SpannableStringBuilder sb = new SpannableStringBuilder();
    Typeface exoMedium = Typeface.createFromAsset(context.getAssets(), "fonts/Exo-Medium.ttf");
    TypefaceSpan exoMediumSpan = new CustomTypeFaceSpan("", exoMedium);
    sb.setSpan(exoMediumSpan, finalString.indexOf(title), title.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    sb.setSpan(new ForegroundColorSpan(Color.BLUE), finalString.indexOf(singer), singer.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    sb.setSpan(new ForegroundColorSpan(Color.CYAN), finalString.indexOf(duration), duration.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

I have created a CustomTypeFaceSpan using this link

setting SpannableStringBuilder in checkedTextView  holder.checkedTextView.setText(sb);  here I Used ViewHolder pattern

and setting listview checked true when item clicked

list.setAdapter(adapter);
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                list.setItemChecked(position, true);

But result is in the screenshot above, tell me where I have done something wrong.

Body:
The code you linked does not contain all the changes I proposed. For example, songlist_item does not reference the selector. Most importantly, I do not want to deal with the details of MediaPlayer prepare callbacks. Therefore I made a minimal, yet complete and verifiable example of your problem. Please test and understand the code separately and then weave it into your project.

MainActivity:

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final ListView listView = findViewById(R.id.list);
        ArrayList<String> songdetails = new ArrayList<>();
        songdetails.add("Song1");
        songdetails.add("Song2");
        songdetails.add("Song3");
        CustomArrayAdapter adapter = new CustomArrayAdapter(this, R.layout.listitem, songdetails);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                listView.setItemChecked(i, true);
                // the selected song can be found at position i of songdetails
                // start playing the selected song here
            }
        });
    }
}

CustomArrayAdapter:

public class CustomArrayAdapter extends ArrayAdapter<String> {

    private final Activity context;
    private final int resource;
    private ArrayList<String> songlist;

    CustomArrayAdapter(Activity context, int resource, ArrayList<String> songlist) {
        super(context, resource);
        this.context = context;
        this.resource = resource;
        this.songlist = songlist;
    }

    @Override
    public int getCount() {
        return songlist.size();
    }

    @NonNull
    @Override
    public View getView(int position, View convertView, @NonNull ViewGroup parent) {
        final ViewHolder holder;
        String song = songlist.get(position);

        LayoutInflater inflater = context.getLayoutInflater();
        if (convertView == null) {
            convertView = inflater.inflate(resource, parent, false);
            holder = new ViewHolder(convertView);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        holder.checkedTextView.setText(song);

        return convertView;
    }

    static class ViewHolder {
        final CheckedTextView checkedTextView;

        private ViewHolder(View convertView) {
            checkedTextView = convertView.findViewById(R.id.tvChecked);
        }
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/list"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:choiceMode="singleChoice" />

listitem.xml

<?xml version="1.0" encoding="utf-8"?>
<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/tvChecked"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:drawableStart="@drawable/checkedstatelist" />

And checkedstatelist.xml (residing in res/drawable/):

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@android:drawable/ic_media_play" android:state_checked="true" />
    <item android:drawable="@android:drawable/ic_media_pause" android:state_checked="false" />
</selector>

And this is the result: