问:
How to Run a jar from another jar and show the console output from the first runnable during the execution
I'm running a jar file from another jar like here somebody answers but waiting for the process.

```<code>Process proc = Runtime.getRuntime().exec("java -jar A.jar" + stringParams);

try {
    proc.waitFor();
} catch (InterruptedException e) {
    e.printStackTrace();
}

InputStream in = proc.getInputStream();
InputStream err = proc.getErrorStream();
</code>```

My problem comes when i have no feedback on the status of the program that is called, but i don't want my program continues beyond those lines. I would need the standard and error outputs but the results are shown when the execution is over. Is there any way of executing and getting those streams while the jar is still running?

答:
Buffered/unbuffered

It seems like an issue with buffered output.

Executed process (in this case java -jar <path>) buffers output and writes it only when it's done (in big chunks, we don't like that!)

So one way to go is execute process through unbuffering (very hacky tools):

unbuffered <command>

stdbuf -i0 -o0 -e0  <command>

use terminal emulation

Hacking

stdbuf is part of GNU tools.

https://www.gnu.org/software/coreutils/manual/html_node/stdbuf-invocation.html

unbuffered is part of expect package.

https://wiki.tcl.tk/3548

The key thing is making the program thinking that it's in interactive mode (like you are launching it from console).

The first two options are very hacky and do not work in all cases (idk if java command works with them?)

Emulation

The third option is most promising.
We launch a program (terminal emulator) that emulates interactive terminal making program think it's working in real active session!

Pty4j

You might use pty4j too:

From there: https://github.com/traff/pty4j

```<code>

    // The command to run in a PTY...
    String[] cmd = { "java", "-jar", "path_to_jar" };
    // The initial environment to pass to the PTY child process...
    String[] env = { "TERM=xterm" };

    PtyProcess pty = PtyProcess.exec(cmd, env);

    OutputStream os = pty.getOutputStream();
    InputStream is = pty.getInputStream();

    // ... work with the streams ...

    // wait until the PTY child process terminates...
    int result = pty.waitFor();

    // free up resources.
    pty.close();

</code>```

Zt-exec

Maybe it's worth trying zt-exec?

I have no idea how it executes commands.

But it may be it (I didn't test that).

Using https://github.com/zeroturnaround/zt-exec

```

    new ProcessExecutor().command("java", "-jar path_to_jar")
        .redirectOutput(new LogOutputStream() {
            @Override
            protected void processLine(String line) {
                ...
            }
        })
        .execute();

```

That should work, but I didn't test that.
In general, there are no ways to nicely resolve your problem.

Depending on what platforms you want to target consider using unbuffered, stdbuff or the (slowest) terminal emulation...

Please let me know if that helps and good luck! :)

Body:
I'm running a jar file from another jar like here somebody answers but waiting for the process.

Process proc = Runtime.getRuntime().exec("java -jar A.jar" + stringParams);

try {
    proc.waitFor();
} catch (InterruptedException e) {
    e.printStackTrace();
}

InputStream in = proc.getInputStream();
InputStream err = proc.getErrorStream();

My problem comes when i have no feedback on the status of the program that is called, but i don't want my program continues beyond those lines. I would need the standard and error outputs but the results are shown when the execution is over. Is there any way of executing and getting those streams while the jar is still running?

Body:
Buffered/unbuffered

It seems like an issue with buffered output.

Executed process (in this case java -jar <path>) buffers output and writes it only when it's done (in big chunks, we don't like that!)

So one way to go is execute process through unbuffering (very hacky tools):

unbuffered <command>

stdbuf -i0 -o0 -e0  <command>

use terminal emulation

Hacking

stdbuf is part of GNU tools.

https://www.gnu.org/software/coreutils/manual/html_node/stdbuf-invocation.html

unbuffered is part of expect package.

https://wiki.tcl.tk/3548

The key thing is making the program thinking that it's in interactive mode (like you are launching it from console).

The first two options are very hacky and do not work in all cases (idk if java command works with them?)

Emulation

The third option is most promising.
We launch a program (terminal emulator) that emulates interactive terminal making program think it's working in real active session!

Pty4j

You might use pty4j too:

From there: https://github.com/traff/pty4j

    // The command to run in a PTY...
    String[] cmd = { "java", "-jar", "path_to_jar" };
    // The initial environment to pass to the PTY child process...
    String[] env = { "TERM=xterm" };

    PtyProcess pty = PtyProcess.exec(cmd, env);

    OutputStream os = pty.getOutputStream();
    InputStream is = pty.getInputStream();

    // ... work with the streams ...

    // wait until the PTY child process terminates...
    int result = pty.waitFor();

    // free up resources.
    pty.close();

Zt-exec

Maybe it's worth trying zt-exec?

I have no idea how it executes commands.

But it may be it (I didn't test that).

Using https://github.com/zeroturnaround/zt-exec

    new ProcessExecutor().command("java", "-jar path_to_jar")
        .redirectOutput(new LogOutputStream() {
            @Override
            protected void processLine(String line) {
                ...
            }
        })
        .execute();

That should work, but I didn't test that.
In general, there are no ways to nicely resolve your problem.

Depending on what platforms you want to target consider using unbuffered, stdbuff or the (slowest) terminal emulation...

Please let me know if that helps and good luck! :)


来源: stackexchange

问:
sqlite3: how to select row's presented only in first table (with other table join)
I have such structure:

mainTable

```<code>article | brand      | price
ocm10   | someBrand1 | 100
ocm20   | someBrand1 | 200
ocm30   | someBrand2 | 300
</code>```

secondTable

```<code>article | brand      | price
ocm30   | someBrand1 | 320
ocm10   | someBrand1 | 120
</code>```

thirdTable

```<code>article | brand      | price
ocm20   | someBrand1 | 230
ocm40   | someBrand1 | 430
ocm50   | someBrand3 | 530
</code>```

and right now i have such query:

```<code>SELECT article,
       mainTable.brand AS priceBrand,
       mainTable.price AS priceTableMain,
       secondTable.price AS priceTableSecond,
       thirdTable.price AS priceTableThird,
       min(ifnull(mainTable.price, 'inf'),
           ifnull(secondTable.price, 'inf'),
           ifnull(thirdTable.price, 'inf')) AS minPrice
FROM (SELECT article FROM mainTable
      UNION
      SELECT article FROM secondTable
      UNION
      SELECT article FROM thirdTable)
LEFT JOIN mainTable USING (article)
LEFT JOIN secondTable USING (article)
LEFT JOIN thirdTable USING (article);
</code>```

as result I want to see:

```<code>article | brand      | priceMainTable | priceSecond | priceThird | minPrice
ocm10   | someBrand1 | 100            |   null      | null       | 100
ocm20   | someBrand1 | 200            |   null      | 230        | 200
ocm30   | someBrand2 | 300            |   320       | null       | 300
</code>```

(so, without rows like ocm40, ocm50 which aren't presented in first table)

how is it possible to get only rows, presented in mainTable?

so in result i will have only rows with articles: ocm10, ocm20, ocm30 with joined data of prices?

here is fiddle: http://sqlfiddle.com/#!7/87df2/4/0

btw: I know, that the same structure is not a good idea... in real app tables are different, this is only a sample. And I can have more than 3 same tables: even 10 with joins etc...

答:
You should be able to just left join the first table to the other two:

```<code>SELECT
    t1.article,
    t1.brand,
    t1.price AS priceMainTable,
    t2.price AS priceSecond,
    t3.price AS priceThird,
    MIN(t1.price,
        COALESCE(t2.price, t1.price),
        COALESCE(t3.price, t1.price)) AS minPrice
FROM mainTable t1
LEFT JOIN secondTable t2
    ON t1.article = t2.article
LEFT JOIN thirdTable t3
    ON t1.article = t3.article;
</code>```

Note here that we use the scalar version of MIN which accepts multiple arguments.  The COALESCE logic is that the second and third price "defer" back to the first price should either be NULL.  So if, for example, both the second and third price were NULL, then the minimum price would be determined by the first price, which is the only reliable piece of information available.

ContentLicense: CC BY-SA 3.0

Body:
I have such structure:

mainTable

article | brand      | price
ocm10   | someBrand1 | 100
ocm20   | someBrand1 | 200
ocm30   | someBrand2 | 300

secondTable

article | brand      | price
ocm30   | someBrand1 | 320
ocm10   | someBrand1 | 120

thirdTable

article | brand      | price
ocm20   | someBrand1 | 230
ocm40   | someBrand1 | 430
ocm50   | someBrand3 | 530

and right now i have such query:

SELECT article,
       mainTable.brand AS priceBrand,
       mainTable.price AS priceTableMain,
       secondTable.price AS priceTableSecond,
       thirdTable.price AS priceTableThird,
       min(ifnull(mainTable.price, 'inf'),
           ifnull(secondTable.price, 'inf'),
           ifnull(thirdTable.price, 'inf')) AS minPrice
FROM (SELECT article FROM mainTable
      UNION
      SELECT article FROM secondTable
      UNION
      SELECT article FROM thirdTable)
LEFT JOIN mainTable USING (article)
LEFT JOIN secondTable USING (article)
LEFT JOIN thirdTable USING (article);

as result I want to see:

article | brand      | priceMainTable | priceSecond | priceThird | minPrice
ocm10   | someBrand1 | 100            |   null      | null       | 100
ocm20   | someBrand1 | 200            |   null      | 230        | 200
ocm30   | someBrand2 | 300            |   320       | null       | 300

(so, without rows like ocm40, ocm50 which aren't presented in first table)

how is it possible to get only rows, presented in mainTable?

so in result i will have only rows with articles: ocm10, ocm20, ocm30 with joined data of prices?

here is fiddle: http://sqlfiddle.com/#!7/87df2/4/0

btw: I know, that the same structure is not a good idea... in real app tables are different, this is only a sample. And I can have more than 3 same tables: even 10 with joins etc...

Body:
You should be able to just left join the first table to the other two:

SELECT
    t1.article,
    t1.brand,
    t1.price AS priceMainTable,
    t2.price AS priceSecond,
    t3.price AS priceThird,
    MIN(t1.price,
        COALESCE(t2.price, t1.price),
        COALESCE(t3.price, t1.price)) AS minPrice
FROM mainTable t1
LEFT JOIN secondTable t2
    ON t1.article = t2.article
LEFT JOIN thirdTable t3
    ON t1.article = t3.article;

Note here that we use the scalar version of MIN which accepts multiple arguments.  The COALESCE logic is that the second and third price "defer" back to the first price should either be NULL.  So if, for example, both the second and third price were NULL, then the minimum price would be determined by the first price, which is the only reliable piece of information available.


问:
Uncheck Selected checkbox on button click
I have already tried all the given methods to uncheck checkbox in jquery, please find my below code.

```<code>$('#btnDeleteEnterpriseID').click(function () {
       $('#chkbox').prop('checked', false);
       $('#chkbox').removeAttr('checked');
       $('#chkbox').checked = false;
       $('#chkbox').attr('checked', false);
       $('#chkbox input:checkbox').attr('checked', false);
       $('#chkbox input[type=checkbox]').removeAttr('checked');
    });
</code>```

Have tried with all methods that I could get till now.

Below is the code for my checkbox and button.

```<code>@helper DisplayMultiLine(string str)
{ foreach (string s in str.Split(new char[] { ',' }))
 { <input type="checkbox" id="chkbox" value="@s"class="edit-mode" />@s <br />}
}
</code>```

Here, @DisplayMultiline is helper class which I used in Web Grid column as shown below,

```<code>grid.Column(columnName: "EnterpriseID",
format:@<text><span class="display-mode">
<label id="EnterpriseId" ></label>
</span>@DisplayMultiLine(@item.EnterpriseId)</text>),
</code>```

And I want this checkbox to get unchecked on click event of delete button, code for it given below.

```<code><button type="button" id="btnDeleteEnterpriseID"
value="Delete" class="cancel-user edit-mode" onclick="DeleteEnterpriseID()">Delete</button>
</code>```

I am not getting my mistake, kindly assist.

Kindly note, I have not used all those possibilities together, I just wanted to tell that I have used almost all methods and have tried them one by one.

答:
You are generating duplicate identifiers in your foreach:

```<code>@helper DisplayMultiLine(string str)
{ foreach (string s in str.Split(new char[] { ',' }))
 { <input type="checkbox" id="chkbox" value="@s"class="edit-mode" />@s <br />}
}
</code>```

When you have multiple objects with the same id, jquery is having trouble to distinguish which one of them you aim at.

Jquery will either work only on the first one it will match or won't work at all. Find a way to distinguish between every check box.
for example:

```<code>@helper DisplayMultiLine(string str)
int i = 0;
{ foreach (string s in str.Split(new char[] { ',' }))
 { <input type="checkbox" id="chkbox" + i value="@s"class="edit-mode" />@s
</code>```

}

```<code>  i++;

}
</code>```

Body:
I have already tried all the given methods to uncheck checkbox in jquery, please find my below code.

$('#btnDeleteEnterpriseID').click(function () {
       $('#chkbox').prop('checked', false);
       $('#chkbox').removeAttr('checked');
       $('#chkbox').checked = false;
       $('#chkbox').attr('checked', false);
       $('#chkbox input:checkbox').attr('checked', false);
       $('#chkbox input[type=checkbox]').removeAttr('checked');
    });

Have tried with all methods that I could get till now.

Below is the code for my checkbox and button.

@helper DisplayMultiLine(string str)
{ foreach (string s in str.Split(new char[] { ',' }))
 { <input type="checkbox" id="chkbox" value="@s"class="edit-mode" />@s
}
}

Here, @DisplayMultiline is helper class which I used in Web Grid column as shown below,

grid.Column(columnName: "EnterpriseID",
format:@<text>

@DisplayMultiLine(@item.EnterpriseId)</text>),

And I want this checkbox to get unchecked on click event of delete button, code for it given below.

<button type="button" id="btnDeleteEnterpriseID"
value="Delete" class="cancel-user edit-mode" onclick="DeleteEnterpriseID()">Delete</button>

I am not getting my mistake, kindly assist.

Kindly note, I have not used all those possibilities together, I just wanted to tell that I have used almost all methods and have tried them one by one.

Body:
You are generating duplicate identifiers in your foreach:

@helper DisplayMultiLine(string str)
{ foreach (string s in str.Split(new char[] { ',' }))
 { <input type="checkbox" id="chkbox" value="@s"class="edit-mode" />@s <br />}
}

When you have multiple objects with the same id, jquery is having trouble to distinguish which one of them you aim at.

Jquery will either work only on the first one it will match or won't work at all. Find a way to distinguish between every check box.
for example:

@helper DisplayMultiLine(string str)
int i = 0;
{ foreach (string s in str.Split(new char[] { ',' }))
 { <input type="checkbox" id="chkbox" + i value="@s"class="edit-mode" />@s

}

  i++;

}


问:
Access command line argument in scripts of package.json
I have created a command in package.json file

```<code>"create": "ng g component process.env.page --it false"
</code>```

Now I want to access the passed page argument in the above command so that user can pass the component name to the npm command

I am running the above command as

```<code>npm run create --page login
</code>```

and this runs the

```<code>ng g component process.env.page --it false
</code>```

so new component is created with name process.

How can I access the passed page (login) in my script?

答:
You can use the primitive process.argv or yargs which is a lot more powerful

here is a yargs example

const argv = require("yargs").argv;

let page = argv.page //get the page

Body:
I have created a command in package.json file

"create": "ng g component process.env.page --it false"

Now I want to access the passed page argument in the above command so that user can pass the component name to the npm command

I am running the above command as

npm run create --page login

and this runs the

ng g component process.env.page --it false

so new component is created with name process.

How can I access the passed page (login) in my script?


问:
Authentication between Desfire EV1 and SAM AV2
I want to Authenticate between Desfire EV1 and SAM AV2 in AV2 mode,
I send the following command between card and SAM but I don't take 90 00 in last command.

(SAM is in AV2 mode of course when it is in AV1 mode I take same response.)
please guide me.

I think I should switch from DES to AES in Desfire but I don't know how do it.

-------------------Commands----------------------

```<code>Desfire Command> 90 1A 00 00 01 00 00
Desfire Response< BF BC 59 EF B2 90 26 51 91 AF
SAM Command> 80 0A 00 00 0A 01 01 BF BC 59 EF B2 90 26 51 00
SAM Response< 10 4C E1 DA F6 A2 E7 51 44 01 86 F3 0D D1 B9 EB 90 AF
Desfire Command> 90 AF 00 00 10 10 4C E1 DA F6 A2 E7 51 44 01 86 F3 0D D1 B9 EB 00
Desfire Response< DE E9 3D 38 8B D7 74 3C 91 00
SAM Command> 80 0A 00 00 08 DE E9 3D 38 8B D7 74 3C 00
SAM Response< 67 00
</code>```

答:
SAM Command> 80 0A 00 00 08 DE E9 3D 38 8B D7 74 3C 00

SAM Response< 67 00

In this step don't append LE which is 00, because in the previous response from SAM returned AF which means there is additional data to be sent to SAM so we should not append LE.

Body:
I want to Authenticate between Desfire EV1 and SAM AV2 in AV2 mode,
I send the following command between card and SAM but I don't take 90 00 in last command.

(SAM is in AV2 mode of course when it is in AV1 mode I take same response.)
please guide me.

I think I should switch from DES to AES in Desfire but I don't know how do it.

-------------------Commands----------------------

Desfire Command> 90 1A 00 00 01 00 00
Desfire Response< BF BC 59 EF B2 90 26 51 91 AF
SAM Command> 80 0A 00 00 0A 01 01 BF BC 59 EF B2 90 26 51 00
SAM Response< 10 4C E1 DA F6 A2 E7 51 44 01 86 F3 0D D1 B9 EB 90 AF
Desfire Command> 90 AF 00 00 10 10 4C E1 DA F6 A2 E7 51 44 01 86 F3 0D D1 B9 EB 00
Desfire Response< DE E9 3D 38 8B D7 74 3C 91 00
SAM Command> 80 0A 00 00 08 DE E9 3D 38 8B D7 74 3C 00
SAM Response< 67 00


问:
How to read a too long repo diff
I'm trying to read the output of the repo diff command but it is too long to be shown on the terminal, so I can't read the whole thing. Is there any solution like exporting the output in a file so I can read all the lines?

答:
Output to file:

```<code>repo diff > /tmp/yourdiff.txt
</code>```

You can output it both to the terminal and a file, this way:

```<code>repo diff | tee /tmp/yourdiff.txt
</code>```

You could open that with any editor you like.

Title: How to read a too long repo diff

Body:
Output to file:

repo diff > /tmp/yourdiff.txt

You can output it both to the terminal and a file, this way:

repo diff | tee /tmp/yourdiff.txt

You could open that with any editor you like.


问:
If there is a Instruction after onDestroy , will the Instruction be executed?
Here after on Destroy I print a Log statement , will the Log get shown as the app already gets destroyed and no Instruction can be executed after app gets destroyed .

```<code>    @Override
protected void onDestroy() {
    super.onDestroy();
    Log.v(TestActivity,"App is currntly getting destroyed")
}
</code>```

So will "App is currently getting destroyed" be printed?
If it won't be printed then how can I execute code in onDestroy Method?

答:
Call the super.onDestory() after your code executed.

```<code>@Override
protected void onDestroy() {
    Log.v(MainActivity,"App is currntly getting destroyed")
    super.onDestroy();
}
</code>```

Also it won't be called if the app destroyed by the android for memory allocation.
Its better to use onStop() method to save your data.

Body:
Here after on Destroy I print a Log statement , will the Log get shown as the app already gets destroyed and no Instruction can be executed after app gets destroyed .

    @Override
protected void onDestroy() {
    super.onDestroy();
    Log.v(TestActivity,"App is currntly getting destroyed")
}

So will "App is currently getting destroyed" be printed?
If it won't be printed then how can I execute code in onDestroy Method?

Body:
Call the super.onDestory() after your code executed.

@Override
protected void onDestroy() {
    Log.v(MainActivity,"App is currntly getting destroyed")
    super.onDestroy();
}

Also it won't be called if the app destroyed by the android for memory allocation.
Its better to use onStop() method to save your data.


问:
How to stress test my page
I would like to test my web app under high load.

What I'd need to do is.
Load the page => click the button => fill the form => click the button.

I'd need to do this to simulate 5-10k page requests, which is expected to happen after we launch one service (based on previous years data as there's going to be some big pre-sale discount for only a couple of items)

What service or approach would be the most suitable to do this?

答:
There is a number of free and open source load testing tools you can consider listed at http://www.opensourcetesting.org/category/testing-tools-overview/performance/?menu-page=overview

Given your requirement of 5-10k concurrent requests my expectation is that you need the tool which can be run in "clustered" mode as you might hit the resource limit of a single load generator so you can use several machines running the load testing tool so it can be done in distributed manner.

One more factor would be possibility to record and replay the scenario so you could just run your steps in browser and the load testing tool would capture the relevant requests so you will be able to replay them with increased number of users.

Check out Open Source Load Testing Tools: Which One Should You Use? for example evaluation and research. Once you stick to this or that tool you can ask questions regarding your scenario implementation using a specific StackOverflow tag.

Title: How to stress test my page


问:
How to use grep -e to match partial words?
If you use grep like

```<code>grep -rnw '/your/path/to/search/' -e 'n getFoo'
</code>```

grep wouldn't find a file that contains "function getFoo()".

If you only search for 'getFoo' or else 'function getFoo', grep will find the file that contains the function.

So what's the best way to find a file containing part(s) of a string?

Thanks in advance!

答:
The -w flag causes whole word matches so it clearly what you don't need.

So what's the best way to find a file containing part(s) of a string?

```<code>shopt -s globstar
grep -li 'string to search for' /path/to/search/**
shopt -u globstar
</code>```

Body:
If you use grep like

grep -rnw '/your/path/to/search/' -e 'n getFoo'

grep wouldn't find a file that contains "function getFoo()".

If you only search for 'getFoo' or else 'function getFoo', grep will find the file that contains the function.

So what's the best way to find a file containing part(s) of a string?

Thanks in advance!

Body:
The -w flag causes whole word matches so it clearly what you don't need.

So what's the best way to find a file containing part(s) of a string?

shopt -s globstar
grep -li 'string to search for' /path/to/search/**
shopt -u globstar


问:
Java Beginner: How do I link one linked list to another?
If I have: linkedlist1= 1,2,3,4; and   linkedlist2= 5,6,7;

Am I able to attach linkedlist2 to the end of linkedlist1 in such a way if I invoke: linkedlist2.set(0,9999)  it changes to linkedlist2 = [999,6,7] and  linkedlist1 becomes [1,2,3,4,9999,7,8]; ?

Is that possible ? Or I do need another structure ?

The following code didn't work:

```<code> List<Double> l1 = new LinkedList<Double>(Arrays.asList(1.0,2.0));
 List<Double> l2 = new LinkedList<Double>(Arrays.asList(3.0,4.0));
 l1.addAll(l2);
 System.out.println(l1);
 l2.set(0, 9.0);
 System.out.println(l1);
</code>```

OUTPUT:

```<code> [1.0, 2.0, 3.0, 4.0]
 [1.0, 2.0, 3.0, 4.0]
</code>```

答:
To answer the question about updating one list and seeing the updates reflected in the other, the answer is it depends.

If you update an object in the first list you will see a change. but if you replace the object you will not see the change. Calling .set() on the first list is replacing the object in the list. Unfortunately, it is not possible to update the value of a primitive (or its class representation, in this case Float) without replacing it.

To append two lists, assuming you are using java.util.LinkedList, you can call addAll

ContentLicense: CC BY-SA 2.5

Body:
If I have: linkedlist1= 1,2,3,4; and   linkedlist2= 5,6,7;

Am I able to attach linkedlist2 to the end of linkedlist1 in such a way if I invoke: linkedlist2.set(0,9999)  it changes to linkedlist2 = [999,6,7] and  linkedlist1 becomes [1,2,3,4,9999,7,8]; ?

Is that possible ? Or I do need another structure ?

The following code didn't work:

 List<Double> l1 = new LinkedList<Double>(Arrays.asList(1.0,2.0));
 List<Double> l2 = new LinkedList<Double>(Arrays.asList(3.0,4.0));
 l1.addAll(l2);
 System.out.println(l1);
 l2.set(0, 9.0);
 System.out.println(l1);

OUTPUT:

 [1.0, 2.0, 3.0, 4.0]
 [1.0, 2.0, 3.0, 4.0]


问:
How can I LEFT JOIN a table and COUNT the rows?
I want to list my projects and the amount of posts each project has:

```<code>     `projects`                `posts`
------------------     ------------------
| `id`  | `name` |     | `id`  | `name`  |
------------------     ------------------
|   1   | Cat    |     |   1   |    Cat  |
|   2   | Dog    |     |   2   |    Cat  |
|   3   | Bird   |     |   3   |    Dog  |
|   4   | Frog   |     ------------------
------------------

$projects = $db->query('SELECT *,
    COUNT(posts.*) AS posts
    FROM projects
    LEFT JOIN posts ON projects.name=posts.name
  ')->fetchAll(PDO::FETCH_ASSOC);

    foreach($projects as $row) {
       echo "Project ".$id." has ".$posts ".posts.".<br>";
    }
</code>```

So as a result I expect:

```<code>Project 1 has 2 posts.
Project 2 has 1 posts.
Project 3 has 0 posts.
Project 4 has 0 posts.
</code>```

But I get an error message:

Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or
  access violation: 1064 You have an error in your SQL syntax; check the
  manual that corresponds to your MySQL server version for the right
  syntax to use near '*) AS posts,

So I changed posts.* into posts.id

But then my result is:

```<code>Project 1 has 3 posts.
</code>```

I am actually now confused how to achieve the result I need.

答:
The error was raised because of count(po.*) you must count for one column only inside of a count() function.

So, we want to find out how many times will find the 'name' column in posts table for a corresponding id column in projects table so we should count posts.name from posts joined with projects.

We need left join because we want also find out if it does not have corespondent (count(po.name) =0))

The query below will do the job:

```<code>SELECT p.*,COUNT(po.name) AS posts
    FROM projects p
    left join posts po on p.name = po.name
    group by p.id
</code>```

You can check here: http://sqlfiddle.com/#!9/3e9d4b/4

Body:
I want to list my projects and the amount of posts each project has:

     `projects`                `posts`
------------------     ------------------
| `id`  | `name` |     | `id`  | `name`  |
------------------     ------------------
|   1   | Cat    |     |   1   |    Cat  |
|   2   | Dog    |     |   2   |    Cat  |
|   3   | Bird   |     |   3   |    Dog  |
|   4   | Frog   |     ------------------
------------------

$projects = $db->query('SELECT *,
    COUNT(posts.*) AS posts
    FROM projects
    LEFT JOIN posts ON projects.name=posts.name
  ')->fetchAll(PDO::FETCH_ASSOC);

    foreach($projects as $row) {
       echo "Project ".$id." has ".$posts ".posts.".
";
    }

So as a result I expect:

Project 1 has 2 posts.
Project 2 has 1 posts.
Project 3 has 0 posts.
Project 4 has 0 posts.

But I get an error message:

Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or
  access violation: 1064 You have an error in your SQL syntax; check the
  manual that corresponds to your MySQL server version for the right
  syntax to use near '*) AS posts,

So I changed posts.* into posts.id

But then my result is:

Project 1 has 3 posts.

I am actually now confused how to achieve the result I need.

Body:
The error was raised because of count(po.*) you must count for one column only inside of a count() function.

So, we want to find out how many times will find the 'name' column in posts table for a corresponding id column in projects table so we should count posts.name from posts joined with projects.

We need left join because we want also find out if it does not have corespondent (count(po.name) =0))

The query below will do the job:

SELECT p.*,COUNT(po.name) AS posts
    FROM projects p
    left join posts po on p.name = po.name
    group by p.id

You can check here: http://sqlfiddle.com/#!9/3e9d4b/4


问:
redmine sub-url on apache2 debian
I had instaled Redmine under Debian8 and Apache/2.4.10 (Debian), it works great. The default instalation causes, it is only app served by Apache...
After mamy googling links and hints, I try change it with Apache configuration in way described here:

basic Redmine file (/etc/apache2/sites-available/redmine.conf) is:

```<code># The passenger module (from the libapache2-mod-passenger package) must be
# enabled
<VirtualHost *:80>
    # ServerName my.domain.name
    # this is the passenger config eee
    RailsEnv production
    SetEnv X_DEBIAN_SITEID "default"
    # CHANGE PassengerAppGroupName FOR OTHER INSTANCES
    PassengerAppGroupName redmine_default
    PassengerDefaultUser www-data
    Alias "/plugin_assets/" /var/cache/redmine/default/plugin_assets/
    DocumentRoot /usr/share/redmine/public
    <Directory "/usr/share/redmine/public">
        Allow from all
        Options -MultiViews
        Require all granted
    </Directory>
</VirtualHost>
</code>```

so, I try to move this settings a little bit upper - from sites-available to conf-available (similar like phpMyAdmin), and created /etc/apache2/conf-available/redmine.conf :

```<code>Alias /redmine /usr/share/redmine/public/

PassengerDefaultUser www-data
DocumentRoot /usr/share/redmine/public

<Location /redmine>
    RailsEnv production
    SetEnv X_DEBIAN_SITEID "default"
    # CHANGE PassengerAppGroupName FOR OTHER INSTANCES
    PassengerAppGroupName redmine_default

</Location>
Alias "/redmine/plugin_assets/" /var/cache/redmine/default/plugin_assets/

<Directory "/usr/share/redmine/public/">
        Allow from all
        Options -MultiViews
        Require all granted
</Directory>
</code>```

and I added:

```<code>RedmineApp::Application.routes.default_scope = "/redmine"
</code>```

to file: /usr/share/redmine/config/environment.rb
(according to hint in: http://www.redmine.org/projects/redmine/wiki/HowTo_Install_Redmine_in_a_sub-URI )

...and :-(
now Redmine works with 'localhost/redmine'
but eg. phpMyAdmin doesnt work and behave like bad redmine-link

When I remove DocumentRoot /usr/share/redmine/public line from redmine.conf - all works except redmine... link localhost/redmine show:

Forbidden
You don't have permission to access /redmine/ on this server.

and Apache error.log :

```<code>[Sun Nov 12 14:14:52.162868 2017] [autoindex:error] [pid 12220] [client ::1:45382] AH01276: Cannot serve directory /usr/share/redmine/public/: No matching DirectoryIndex (index.html,index.cgi,index.pl,index.php,index.xhtml ...
</code>```

My question is: is there a way to use DocumentRoot depending on match Alias? Or maybe is another way to fix it...

EDIT:

when redmine.conf is changed to:

```<code>[...]
#DocumentRoot /usr/share/redmine/public
[...]
<Directory "/usr/share/redmine/public/">

        PassengerEnabled on
        SetHandler none
        PassengerAppRoot /usr/share/redmine
        RailsBaseURI /redmine/redmine

        Allow from all
        Options -MultiViews
        Require all granted
</Directory>
</code>```

And, at the end of file environment.rb , I have added:

```<code>Redmine::Utils::relative_url_root = "/redmine"
</code>```

Now it works (Redmine and phpMyAdmin and other php) perfect!

:-)

答:
Since you are already using Passenger, the proper value to pass if your app is in sub-folder is:

```<code>PassengerBaseURI /redmine
</code>```

From their website, just replace subapp with redmine...

```<code><VirtualHost *:80>
    ServerName www.phusion.nl
    DocumentRoot /websites/phusion/public
    <Directory /websites/phusion>
        Allow from all
        Options -MultiViews
        # Uncomment this if you're on Apache >= 2.4:
        #Require all granted
    </Directory>

    # These have been added:
    Alias /subapp /websites/secondapp/public
    <Location /subapp>
        PassengerBaseURI /subapp
        PassengerAppRoot /websites/secondapp

    </Location>
    <Directory /websites/secondapp/public>
        Allow from all
        Options -MultiViews
        # Uncomment this if you're on Apache >= 2.4:
        #Require all granted
    </Directory>
</VirtualHost>
</code>```

Complete integration guide is:

https://www.phusionpassenger.com/library/deploy/apache/deploy/ruby/

Title: redmine sub-url on apache2 debian

Body:
I had instaled Redmine under Debian8 and Apache/2.4.10 (Debian), it works great. The default instalation causes, it is only app served by Apache...
After mamy googling links and hints, I try change it with Apache configuration in way described here:

basic Redmine file (/etc/apache2/sites-available/redmine.conf) is:

# The passenger module (from the libapache2-mod-passenger package) must be
# enabled
<VirtualHost *:80>
    # ServerName my.domain.name
    # this is the passenger config eee
    RailsEnv production
    SetEnv X_DEBIAN_SITEID "default"
    # CHANGE PassengerAppGroupName FOR OTHER INSTANCES
    PassengerAppGroupName redmine_default
    PassengerDefaultUser www-data
    Alias "/plugin_assets/" /var/cache/redmine/default/plugin_assets/
    DocumentRoot /usr/share/redmine/public
    <Directory "/usr/share/redmine/public">
        Allow from all
        Options -MultiViews
        Require all granted
    </Directory>
</VirtualHost>

so, I try to move this settings a little bit upper - from sites-available to conf-available (similar like phpMyAdmin), and created /etc/apache2/conf-available/redmine.conf :

Alias /redmine /usr/share/redmine/public/

PassengerDefaultUser www-data
DocumentRoot /usr/share/redmine/public

<Location /redmine>
    RailsEnv production
    SetEnv X_DEBIAN_SITEID "default"
    # CHANGE PassengerAppGroupName FOR OTHER INSTANCES
    PassengerAppGroupName redmine_default

</Location>
Alias "/redmine/plugin_assets/" /var/cache/redmine/default/plugin_assets/

<Directory "/usr/share/redmine/public/">
        Allow from all
        Options -MultiViews
        Require all granted
</Directory>

and I added:

RedmineApp::Application.routes.default_scope = "/redmine"

to file: /usr/share/redmine/config/environment.rb
(according to hint in: http://www.redmine.org/projects/redmine/wiki/HowTo_Install_Redmine_in_a_sub-URI )

...and :-(
now Redmine works with 'localhost/redmine'
but eg. phpMyAdmin doesnt work and behave like bad redmine-link

When I remove DocumentRoot /usr/share/redmine/public line from redmine.conf - all works except redmine... link localhost/redmine show:

Forbidden
You don't have permission to access /redmine/ on this server.

and Apache error.log :

[Sun Nov 12 14:14:52.162868 2017] [autoindex:error] [pid 12220] [client ::1:45382] AH01276: Cannot serve directory /usr/share/redmine/public/: No matching DirectoryIndex (index.html,index.cgi,index.pl,index.php,index.xhtml ...

My question is: is there a way to use DocumentRoot depending on match Alias? Or maybe is another way to fix it...

EDIT:

when redmine.conf is changed to:

[...]
#DocumentRoot /usr/share/redmine/public
[...]
<Directory "/usr/share/redmine/public/">

        PassengerEnabled on
        SetHandler none
        PassengerAppRoot /usr/share/redmine
        RailsBaseURI /redmine/redmine

        Allow from all
        Options -MultiViews
        Require all granted
</Directory>

And, at the end of file environment.rb , I have added:

Redmine::Utils::relative_url_root = "/redmine"

Now it works (Redmine and phpMyAdmin and other php) perfect!

:-)

Body:
Since you are already using Passenger, the proper value to pass if your app is in sub-folder is:

PassengerBaseURI /redmine

From their website, just replace subapp with redmine...

<VirtualHost *:80>
    ServerName www.phusion.nl
    DocumentRoot /websites/phusion/public
    <Directory /websites/phusion>
        Allow from all
        Options -MultiViews
        # Uncomment this if you're on Apache >= 2.4:
        #Require all granted
    </Directory>

    # These have been added:
    Alias /subapp /websites/secondapp/public
    <Location /subapp>
        PassengerBaseURI /subapp
        PassengerAppRoot /websites/secondapp

    </Location>
    <Directory /websites/secondapp/public>
        Allow from all
        Options -MultiViews
        # Uncomment this if you're on Apache >= 2.4:
        #Require all granted
    </Directory>
</VirtualHost>

Complete integration guide is:

https://www.phusionpassenger.com/library/deploy/apache/deploy/ruby/


答: It is not guarantee that onDestroy() will always call. You can do your cleaning stuff in onStop() method.</p>

Title: If there is a Instruction after onDestroy , will the Instruction be executed?


问:
Printing parsed JSON in Python
Assuming this is the .JSON file I have to parse:

```<code>{
"item": {
    "allInventory": {
        "onHand": 64,
        "total": {
            "1000": 0,
            "1001": 6,
            "1002": 5,
            "1003": 3,
            "1004": 12,
            "1005": 0
        }
    }
},
"image": {
    "tag": "/828402de-6cc8-493e-8abd-935a48a3d766_1.285a6f66ecf3ee434100921a3911ce6c.jpeg?odnHeight=450&odnWidth=450&odnBg=FFFFFF"
 }
}
</code>```

How would I go about printing the total values like:

```<code>1000 - 0
1001 - 6
1002 - 5
1003 - 4
1004 - 12
1005 - 0
</code>```

I have already parsed the values, but I'm unsure of how to actually print them. I've already spent awhile on this and couldn't find a solution so any help is appreciated. Here is my code thus far:

```<code>import requests
import json

src = requests.get('https://hastebin.com/raw/nenowimite').json()

stats = src['item']['allInventory']['total']
print(stats)
</code>```

答:
This can be done through a for loop as follows:</p>

```<code>for key in stats.keys():
    print(key, '-', stats[key])
</code>```

Title: Printing parsed JSON in Python

Body:
Assuming this is the .JSON file I have to parse:

{
"item": {
    "allInventory": {
        "onHand": 64,
        "total": {
            "1000": 0,
            "1001": 6,
            "1002": 5,
            "1003": 3,
            "1004": 12,
            "1005": 0
        }
    }
},
"image": {
    "tag": "/828402de-6cc8-493e-8abd-935a48a3d766_1.285a6f66ecf3ee434100921a3911ce6c.jpeg?odnHeight=450&odnWidth=450&odnBg=FFFFFF"
 }
}

How would I go about printing the total values like:

1000 - 0
1001 - 6
1002 - 5
1003 - 4
1004 - 12
1005 - 0

I have already parsed the values, but I'm unsure of how to actually print them. I've already spent awhile on this and couldn't find a solution so any help is appreciated. Here is my code thus far:

import requests
import json

src = requests.get('https://hastebin.com/raw/nenowimite').json()

stats = src['item']['allInventory']['total']
print(stats)

Body:
This can be done through a for loop as follows:

for key in stats.keys():
    print(key, '-', stats[key])


问:
Formula to make a score based on how evenly 5 groups are distributed
I have 5 buckets of age ranges: Age Less than 25 years, Age 25-34 years, Age 35-44 years, Age 45-54 years, Age 55 years and more

I want a formula to create a score based on how evenly 5 groups are distributed. For example if there are the same number of people in each of the 5 buckets I want the score to be 100 and if only 1 of the 5 buckets has people in it (worst distribution) I want the score to be zero.

答:
If you are placing the values for the five buckets into the cells A1 through E1 then the following array formula should give you a pretty good estimate:

```<code>=STDEV.S((A1:E1)/AVERAGE(A1:E1))/2.25
</code>```

Note that this is an array formula and needs to be entered as such using Ctrl+Shift+Enter (instead of just Enter). You will see that Excel recognizes the formula as an array formula by automatically adding curved brackets around your formula (no need to add them yourself):

```<code>{=STDEV.S((A1:E1)/AVERAGE(A1:E1))/2.25}
</code>```

Explanation:
Basically, standard deviation is by definition what you are looking for: "a measure to quantify the amount of variation".

Yet, the resulting value of a standard deviation would be dependable on the underlying values and would not give you an even-spread from 0% to 100%. Hence, I implemented a comparative measure which is the same for all values using the AVERAGE(). Yet, you could also use a SUM() instead. Afterwards you set one of the “buckets” to any number and the rest of the buckets to zero and in turn you’ll get the divisor you need to ensure that the result will be always between 0 and 100.

So, the result for {=STDEV.S((A1:E1)/AVERAGE(A1:E1))} will be 2.23607... which I rounded to 2.25. With {=STDEV.S((A1:E1)/SUM(A1:E1))} you'll get something like 0.44721... which could be rounded to 0.45.

I am sure that a more savvy user here might be able to explain you how to calculate this last bit of information too instead of merely estimating it as I do. But unfortunately, I am unable to do so. But if you are really curious then you might want to re-post this question on Data Science and I am sure you'll find someone to explain this to you in mathematical terms.

Body:
If you are placing the values for the five buckets into the cells A1 through E1 then the following array formula should give you a pretty good estimate:

=STDEV.S((A1:E1)/AVERAGE(A1:E1))/2.25

Note that this is an array formula and needs to be entered as such using Ctrl+Shift+Enter (instead of just Enter). You will see that Excel recognizes the formula as an array formula by automatically adding curved brackets around your formula (no need to add them yourself):

{=STDEV.S((A1:E1)/AVERAGE(A1:E1))/2.25}

Explanation:
Basically, standard deviation is by definition what you are looking for: "a measure to quantify the amount of variation".

Yet, the resulting value of a standard deviation would be dependable on the underlying values and would not give you an even-spread from 0% to 100%. Hence, I implemented a comparative measure which is the same for all values using the AVERAGE(). Yet, you could also use a SUM() instead. Afterwards you set one of the “buckets” to any number and the rest of the buckets to zero and in turn you’ll get the divisor you need to ensure that the result will be always between 0 and 100.

So, the result for {=STDEV.S((A1:E1)/AVERAGE(A1:E1))} will be 2.23607... which I rounded to 2.25. With {=STDEV.S((A1:E1)/SUM(A1:E1))} you'll get something like 0.44721... which could be rounded to 0.45.

I am sure that a more savvy user here might be able to explain you how to calculate this last bit of information too instead of merely estimating it as I do. But unfortunately, I am unable to do so. But if you are really curious then you might want to re-post this question on Data Science and I am sure you'll find someone to explain this to you in mathematical terms.


问:
Fill comboBox with SELECT results
I want to populate a combo box with the results of a SELECT query.

It shows rows in the combobox but all are : System.Data.DataRow

The results of the SELECT is stored in a datatable.

```<code>string ChaineDeSelction = "SELECT fir_mdnt FROM -- WHERE fir_aktiv = 1 AND EXISTS(select firbpv_fir from --)";
        OdbcConnection MyConnec = new OdbcConnection(MyConnString);
        MyConnec.Open();
        OdbcCommand MyComm = new OdbcCommand(ChaineDeSelction, MyConnec);
        DataTable.Load(MyComm.ExecuteReader());

        _cb_Societe.DataSource = DataTable; <--- I tried this way the the foreach .Add way but both return the same.

        foreach(DataRow Ligne in DataTable.Rows)
        {
            _cb_Societe.Items.Add(Ligne);
        }
</code>```

I also have a DataGridView filled with the same

Any suggestions ?

答:
And what about the following way:</p>

```<code> string ChaineDeSelction = "SELECT fir_mdnt FROM -- WHERE fir_aktiv = 1 AND EXISTS(select firbpv_fir from --)";
        OdbcConnection MyConnec = new OdbcConnection(MyConnString);
        MyConnec.Open();
        OdbcCommand MyComm = new OdbcCommand(ChaineDeSelction, MyConnec);
        OdbcDataReader reader = MyComm.ExecuteReader();
        while (reader.Read())
        {
            _cb_Societe.Items.Add(reader[0]);
        };
</code>```

Title: Fill comboBox with SELECT results

Body:
I want to populate a combo box with the results of a SELECT query.

It shows rows in the combobox but all are : System.Data.DataRow

The results of the SELECT is stored in a datatable.

string ChaineDeSelction = "SELECT fir_mdnt FROM -- WHERE fir_aktiv = 1 AND EXISTS(select firbpv_fir from --)";
        OdbcConnection MyConnec = new OdbcConnection(MyConnString);
        MyConnec.Open();
        OdbcCommand MyComm = new OdbcCommand(ChaineDeSelction, MyConnec);
        DataTable.Load(MyComm.ExecuteReader());

        _cb_Societe.DataSource = DataTable; <--- I tried this way the the foreach .Add way but both return the same.

        foreach(DataRow Ligne in DataTable.Rows)
        {
            _cb_Societe.Items.Add(Ligne);
        }

I also have a DataGridView filled with the same

Any suggestions ?

Body:
And what about the following way:

 string ChaineDeSelction = "SELECT fir_mdnt FROM -- WHERE fir_aktiv = 1 AND EXISTS(select firbpv_fir from --)";
        OdbcConnection MyConnec = new OdbcConnection(MyConnString);
        MyConnec.Open();
        OdbcCommand MyComm = new OdbcCommand(ChaineDeSelction, MyConnec);
        OdbcDataReader reader = MyComm.ExecuteReader();
        while (reader.Read())
        {
            _cb_Societe.Items.Add(reader[0]);
        };


问:
  in String.Format(...) for currency
I use String.Format to do currency formatting. It works great, but I want a non-breaking space ( ) between the currency symbol (R) and the value so it doesn't wrap in small spaces, making it harder to read.

```<code><%=String.Format("{0:R #,###.00;(R #,###.00);R 0.00}", Model)%>
</code>```

where Model is a decimal.

How do I add   between R and #,###.00 without confusing the String.Format method?

答:
Would it be possible to wrap the result in an element with the css white-space property set?</p>

```<code><span style="white-space:nowrap;"><%=String.Format("{0:R #,###.00;(R #,###.00);R 0.00}", Model)%></span>
</code>```

Title: in String.Format(...) for currency

Body:
I use String.Format to do currency formatting. It works great, but I want a non-breaking space ( ) between the currency symbol (R) and the value so it doesn't wrap in small spaces, making it harder to read.

<%=String.Format("{0:R #,###.00;(R #,###.00);R 0.00}", Model)%>

where Model is a decimal.

How do I add   between R and #,###.00 without confusing the String.Format method?

Body:
Would it be possible to wrap the result in an element with the css white-space property set?

<span style="white-space:nowrap;"><%=String.Format("{0:R #,###.00;(R #,###.00);R 0.00}", Model)%></span>


问:
How to use one Action Listener for buttons that require different method parameters?
I want to reduce the amount of button action listeners I have by simply calling one Action Listener:

```<code>ActionListener calculatorListener = new ActionListener(){
             @Override
            public void actionPerformed(ActionEvent e) {
                int x = 9;
                calc.calculate(x);
            }
        };

JButton button9 = new JButton("9");
        buttonPanel.add(button9);

        button9.addActionListener(calculatorListener);

JButton button8 = new JButton("8");

buttonPanel.add(button8);

 button8.addActionListener(calculatorListener); //etc.....
</code>```

I have many different buttons, but need the parameter in the one ActionListener (x for example) to be different for each button that uses the ActionListener. Is there a way that the action listener can detect which JButton is being used?

答:
There are lots of ways of accomplishing your goal.  Here's one that's fairly simple and straightforward.

First, make your action listener a named class that you can construct with a parameter:

```<code>private class CalcListener implements ActionListener {
    private int x;
    private CalcListener(int x){
        this.x = x;
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        calc.calculate(x);
    }
}
</code>```

Then, use it like this:

```<code>button1.addActionListener(new CalcAction(1));
...
button8.addActionListener(new CalcAction(8));
button9.addActionListener(new CalcAction(9));
</code>```

Body:
I want to reduce the amount of button action listeners I have by simply calling one Action Listener:

ActionListener calculatorListener = new ActionListener(){
             @Override
            public void actionPerformed(ActionEvent e) {
                int x = 9;
                calc.calculate(x);
            }
        };

JButton button9 = new JButton("9");
        buttonPanel.add(button9);

        button9.addActionListener(calculatorListener);

JButton button8 = new JButton("8");

buttonPanel.add(button8);

 button8.addActionListener(calculatorListener); //etc.....

I have many different buttons, but need the parameter in the one ActionListener (x for example) to be different for each button that uses the ActionListener. Is there a way that the action listener can detect which JButton is being used?

Body:
There are lots of ways of accomplishing your goal.  Here's one that's fairly simple and straightforward.

First, make your action listener a named class that you can construct with a parameter:

private class CalcListener implements ActionListener {
    private int x;
    private CalcListener(int x){
        this.x = x;
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        calc.calculate(x);
    }
}

Then, use it like this:

button1.addActionListener(new CalcAction(1));
...
button8.addActionListener(new CalcAction(8));
button9.addActionListener(new CalcAction(9));


问:
DATENAME and DATEPART in SQL
I'm trying to get my EntryDate column in this format 'YYYY_m' for example '2013_04'.

This code has been unsuccessful

```<code>DATENAME (YYYY, EntryDate) + '_' + DATEPART (M, EntryDate)
</code>```

Attempts using DATEFORMAT have also been unsuccessful, stating there was syntax error at ','  after the M. What code would work instead?

Thank you.

答:
DATEPART
It is a Datetime function which extract information from date. This function always returns result as integer type.

```<code>SELECT DATEPART(month, '2009-01-01 00:00:00:000') as month
it is return "1" as an integer:
</code>```

DATENAME
It is also another Datetime function which to extract information from date. This function always returns result as varchar

```<code>SELECT DATENAME(month, '2009-01-01 00:00:00:000')  as month
it is return "January".
</code>```

Title: DATENAME and DATEPART in SQL

Body:
I'm trying to get my EntryDate column in this format 'YYYY_m' for example '2013_04'.

This code has been unsuccessful

DATENAME (YYYY, EntryDate) + '_' + DATEPART (M, EntryDate)

Attempts using DATEFORMAT have also been unsuccessful, stating there was syntax error at ','  after the M. What code would work instead?

Thank you.

Body:
DATEPART
It is a Datetime function which extract information from date. This function always returns result as integer type.

SELECT DATEPART(month, '2009-01-01 00:00:00:000') as month
it is return "1" as an integer:

DATENAME
It is also another Datetime function which to extract information from date. This function always returns result as varchar

SELECT DATENAME(month, '2009-01-01 00:00:00:000')  as month
it is return "January".


问:
Toggle switch to call url but not open it
I have a toggle switch on my html which i would like to enable/disable a relay in arduino with.

On: call http://192.168.1.144:8000/1234!Q02=0$
Off: call http://192.168.1.144:8000/1234!Q02=1$

I don't want the url to be opened, i just want it to be called.

```<code>function getValue1() {
   var isChecked = document.getElementById("button1").checked;

   if(isChecked){
     alert("button1 is checked");
   } else {
     alert("button1 is NOT checked");
   }
}
</code>```

My javascript code is working, but i dont know how to call the url.

Thanks.

答:
you can also try this.</p>

```<code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<script>
  $(document).ready(function() {
    $("#btnCall").click(function(){

        if($("button1").prop('checked')){
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "http://192.168.1.144:8000/1234!Q02=0$",
                data: JSON.stringify(data), //yourData
                success: function (data) {
                    console.log(data);
                },
                dataType: "json"
           });
        } else {
            $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "http://192.168.1.144:8000/1234!Q02=1$",
            data: JSON.stringify(data), //yourData
            success: function (data) {
                console.log(data);
            },
            dataType: "json"
        });
        }
    });
});
</script>
</code>```

Body:
I have a toggle switch on my html which i would like to enable/disable a relay in arduino with.

On: call http://192.168.1.144:8000/1234!Q02=0$
Off: call http://192.168.1.144:8000/1234!Q02=1$

I don't want the url to be opened, i just want it to be called.

function getValue1() {
   var isChecked = document.getElementById("button1").checked;

   if(isChecked){
     alert("button1 is checked");
   } else {
     alert("button1 is NOT checked");
   }
}

My javascript code is working, but i dont know how to call the url.

Thanks.

Body:
you can also try this.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<script>
  $(document).ready(function() {
    $("#btnCall").click(function(){

        if($("button1").prop('checked')){
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "http://192.168.1.144:8000/1234!Q02=0$",
                data: JSON.stringify(data), //yourData
                success: function (data) {
                    console.log(data);
                },
                dataType: "json"
           });
        } else {
            $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "http://192.168.1.144:8000/1234!Q02=1$",
            data: JSON.stringify(data), //yourData
            success: function (data) {
                console.log(data);
            },
            dataType: "json"
        });
        }
    });
});
</script>


问:
ARKit - place object without touching the screen
Using ARKit I can tap on the surface to place 3D object here. I also can move my finger and thus move the object along the surface.

How can I make an object to automatically appear and stick to the surface in front of the camera, with no need in touching the screen?

Here is the example script for placing 3D objects by finger tap:

```<code>using System;
using System.Collections.Generic;

namespace UnityEngine.XR.iOS
{
    public class UnityARHitTestExample : MonoBehaviour
    {
        public Transform m_HitTransform;

        bool HitTestWithResultType (ARPoint point, ARHitTestResultType resultTypes)
        {
            List<ARHitTestResult> hitResults = UnityARSessionNativeInterface.GetARSessionNativeInterface ().HitTest (point, resultTypes);
            if (hitResults.Count > 0) {
                foreach (var hitResult in hitResults) {
                    Debug.Log ("Got hit!");
                    m_HitTransform.position = UnityARMatrixOps.GetPosition (hitResult.worldTransform);
                    m_HitTransform.rotation = UnityARMatrixOps.GetRotation (hitResult.worldTransform);
                    Debug.Log (string.Format ("x:{0:0.######} y:{1:0.######} z:{2:0.######}", m_HitTransform.position.x, m_HitTransform.position.y, m_HitTransform.position.z));
                    return true;
                }
            }
            return false;
        }

        // Update is called once per frame
        void Update () {
            if (Input.touchCount > 0 && m_HitTransform != null)
            {
                var touch = Input.GetTouch(0);
                if (touch.phase == TouchPhase.Began || touch.phase == TouchPhase.Moved)
                {
                    var screenPosition = Camera.main.ScreenToViewportPoint(touch.position);
                    ARPoint point = new ARPoint {
                        x = screenPosition.x,
                        y = screenPosition.y
                    };

                    // prioritize reults types
                    ARHitTestResultType[] resultTypes = {
                        ARHitTestResultType.ARHitTestResultTypeExistingPlaneUsingExtent,
                        // if you want to use infinite planes use this:
                        //ARHitTestResultType.ARHitTestResultTypeExistingPlane,
                        ARHitTestResultType.ARHitTestResultTypeHorizontalPlane,
                        ARHitTestResultType.ARHitTestResultTypeFeaturePoint
                    };

                    foreach (ARHitTestResultType resultType in resultTypes)
                    {
                        if (HitTestWithResultType (point, resultType))
                        {
                            return;
                        }
                    }
                }
            }
        }

    }
}
</code>```

答:
I've done something similar in Objective-C, so hopefully I can help with your unity example. </p>

<p>My logic was basically that placing the objects using a tap is based on the hitTest function with a point provided to it retrieved from the touch location. So I just created a CGPoint programmatically in the center of the screen and ran the hitTest function with this point. Had it hooked to a timer, and when a hit returned objects were added there. </p>

```<code>CGPoint point = CGPointMake(self.sceneView.frame.size.width / 2, self.sceneView.frame.size.height / 2); //Get a point at the middle of the screen
NSArray <ARHitTestResult *> *hitResults = [_sceneView hitTest:point types:ARHitTestResultTypeFeaturePoint]; //Try to do a AR Hit Test on this point
if ([hitResults count] != 0) { //If have any results
    //Perform desired operation
}
</code>```

Body:
Using ARKit I can tap on the surface to place 3D object here. I also can move my finger and thus move the object along the surface.

How can I make an object to automatically appear and stick to the surface in front of the camera, with no need in touching the screen?

Here is the example script for placing 3D objects by finger tap:

using System;
using System.Collections.Generic;

namespace UnityEngine.XR.iOS
{
    public class UnityARHitTestExample : MonoBehaviour
    {
        public Transform m_HitTransform;

        bool HitTestWithResultType (ARPoint point, ARHitTestResultType resultTypes)
        {
            List<ARHitTestResult> hitResults = UnityARSessionNativeInterface.GetARSessionNativeInterface ().HitTest (point, resultTypes);
            if (hitResults.Count > 0) {
                foreach (var hitResult in hitResults) {
                    Debug.Log ("Got hit!");
                    m_HitTransform.position = UnityARMatrixOps.GetPosition (hitResult.worldTransform);
                    m_HitTransform.rotation = UnityARMatrixOps.GetRotation (hitResult.worldTransform);
                    Debug.Log (string.Format ("x:{0:0.######} y:{1:0.######} z:{2:0.######}", m_HitTransform.position.x, m_HitTransform.position.y, m_HitTransform.position.z));
                    return true;
                }
            }
            return false;
        }

        // Update is called once per frame
        void Update () {
            if (Input.touchCount > 0 && m_HitTransform != null)
            {
                var touch = Input.GetTouch(0);
                if (touch.phase == TouchPhase.Began || touch.phase == TouchPhase.Moved)
                {
                    var screenPosition = Camera.main.ScreenToViewportPoint(touch.position);
                    ARPoint point = new ARPoint {
                        x = screenPosition.x,
                        y = screenPosition.y
                    };

                    // prioritize reults types
                    ARHitTestResultType[] resultTypes = {
                        ARHitTestResultType.ARHitTestResultTypeExistingPlaneUsingExtent,
                        // if you want to use infinite planes use this:
                        //ARHitTestResultType.ARHitTestResultTypeExistingPlane,
                        ARHitTestResultType.ARHitTestResultTypeHorizontalPlane,
                        ARHitTestResultType.ARHitTestResultTypeFeaturePoint
                    };

                    foreach (ARHitTestResultType resultType in resultTypes)
                    {
                        if (HitTestWithResultType (point, resultType))
                        {
                            return;
                        }
                    }
                }
            }
        }

    }
}

Body:
I've done something similar in Objective-C, so hopefully I can help with your unity example.

My logic was basically that placing the objects using a tap is based on the hitTest function with a point provided to it retrieved from the touch location. So I just created a CGPoint programmatically in the center of the screen and ran the hitTest function with this point. Had it hooked to a timer, and when a hit returned objects were added there.

CGPoint point = CGPointMake(self.sceneView.frame.size.width / 2, self.sceneView.frame.size.height / 2); //Get a point at the middle of the screen
NSArray <ARHitTestResult *> *hitResults = [_sceneView hitTest:point types:ARHitTestResultTypeFeaturePoint]; //Try to do a AR Hit Test on this point
if ([hitResults count] != 0) { //If have any results
    //Perform desired operation
}


问:
How to make a glow effect under the cursor while also not affecting components underneath MouseListener (mouseEntered, mouseExit) methods?
Background: Currently in my project I have multiple components that each have a custom MouseListener. With these MouseListeners, majority of the code is in the mouseEntered/mouseExit method.

Right now I was trying to implement a glow effect under the cursor. To do this I have been using JPanels stacked on top of each other but for sample code I provide I will setting panes (ContentPane and GlassPane).

The problem shown in the example is the GlassPane (glowPanel) intercepts all MouseEvents and thus I don't know how to incorporate mouseEntered/mouseExit events because GlassPane/glowPanel covers the whole window: aka mouseEntered/mouseExit events never happen. I was thinking I could keep track of the component I am under at all times and when it changes I redispatch a mouseEntered/mouseExit but I wasn't sure if this was the best way to go about this. Another option was just spamming mouseEntered/mouseExit but I know that won't work.

In the example code I provide two ways I have tried to go about this.

MouseListener way: use mouse events to update glowPanel where the mouse is currently located and repaint. Doesn't work right, doesn't redispatch correctly mouseEntered, mouseExit because GlowPanel never triggers such events (

Thread: Have a thread run in a loop sleeping every so often. When it wakes get mouse location and then repaint the glowPanel with new location. This works but I think the MouseListener way would be better overall if I could get mouseEntered/mouseExit events to work correctly.

I know this code isn't the prettiest. I tried to do this as fast as possible to show an example. I hopefully will go through the code later and make it prettier.

```<code>public class GlowPanel extends JPanel{

//Attributes
private MouseAdapter repaintAdapter;
private MouseAdapter redispatchAdapter;
private static Color INNER_COLOR = new Color(30, 30, 30, 127);
private static Color OUTER_COLOR = new Color(90, 90, 90, 127);
private static int RADIUS = 25;
private static int DIAMETER = RADIUS * 2;
private Thread glowThread;
private static Point p = new Point(0,0);
private static GlowPanel glowPanel;
private static Boolean MOUSE_LISTEN_STATE = true;
private static Boolean GLOW_THREAD_STATE = false;
private Boolean CURRENT_STATE;
private static ButtonGroup buttonGroup;

//Start Constructor
public GlowPanel(){
    //Set Attributes
    this.setName("GLOW PANEL");
    this.setOpaque(false);
    this.setVisible(true);
    //this.event

    //Add MouseMouseListener
    this.repaintAdapter = new RepaintMouseAdapter(this);
    this.redispatchAdapter = new RedispatchAdapter();
}
//End Constructor

//Start Methods

/**
 * Set state to mouseListen
 */
public synchronized void setStateMouseListen(){
    if(!MOUSE_LISTEN_STATE.equals(CURRENT_STATE)){
        if(this.glowThread != null){
            this.glowThread.interrupt();
        }
        this.addMouseMotionListener(this.repaintAdapter);
        this.addMouseListener(this.redispatchAdapter);
        this.addMouseMotionListener(this.redispatchAdapter);
        CURRENT_STATE = MOUSE_LISTEN_STATE;
    }
}

/**
 * Set state to off (don't do any effects)
 */
public synchronized void setStateOff(){
    if(this.glowThread != null){
        this.glowThread.interrupt();
    }
    this.removeMouseMotionListener(this.repaintAdapter);
    this.removeMouseListener(this.redispatchAdapter);
    this.removeMouseMotionListener(this.redispatchAdapter);
    CURRENT_STATE = null;
}

/**
 * Set state to GlowThread
 */
public synchronized void setStateGlowThread(){
    if(!GLOW_THREAD_STATE.equals(CURRENT_STATE)){
        this.removeMouseMotionListener(this.repaintAdapter);
        this.removeMouseListener(this.redispatchAdapter);
        this.removeMouseMotionListener(this.redispatchAdapter);
        this.glowThread = new Thread(new Runnable(){
            public void run(){
                while(!Thread.currentThread().isInterrupted()){
                    try {
                        Thread.sleep(1000);
                        GlowPanel.this.p = MouseInfo.getPointerInfo().getLocation();
                        SwingUtilities.convertPointFromScreen(p, GlowPanel.this);
                        GlowPanel.this.repaint();
                    }   catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                }
            }
        });
        this.glowThread.start();
        CURRENT_STATE = GLOW_THREAD_STATE;
    }
}

@Override
public void paintComponent(Graphics g){
    super.paintComponent(g);
    Point p = GlowPanel.this.p;
    Shape circle = new Ellipse2D.Double(p.getX() - RADIUS, p.getY() - RADIUS, DIAMETER, DIAMETER);
    Graphics2D g2 = (Graphics2D) g;

    g2.setColor(GlowPanel.INNER_COLOR);

    //g2.fill(circle);
    Shape circle2 = new Ellipse2D.Double(p.getX() - RADIUS + 9, p.getY() - RADIUS + 9, DIAMETER - 18, DIAMETER - 18);
    //Area a = new Area(circle);
    //a.subtract(new Area(circle2));
    g2.fill(circle);
    g2.setColor(GlowPanel.OUTER_COLOR);
    g2.fill(circle2);
}

/**
 * Create GUI used to show example
 */
public static void createGUI(){
    JFrame jFrame = new JFrame();

    //GlowPanel
    GlowPanel.glowPanel = new GlowPanel();

    //ContentPanel
    JPanel contentPanel = new JPanel();
    GridBagLayout gBL = new GridBagLayout();
    gBL.columnWidths = new int[]{100, 100, 100};
    gBL.rowHeights = new int[]{200, 50};
    contentPanel.setLayout(gBL);

    //Initial Constraints
    GridBagConstraints gBC = new GridBagConstraints();
    gBC.fill = GridBagConstraints.BOTH;
    gBC.gridx = 0;
    gBC.gridy = 0;
    gBC.weightx = 1;
    gBC.weighty = 1;
    gBC.gridwidth = 3;

    //Hover Panel
    JPanel hoverPanel = new JPanel();
    hoverPanel.setOpaque(true);
    hoverPanel.setBackground(Color.blue);
    hoverPanel.addMouseListener(new MouseAdapter(){

        @Override
        public void mouseClicked(MouseEvent e){}

        @Override
        public void mousePressed(MouseEvent e){}

        @Override
        public void mouseReleased(MouseEvent e){}

        @Override
        public void mouseEntered(MouseEvent e){
            hoverPanel.setBackground(Color.yellow);

        }

        @Override
        public void mouseExited(MouseEvent e){
            hoverPanel.setBackground(Color.blue);
        }

    });
    contentPanel.add(hoverPanel, gBC);

    //Create Buttons
    JToggleButton mouseListenButton = new JToggleButton("Mouse Listen");
    mouseListenButton.addActionListener(new AbstractAction(){
        @Override
        public void actionPerformed(ActionEvent e) {
            GlowPanel.glowPanel.setStateMouseListen();
        }
    });
    gBC.gridy++;
    gBC.weighty = 1;
    gBC.gridwidth = 1;
    contentPanel.add(mouseListenButton, gBC);

    JToggleButton glowThreadButton = new JToggleButton("GlowThread Button");
    glowThreadButton.addActionListener(new AbstractAction(){
        @Override
        public void actionPerformed(ActionEvent e) {
            GlowPanel.glowPanel.setStateGlowThread();
        }
    });
    gBC.gridx++;
    contentPanel.add(glowThreadButton, gBC);

    JToggleButton offButton = new JToggleButton("Off Button");
    offButton.addActionListener(new AbstractAction(){
        @Override
        public void actionPerformed(ActionEvent e) {
            GlowPanel.glowPanel.setStateOff();
        }
    });
    gBC.gridx++;
    contentPanel.add(offButton, gBC);

    GlowPanel.buttonGroup = new ButtonGroup();
    GlowPanel.buttonGroup.add(mouseListenButton);
    GlowPanel.buttonGroup.add(glowThreadButton);
    GlowPanel.buttonGroup.add(offButton);

    jFrame.setContentPane(contentPanel);
    jFrame.setGlassPane(GlowPanel.glowPanel);
    jFrame.getGlassPane().setVisible(true);
    jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    jFrame.pack();
    jFrame.setVisible(true);
}

public static void main(String[] args){
    SwingUtilities.invokeLater(new Runnable(){
        public void run(){
            GlowPanel.createGUI();
        }
    });
}

@Override
public boolean isOptimizedDrawingEnabled(){
    return false;
}
//End Methods

public static class RepaintMouseAdapter extends MouseAdapter{
    private JComponent jC;

    public RepaintMouseAdapter(JComponent jC){
        this.jC = jC;
    }

    @Override
    public void mouseMoved(MouseEvent e){
        GlowPanel.p = e.getPoint();
        this.jC.repaint();
    }
}

public static class RedispatchAdapter extends MouseAdapter{
    private JComponent lastComponentEntered;

    @Override
    public void mouseClicked(MouseEvent e){
        this.dispatchEvent(e);
    }

    @Override
    public void mousePressed(MouseEvent e){
        this.dispatchEvent(e);
    }

    @Override
    public void mouseReleased(MouseEvent e){
        this.dispatchEvent(e);
    }

    @Override
    public void mouseEntered(MouseEvent e){
        this.dispatchEvent(e);
        System.out.println("MOUSE ENTERED");
    }

    @Override
    public void mouseExited(MouseEvent e){
        this.dispatchEvent(e);
    }

    @Override
    public void mouseWheelMoved(MouseWheelEvent e){
        this.dispatchEvent(e);
    }

    @Override
    public void mouseDragged(MouseEvent e){
        this.dispatchEvent(e);
    }

    @Override
    public void mouseMoved(MouseEvent e){
        this.dispatchEvent(e);
    }

    private void dispatchEvent(MouseEvent e) {
        Component glass = (Component) e.getSource();
        Point glassPanePoint = e.getPoint();
        Container container = glass.getParent();
        Point containerPoint = SwingUtilities.convertPoint(glass,
                glassPanePoint, container);

        if (containerPoint.y < 0) { // we're not in the content pane
            // Could have special code to handle mouse events over
            // the menu bar or non-system window decorations, such as
            // the ones provided by the Java look and feel.
        } else {
            // The mouse event is probably over the content pane.
            // Find out exactly which component it's over.
            JComponent component = (JComponent) GlowPanel.getDeepestComponentAt(
                    container, containerPoint.x, containerPoint.y);
            //System.out.println(component);
            if (component != null) {
                // Forward events to component below
                Point componentPoint = SwingUtilities.convertPoint(
                        glass, glassPanePoint, component);
                if(e instanceof MouseWheelEvent){
                    MouseWheelEvent wE = (MouseWheelEvent) e;
                    component.dispatchEvent(new MouseWheelEvent(component, wE.getID(), wE.getWhen(),
                            wE.getModifiers(), componentPoint.x, componentPoint.y, wE.getClickCount(),
                            wE.isPopupTrigger(), wE.getScrollType(), wE.getScrollAmount(), wE.getWheelRotation()));
                }   else{
                    component.dispatchEvent(new MouseEvent(component, e
                            .getID(), e.getWhen(), e.getModifiers(),
                            componentPoint.x, componentPoint.y, e
                                    .getClickCount(), e.isPopupTrigger()));
                }

                if(this.lastComponentEntered != null && !this.lastComponentEntered.equals(component)){
                    System.out.println(!this.lastComponentEntered.equals(component));
                }
                if(this.lastComponentEntered != null && !this.lastComponentEntered.equals(component)){
                    e.getComponent().setCursor(component.getCursor());
                    component.dispatchEvent(new MouseEvent(component, MouseEvent.MOUSE_ENTERED, e.getWhen(),
                            e.getModifiers(), componentPoint.x, componentPoint.y,
                            e.getClickCount(), e.isPopupTrigger()));
                    Point lastComponentPoint = SwingUtilities.convertPoint(
                            glass, glassPanePoint, this.lastComponentEntered);
                    this.lastComponentEntered.dispatchEvent(new MouseEvent(this.lastComponentEntered,
                            MouseEvent.MOUSE_EXITED, e.getWhen(),
                            e.getModifiers(), lastComponentPoint.x, lastComponentPoint.y,
                            e.getClickCount(), e.isPopupTrigger()));
                }
                this.lastComponentEntered = component;
                System.out.println(this.lastComponentEntered);
            }

        }
        e.getComponent().repaint();
    }

}

public static Component getDeepestComponentAt(Component parent, int x, int y) {
    if (!parent.contains(x, y)) {
        return null;
    }
    if (parent instanceof Container) {
        Component components[] = ((Container)parent).getComponents();
        for (Component comp : components) {
            if (comp != null && comp.isVisible() && !(comp instanceof GlowPanel) && !(comp instanceof JLabel)) {
                Point loc = comp.getLocation();
                if (comp instanceof Container) {
                    comp = getDeepestComponentAt(comp, x - loc.x, y - loc.y);
                } else {
                    comp = comp.getComponentAt(x - loc.x, y - loc.y);
                }
                if (comp != null && comp.isVisible()) {
                    return comp;
                }
            }
        }
    }
    return parent;
}
</code>```

}

Hopefully that works. I basically copy pasted what I had in my project into my example class.

答:
I ended up going the route of making my own custom getDeepestComponentAt (makes sure the component is not GlassPane/also component contains a listener) and for my RedispatchAdapter I added a instance field of lastComponent. If the lastComponent wasn't the same as the one before then send a MOUSE_ENTERED to the new component and MOUSE_EXIT to the old component.

I'll edit my code to show the results.

Body:
Background: Currently in my project I have multiple components that each have a custom MouseListener. With these MouseListeners, majority of the code is in the mouseEntered/mouseExit method.

Right now I was trying to implement a glow effect under the cursor. To do this I have been using JPanels stacked on top of each other but for sample code I provide I will setting panes (ContentPane and GlassPane).

The problem shown in the example is the GlassPane (glowPanel) intercepts all MouseEvents and thus I don't know how to incorporate mouseEntered/mouseExit events because GlassPane/glowPanel covers the whole window: aka mouseEntered/mouseExit events never happen. I was thinking I could keep track of the component I am under at all times and when it changes I redispatch a mouseEntered/mouseExit but I wasn't sure if this was the best way to go about this. Another option was just spamming mouseEntered/mouseExit but I know that won't work.

In the example code I provide two ways I have tried to go about this.

MouseListener way: use mouse events to update glowPanel where the mouse is currently located and repaint. Doesn't work right, doesn't redispatch correctly mouseEntered, mouseExit because GlowPanel never triggers such events (

Thread: Have a thread run in a loop sleeping every so often. When it wakes get mouse location and then repaint the glowPanel with new location. This works but I think the MouseListener way would be better overall if I could get mouseEntered/mouseExit events to work correctly.

I know this code isn't the prettiest. I tried to do this as fast as possible to show an example. I hopefully will go through the code later and make it prettier.

public class GlowPanel extends JPanel{

//Attributes
private MouseAdapter repaintAdapter;
private MouseAdapter redispatchAdapter;
private static Color INNER_COLOR = new Color(30, 30, 30, 127);
private static Color OUTER_COLOR = new Color(90, 90, 90, 127);
private static int RADIUS = 25;
private static int DIAMETER = RADIUS * 2;
private Thread glowThread;
private static Point p = new Point(0,0);
private static GlowPanel glowPanel;
private static Boolean MOUSE_LISTEN_STATE = true;
private static Boolean GLOW_THREAD_STATE = false;
private Boolean CURRENT_STATE;
private static ButtonGroup buttonGroup;

//Start Constructor
public GlowPanel(){
    //Set Attributes
    this.setName("GLOW PANEL");
    this.setOpaque(false);
    this.setVisible(true);
    //this.event

    //Add MouseMouseListener
    this.repaintAdapter = new RepaintMouseAdapter(this);
    this.redispatchAdapter = new RedispatchAdapter();
}
//End Constructor

//Start Methods

/**
 * Set state to mouseListen
 */
public synchronized void setStateMouseListen(){
    if(!MOUSE_LISTEN_STATE.equals(CURRENT_STATE)){
        if(this.glowThread != null){
            this.glowThread.interrupt();
        }
        this.addMouseMotionListener(this.repaintAdapter);
        this.addMouseListener(this.redispatchAdapter);
        this.addMouseMotionListener(this.redispatchAdapter);
        CURRENT_STATE = MOUSE_LISTEN_STATE;
    }
}

/**
 * Set state to off (don't do any effects)
 */
public synchronized void setStateOff(){
    if(this.glowThread != null){
        this.glowThread.interrupt();
    }
    this.removeMouseMotionListener(this.repaintAdapter);
    this.removeMouseListener(this.redispatchAdapter);
    this.removeMouseMotionListener(this.redispatchAdapter);
    CURRENT_STATE = null;
}

/**
 * Set state to GlowThread
 */
public synchronized void setStateGlowThread(){
    if(!GLOW_THREAD_STATE.equals(CURRENT_STATE)){
        this.removeMouseMotionListener(this.repaintAdapter);
        this.removeMouseListener(this.redispatchAdapter);
        this.removeMouseMotionListener(this.redispatchAdapter);
        this.glowThread = new Thread(new Runnable(){
            public void run(){
                while(!Thread.currentThread().isInterrupted()){
                    try {
                        Thread.sleep(1000);
                        GlowPanel.this.p = MouseInfo.getPointerInfo().getLocation();
                        SwingUtilities.convertPointFromScreen(p, GlowPanel.this);
                        GlowPanel.this.repaint();
                    }   catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                }
            }
        });
        this.glowThread.start();
        CURRENT_STATE = GLOW_THREAD_STATE;
    }
}

@Override
public void paintComponent(Graphics g){
    super.paintComponent(g);
    Point p = GlowPanel.this.p;
    Shape circle = new Ellipse2D.Double(p.getX() - RADIUS, p.getY() - RADIUS, DIAMETER, DIAMETER);
    Graphics2D g2 = (Graphics2D) g;

    g2.setColor(GlowPanel.INNER_COLOR);

    //g2.fill(circle);
    Shape circle2 = new Ellipse2D.Double(p.getX() - RADIUS + 9, p.getY() - RADIUS + 9, DIAMETER - 18, DIAMETER - 18);
    //Area a = new Area(circle);
    //a.subtract(new Area(circle2));
    g2.fill(circle);
    g2.setColor(GlowPanel.OUTER_COLOR);
    g2.fill(circle2);
}

/**
 * Create GUI used to show example
 */
public static void createGUI(){
    JFrame jFrame = new JFrame();

    //GlowPanel
    GlowPanel.glowPanel = new GlowPanel();

    //ContentPanel
    JPanel contentPanel = new JPanel();
    GridBagLayout gBL = new GridBagLayout();
    gBL.columnWidths = new int[]{100, 100, 100};
    gBL.rowHeights = new int[]{200, 50};
    contentPanel.setLayout(gBL);

    //Initial Constraints
    GridBagConstraints gBC = new GridBagConstraints();
    gBC.fill = GridBagConstraints.BOTH;
    gBC.gridx = 0;
    gBC.gridy = 0;
    gBC.weightx = 1;
    gBC.weighty = 1;
    gBC.gridwidth = 3;

    //Hover Panel
    JPanel hoverPanel = new JPanel();
    hoverPanel.setOpaque(true);
    hoverPanel.setBackground(Color.blue);
    hoverPanel.addMouseListener(new MouseAdapter(){

        @Override
        public void mouseClicked(MouseEvent e){}

        @Override
        public void mousePressed(MouseEvent e){}

        @Override
        public void mouseReleased(MouseEvent e){}

        @Override
        public void mouseEntered(MouseEvent e){
            hoverPanel.setBackground(Color.yellow);

        }

        @Override
        public void mouseExited(MouseEvent e){
            hoverPanel.setBackground(Color.blue);
        }

    });
    contentPanel.add(hoverPanel, gBC);

    //Create Buttons
    JToggleButton mouseListenButton = new JToggleButton("Mouse Listen");
    mouseListenButton.addActionListener(new AbstractAction(){
        @Override
        public void actionPerformed(ActionEvent e) {
            GlowPanel.glowPanel.setStateMouseListen();
        }
    });
    gBC.gridy++;
    gBC.weighty = 1;
    gBC.gridwidth = 1;
    contentPanel.add(mouseListenButton, gBC);

    JToggleButton glowThreadButton = new JToggleButton("GlowThread Button");
    glowThreadButton.addActionListener(new AbstractAction(){
        @Override
        public void actionPerformed(ActionEvent e) {
            GlowPanel.glowPanel.setStateGlowThread();
        }
    });
    gBC.gridx++;
    contentPanel.add(glowThreadButton, gBC);

    JToggleButton offButton = new JToggleButton("Off Button");
    offButton.addActionListener(new AbstractAction(){
        @Override
        public void actionPerformed(ActionEvent e) {
            GlowPanel.glowPanel.setStateOff();
        }
    });
    gBC.gridx++;
    contentPanel.add(offButton, gBC);

    GlowPanel.buttonGroup = new ButtonGroup();
    GlowPanel.buttonGroup.add(mouseListenButton);
    GlowPanel.buttonGroup.add(glowThreadButton);
    GlowPanel.buttonGroup.add(offButton);

    jFrame.setContentPane(contentPanel);
    jFrame.setGlassPane(GlowPanel.glowPanel);
    jFrame.getGlassPane().setVisible(true);
    jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    jFrame.pack();
    jFrame.setVisible(true);
}

public static void main(String[] args){
    SwingUtilities.invokeLater(new Runnable(){
        public void run(){
            GlowPanel.createGUI();
        }
    });
}

@Override
public boolean isOptimizedDrawingEnabled(){
    return false;
}
//End Methods

public static class RepaintMouseAdapter extends MouseAdapter{
    private JComponent jC;

    public RepaintMouseAdapter(JComponent jC){
        this.jC = jC;
    }

    @Override
    public void mouseMoved(MouseEvent e){
        GlowPanel.p = e.getPoint();
        this.jC.repaint();
    }
}

public static class RedispatchAdapter extends MouseAdapter{
    private JComponent lastComponentEntered;

    @Override
    public void mouseClicked(MouseEvent e){
        this.dispatchEvent(e);
    }

    @Override
    public void mousePressed(MouseEvent e){
        this.dispatchEvent(e);
    }

    @Override
    public void mouseReleased(MouseEvent e){
        this.dispatchEvent(e);
    }

    @Override
    public void mouseEntered(MouseEvent e){
        this.dispatchEvent(e);
        System.out.println("MOUSE ENTERED");
    }

    @Override
    public void mouseExited(MouseEvent e){
        this.dispatchEvent(e);
    }

    @Override
    public void mouseWheelMoved(MouseWheelEvent e){
        this.dispatchEvent(e);
    }

    @Override
    public void mouseDragged(MouseEvent e){
        this.dispatchEvent(e);
    }

    @Override
    public void mouseMoved(MouseEvent e){
        this.dispatchEvent(e);
    }

    private void dispatchEvent(MouseEvent e) {
        Component glass = (Component) e.getSource();
        Point glassPanePoint = e.getPoint();
        Container container = glass.getParent();
        Point containerPoint = SwingUtilities.convertPoint(glass,
                glassPanePoint, container);

        if (containerPoint.y < 0) { // we're not in the content pane
            // Could have special code to handle mouse events over
            // the menu bar or non-system window decorations, such as
            // the ones provided by the Java look and feel.
        } else {
            // The mouse event is probably over the content pane.
            // Find out exactly which component it's over.
            JComponent component = (JComponent) GlowPanel.getDeepestComponentAt(
                    container, containerPoint.x, containerPoint.y);
            //System.out.println(component);
            if (component != null) {
                // Forward events to component below
                Point componentPoint = SwingUtilities.convertPoint(
                        glass, glassPanePoint, component);
                if(e instanceof MouseWheelEvent){
                    MouseWheelEvent wE = (MouseWheelEvent) e;
                    component.dispatchEvent(new MouseWheelEvent(component, wE.getID(), wE.getWhen(),
                            wE.getModifiers(), componentPoint.x, componentPoint.y, wE.getClickCount(),
                            wE.isPopupTrigger(), wE.getScrollType(), wE.getScrollAmount(), wE.getWheelRotation()));
                }   else{
                    component.dispatchEvent(new MouseEvent(component, e
                            .getID(), e.getWhen(), e.getModifiers(),
                            componentPoint.x, componentPoint.y, e
                                    .getClickCount(), e.isPopupTrigger()));
                }

                if(this.lastComponentEntered != null && !this.lastComponentEntered.equals(component)){
                    System.out.println(!this.lastComponentEntered.equals(component));
                }
                if(this.lastComponentEntered != null && !this.lastComponentEntered.equals(component)){
                    e.getComponent().setCursor(component.getCursor());
                    component.dispatchEvent(new MouseEvent(component, MouseEvent.MOUSE_ENTERED, e.getWhen(),
                            e.getModifiers(), componentPoint.x, componentPoint.y,
                            e.getClickCount(), e.isPopupTrigger()));
                    Point lastComponentPoint = SwingUtilities.convertPoint(
                            glass, glassPanePoint, this.lastComponentEntered);
                    this.lastComponentEntered.dispatchEvent(new MouseEvent(this.lastComponentEntered,
                            MouseEvent.MOUSE_EXITED, e.getWhen(),
                            e.getModifiers(), lastComponentPoint.x, lastComponentPoint.y,
                            e.getClickCount(), e.isPopupTrigger()));
                }
                this.lastComponentEntered = component;
                System.out.println(this.lastComponentEntered);
            }

        }
        e.getComponent().repaint();
    }

}

public static Component getDeepestComponentAt(Component parent, int x, int y) {
    if (!parent.contains(x, y)) {
        return null;
    }
    if (parent instanceof Container) {
        Component components[] = ((Container)parent).getComponents();
        for (Component comp : components) {
            if (comp != null && comp.isVisible() && !(comp instanceof GlowPanel) && !(comp instanceof JLabel)) {
                Point loc = comp.getLocation();
                if (comp instanceof Container) {
                    comp = getDeepestComponentAt(comp, x - loc.x, y - loc.y);
                } else {
                    comp = comp.getComponentAt(x - loc.x, y - loc.y);
                }
                if (comp != null && comp.isVisible()) {
                    return comp;
                }
            }
        }
    }
    return parent;
}

}

Hopefully that works. I basically copy pasted what I had in my project into my example class.


问:
How to search and replace using regular expressions in Visual Studio
I need to replace all the urls with empty string:

```<code>""regular"": ""http://fonts.gstatic.com/s/abhayalibre/v3/zTLc5Jxv6yvb1nHyqBasVy3USBnSvpkopQaUR-2r7iU.ttf"",
""500"": ""http://fonts.gstatic.com/s/abhayalibre/v3/wBjdF6T34NCo7wQYXgzrc5MQuUSAwdHsY8ov_6tk1oA.ttf"",
""600"": ""http://fonts.gstatic.com/s/abhayalibre/v3/wBjdF6T34NCo7wQYXgzrc2v8CylhIUtwUiYO7Z2wXbE.ttf"",
""700"": ""http://fonts.gstatic.com/s/abhayalibre/v3/wBjdF6T34NCo7wQYXgzrc0D2ttfZwueP-QU272T9-k4.ttf"",
""800"": ""http://fonts.gstatic.com/s/abhayalibre/v3/wBjdF6T34NCo7wQYXgzrc_qsay_1ZmRGmC8pVRdIfAg.ttf""
</code>```

I've tried using the Regular Expressions with:

"http://fonts(*).ttf"

but i can't see the replace working.

答:
Regular Expression Search and Replace is actually quite well documented.

At the moment you're matching strings that look like this, unless Visual Studio actually fails to parse the expression because of the incorrect usage of *.

```<code>http://font).ttf
http://font().ttf
http://font(().ttf
http://font(((().ttf
http://font((((((((((((((((((((((((((((((().ttf
etc
</code>```

To match any character you could use .*, . being the universal match in Regex, but that will match beyond the closing quotes.

Instead, you can use [^"]+ to match one or more characters except ".

```<code>http://font\.[^"]+
</code>```

Also, note the \. to make sure the regex actually matches the . character, the \ escapes it from being the universal match character.

Body:
I need to replace all the urls with empty string:

""regular"": ""http://fonts.gstatic.com/s/abhayalibre/v3/zTLc5Jxv6yvb1nHyqBasVy3USBnSvpkopQaUR-2r7iU.ttf"",
""500"": ""http://fonts.gstatic.com/s/abhayalibre/v3/wBjdF6T34NCo7wQYXgzrc5MQuUSAwdHsY8ov_6tk1oA.ttf"",
""600"": ""http://fonts.gstatic.com/s/abhayalibre/v3/wBjdF6T34NCo7wQYXgzrc2v8CylhIUtwUiYO7Z2wXbE.ttf"",
""700"": ""http://fonts.gstatic.com/s/abhayalibre/v3/wBjdF6T34NCo7wQYXgzrc0D2ttfZwueP-QU272T9-k4.ttf"",
""800"": ""http://fonts.gstatic.com/s/abhayalibre/v3/wBjdF6T34NCo7wQYXgzrc_qsay_1ZmRGmC8pVRdIfAg.ttf""

I've tried using the Regular Expressions with:

"http://fonts(*).ttf"

but i can't see the replace working.

Body:
Regular Expression Search and Replace is actually quite well documented.

At the moment you're matching strings that look like this, unless Visual Studio actually fails to parse the expression because of the incorrect usage of *.

http://font).ttf
http://font().ttf
http://font(().ttf
http://font(((().ttf
http://font((((((((((((((((((((((((((((((().ttf
etc

To match any character you could use .*, . being the universal match in Regex, but that will match beyond the closing quotes.

Instead, you can use [^"]+ to match one or more characters except ".

http://font\.[^"]+

Also, note the \. to make sure the regex actually matches the . character, the \ escapes it from being the universal match character.


问:
How do I maintain the user credentials when each request can hit multiple servers
Say I have logged into amazon.com. there are say 5 servers present to handle the traffic. Every request from my end hits say Amazon's server 1. Now there are many users coming to picture and my every request can go to server 2 or server 3. How do you make sure that servers two and three communicate communicate with one for my login details??
Which would be the best way to handle it in Java?</p>

答:
I would suggest the following:

Go for a Standalone Authentication and Authorization server.

Any incoming request should first be validated by Authentication
server and then processed.

Authentication and authorization mechanism will probably be Token
Based using OAUth.

To keep things like user preferences etc which expire with the
session, you will probably need a seperate In-memory DB server.


问:
Failed to upload AppName.app
I am trying to run my app on my iPad and I get the following error:

Failed to upload AppName.app

However when I run it in Simulator there are no problems.

答:
Pay your $99 to Apple, log into the developer portal, provision your device (can also be done through organizer). Install that provisioning profile on your iPad and then try and build & run again in xcode.

I highly recommend the organizer route, it simplifies all this for you. But if you opt to do it through the web, there are instructions in the portal to tell you what to do.

Title: Failed to upload AppName.app


答:
Using full Python 3.6 you can do (similarly than Ecir's answer)

```<code>for key, value in stats.items():
    printf(f'{key} - {value}')
</code>```

but being clearer about what is the key and the value and using the f-string interpolation.

Title: Printing parsed JSON in Python

Body:
Assuming this is the .JSON file I have to parse:

{
"item": {
    "allInventory": {
        "onHand": 64,
        "total": {
            "1000": 0,
            "1001": 6,
            "1002": 5,
            "1003": 3,
            "1004": 12,
            "1005": 0
        }
    }
},
"image": {
    "tag": "/828402de-6cc8-493e-8abd-935a48a3d766_1.285a6f66ecf3ee434100921a3911ce6c.jpeg?odnHeight=450&odnWidth=450&odnBg=FFFFFF"
 }
}

How would I go about printing the total values like:

1000 - 0
1001 - 6
1002 - 5
1003 - 4
1004 - 12
1005 - 0

I have already parsed the values, but I'm unsure of how to actually print them. I've already spent awhile on this and couldn't find a solution so any help is appreciated. Here is my code thus far:

import requests
import json

src = requests.get('https://hastebin.com/raw/nenowimite').json()

stats = src['item']['allInventory']['total']
print(stats)

Body:
Using full Python 3.6 you can do (similarly than Ecir's answer)

for key, value in stats.items():
    printf(f'{key} - {value}')

but being clearer about what is the key and the value and using the f-string interpolation.


问:
Glide 4.3.1 override and placeholder features not work
I update my glide to 4.3.1 but all over I use glide the feature .override() and .placeholder() get error: cannot find symbol method.

```<code>Glide.with(this)
            .load(imageUrl)
            .override(200, 200)
            .placeholder(R.drawable.ic_avatar_sign_up)
            .into(ivAvatar);
</code>```

How can I fix this?

答:
You should use RequestOptions

Includes methods like:

centerCrop()

placeholder()

error()

priority()

diskCacheStrategy()

priority()

override(100, 100)

transforms()

Sample code

```<code>Glide.with(this)
     .load(YOUR_URL)
     .apply(new RequestOptions().override(100, 100).placeholder(R.drawable.placeHolder).error(R.drawable.error_pic))
     .into(imageview);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I update my glide to 4.3.1 but all over I use glide the feature .override() and .placeholder() get error: cannot find symbol method.

Glide.with(this)
            .load(imageUrl)
            .override(200, 200)
            .placeholder(R.drawable.ic_avatar_sign_up)
            .into(ivAvatar);

How can I fix this?

Body:
You should use RequestOptions

Includes methods like:

centerCrop()

placeholder()

error()

priority()

diskCacheStrategy()

priority()

override(100, 100)

transforms()

Sample code

Glide.with(this)
     .load(YOUR_URL)
     .apply(new RequestOptions().override(100, 100).placeholder(R.drawable.placeHolder).error(R.drawable.error_pic))
     .into(imageview);