问:
CSS Grab All Class Name Except For Last
I want to grab all the class name ('my-class') and change it's color to red EXCEPT for the last one

Apparently I've been googling and there's no such thing as :last-of-class or whatever. I'm having trouble trying to find a work around without using JS.

div1 and div2 are both dynamic! If div2 doesn't exist, then div1 should have the first p element red and the second not.

Please note I left a 'p' tag at the top because I don't want that being part of my selector. I just need the 'my-class' specifically.

or is there a selector I can write to grab all "p"s inside of my-container which include nested P's

```<code><p>Some text</p>
<div class="my-container">
  <div class="div1">
    <p class="my-class"></p>
    <p class="my-class"></p>
  </div>
  <div class="div2">
    <p class="my-class"></p>
    <p class="my-class"></p>
    <p class="my-class"></p>
    <p class="my-class"></p>   <!-- This tag should not be red-->
  </div>
</div>
</code>```

I can also use sass so feel free to include that in if need be.

答:
This will get the behavior you're looking for without any forced reflow:

.my-class:not(:last-child) {
    color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>Some text</p>
<div class="my-container">
  <div class="div1">
    <p class="my-class">a</p>
    <p class="my-class">b</p>
  </div>
  <div class="div2">
    <p class="my-class">c</p>
    <p class="my-class">d</p>
    <p class="my-class">e</p>
    <p class="my-class">f</p>   <!-- This tag should not be red-->
  </div>
</div></code>```

Title: CSS Grab All Class Name Except For Last

Body:
I want to grab all the class name ('my-class') and change it's color to red EXCEPT for the last one

Apparently I've been googling and there's no such thing as :last-of-class or whatever. I'm having trouble trying to find a work around without using JS.

div1 and div2 are both dynamic! If div2 doesn't exist, then div1 should have the first p element red and the second not.

Please note I left a 'p' tag at the top because I don't want that being part of my selector. I just need the 'my-class' specifically.

or is there a selector I can write to grab all "p"s inside of my-container which include nested P's

Some text

I can also use sass so feel free to include that in if need be.

Body:
This will get the behavior you're looking for without any forced reflow:

.my-class:not(:last-child) {
    color: red;
}

<p>Some text</p>
<div class="my-container">
  <div class="div1">
    <p class="my-class">a</p>
    <p class="my-class">b</p>
  </div>
  <div class="div2">
    <p class="my-class">c</p>
    <p class="my-class">d</p>
    <p class="my-class">e</p>
    <p class="my-class">f</p>   <!-- This tag should not be red-->
  </div>
</div>


来源: stackexchange

问:
Azure Service Bus - Lowering round trip time
We are checking out Azure Service bus to use it as our on premise service bus. We are testing the round trip time and it seems to fluctuate between 10 ms and 2000 ms. On average it is around 100-200ms. There seems to be a warm up time that goes from 2 seconds and moves down to 200ms on higher load.

Is there any way to get a lower average round trip time?

Does it help to use the premium tier?
--> (Edit: Didn't help. With 1 message unit, the average was in fact worse with a premium tier)

Our setup:

Consumer (PC#1)

Producer (PC#2) (note: These two computers are on the same local network)

Azure Service Bus (actually on azure)

Side note/fun fact: Distance 1500km to microsoft data center. Speed of light uses ~10ms round trip.

Test 1:

Message count: 1000 pr minute

MaxConcurrentCalls: 1

Operation: Receive and delete message

Prefetch count: 0

Start avg. 1-2s

End avg. 100-200ms

Output: Pastebin link

Sample output:

```<code>20; 2017-12-07T11:41:48.5134157+01:00; 2017-12-07T11:41:48.7781795+01:00; 264,7638
3; 2017-12-07T11:41:47.4827021+01:00; 2017-12-07T11:41:48.8378167+01:00; 1355,1146
14; 2017-12-07T11:41:48.1491488+01:00; 2017-12-07T11:41:48.8950421+01:00; 745,8933
0; 2017-12-07T11:41:47.2250519+01:00; 2017-12-07T11:41:48.9518713+01:00; 1726,8194
</code>```

Test 2:

Message count: 1000 pr minute

MaxConcurrentCalls: 1000

Operation: Receive and delete message

Prefetch count: 0

Start avg. 1-2s

End avg. 100-200ms (note: with spikes up to 20 seconds)

Output: Pastebin link

Sample output:

```<code>4; 2017-12-07T11:43:43.5735023+01:00; 2017-12-07T11:43:44.7905668+01:00; 1217,0645
8; 2017-12-07T11:43:43.8166842+01:00; 2017-12-07T11:43:44.8424773+01:00; 1025,7931
11; 2017-12-07T11:43:43.9990189+01:00; 2017-12-07T11:43:44.8989094+01:00; 899,8905
10; 2017-12-07T11:43:43.9383692+01:00; 2017-12-07T11:43:44.9553891+01:00; 1017,0199
</code>```

Test 3:

Message count: 1000 pr minute

MaxConcurrentCalls: 1000

Operation: Receive and delete message

Prefetch count: 1000

Start avg. 1-2s (warm up significantly reduced)

End avg. ~100ms(note: with spikes up to max 4.5 seconds, significantly less spikes)

Output: Pastebin link

Sample output:

```<code>11; 2017-12-07T11:54:16.8149682+01:00; 2017-12-07T11:54:17.6029464+01:00; 787,9782
14; 2017-12-07T11:54:16.9967915+01:00; 2017-12-07T11:54:17.6709669+01:00; 674,1754
0; 2017-12-07T11:54:16.0599312+01:00; 2017-12-07T11:54:17.6720080+01:00; 1612,0768
15; 2017-12-07T11:54:17.0578415+01:00; 2017-12-07T11:54:17.6724941+01:00; 614,6526
</code>```

=========================

Client:

```<code>using System;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.ServiceBus;

namespace Sticos.ServiceBus.Client
{
    public class ServiceBusClient
    {
        private readonly string _connectionstring;
        private readonly string _topic;
        private readonly TopicClient _topicClient;

        public ServiceBusClient(string connectionstring, string topic)
        {
            _connectionstring = connectionstring ?? throw new ArgumentNullException(nameof(connectionstring));
            _topic = topic ?? throw new ArgumentNullException(nameof(topic));
            _topicClient = new TopicClient(_connectionstring, _topic);
        }

        public async Task SendAsync(string message)
        {
            await _topicClient.SendAsync(
                new Message()
                {
                    Body = Encoding.UTF8.GetBytes(message + ";" + DateTime.Now.ToString())
                });
        }
    }
}
</code>```

Producer:

```<code>using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Sticos.ServiceBus.Client.Test
{
    [TestClass]
    public class ServiceBusClientTest
    {
        [TestMethod]
        public void Producer()
        {
            var serviceBus = new ServiceBusClient("[connectionstring]", "[topic]");

            var producer = Task.Factory.StartNew(() =>
            {
                var tasks = new Task[1000];
                for (int i = 0; i < 1000; i++)
                {
                    tasks[i] = serviceBus.SendAsync($"{i};{DateTime.Now.ToString("o")}");
                    Thread.Sleep(60);
                }

                Task.WaitAll(tasks);
            });

            Task.WaitAll(producer);
        }
    }
}
</code>```

答:
Premium tier of service bus offers consistent performance, as your namespace will have dedicated resources undisturbed by noisy neighbors. On standard tier, performance fluctuates depending on the overall load on the service as your queues/topics share resources with queues/topics from other customers.

Coming to the time taken for a message to reach consumer from producer, I can tell you that there are no delays or other settings in service bus that introduce delay. Service bus delivers messages as fast as it could. I can't really talk or help about network transmission speeds.

But I think improving the throughput of receiving messages will also lower the average time taken for a message to reach the consumer. btw, you didn't paste the code for consumer here. I would suggest few improvement for you to try. Batching of sends really helps performance. Instead of sending one message per send call, send in batches of 10s or 100s based on message size. Also on the receiver, try to use RECEIVEANDDELETE mode if PEEKLOCK/COMPLETE pattern is not that important to you. And using too many concurrent calls means using too many threads. Try adjusting max concurrent calls and prefetch count values and see how throughput changes.

Also AMQP delivers better performance over NetMessaging or Http. Check your client configuration for the protocol being used and change it to AMQP.

As other answers have suggested, more connections will definitely improve throughput. Simply use more senders and more receivers.

ContentLicense: CC BY-SA 3.0

Body:
We are checking out Azure Service bus to use it as our on premise service bus. We are testing the round trip time and it seems to fluctuate between 10 ms and 2000 ms. On average it is around 100-200ms. There seems to be a warm up time that goes from 2 seconds and moves down to 200ms on higher load.

Is there any way to get a lower average round trip time?

Does it help to use the premium tier?
--> (Edit: Didn't help. With 1 message unit, the average was in fact worse with a premium tier)

Our setup:

Consumer (PC#1)

Producer (PC#2) (note: These two computers are on the same local network)

Azure Service Bus (actually on azure)

Side note/fun fact: Distance 1500km to microsoft data center. Speed of light uses ~10ms round trip.

Test 1:

Message count: 1000 pr minute

MaxConcurrentCalls: 1

Operation: Receive and delete message

Prefetch count: 0

Start avg. 1-2s

End avg. 100-200ms

Output: Pastebin link

Sample output:

20; 2017-12-07T11:41:48.5134157+01:00; 2017-12-07T11:41:48.7781795+01:00; 264,7638
3; 2017-12-07T11:41:47.4827021+01:00; 2017-12-07T11:41:48.8378167+01:00; 1355,1146
14; 2017-12-07T11:41:48.1491488+01:00; 2017-12-07T11:41:48.8950421+01:00; 745,8933
0; 2017-12-07T11:41:47.2250519+01:00; 2017-12-07T11:41:48.9518713+01:00; 1726,8194

Test 2:

Message count: 1000 pr minute

MaxConcurrentCalls: 1000

Operation: Receive and delete message

Prefetch count: 0

Start avg. 1-2s

End avg. 100-200ms (note: with spikes up to 20 seconds)

Output: Pastebin link

Sample output:

4; 2017-12-07T11:43:43.5735023+01:00; 2017-12-07T11:43:44.7905668+01:00; 1217,0645
8; 2017-12-07T11:43:43.8166842+01:00; 2017-12-07T11:43:44.8424773+01:00; 1025,7931
11; 2017-12-07T11:43:43.9990189+01:00; 2017-12-07T11:43:44.8989094+01:00; 899,8905
10; 2017-12-07T11:43:43.9383692+01:00; 2017-12-07T11:43:44.9553891+01:00; 1017,0199

Test 3:

Message count: 1000 pr minute

MaxConcurrentCalls: 1000

Operation: Receive and delete message

Prefetch count: 1000

Start avg. 1-2s (warm up significantly reduced)

End avg. ~100ms(note: with spikes up to max 4.5 seconds, significantly less spikes)

Output: Pastebin link

Sample output:

11; 2017-12-07T11:54:16.8149682+01:00; 2017-12-07T11:54:17.6029464+01:00; 787,9782
14; 2017-12-07T11:54:16.9967915+01:00; 2017-12-07T11:54:17.6709669+01:00; 674,1754
0; 2017-12-07T11:54:16.0599312+01:00; 2017-12-07T11:54:17.6720080+01:00; 1612,0768
15; 2017-12-07T11:54:17.0578415+01:00; 2017-12-07T11:54:17.6724941+01:00; 614,6526

=========================

Client:

using System;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.ServiceBus;

namespace Sticos.ServiceBus.Client
{
    public class ServiceBusClient
    {
        private readonly string _connectionstring;
        private readonly string _topic;
        private readonly TopicClient _topicClient;

        public ServiceBusClient(string connectionstring, string topic)
        {
            _connectionstring = connectionstring ?? throw new ArgumentNullException(nameof(connectionstring));
            _topic = topic ?? throw new ArgumentNullException(nameof(topic));
            _topicClient = new TopicClient(_connectionstring, _topic);
        }

        public async Task SendAsync(string message)
        {
            await _topicClient.SendAsync(
                new Message()
                {
                    Body = Encoding.UTF8.GetBytes(message + ";" + DateTime.Now.ToString())
                });
        }
    }
}

Producer:

using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Sticos.ServiceBus.Client.Test
{
    [TestClass]
    public class ServiceBusClientTest
    {
        [TestMethod]
        public void Producer()
        {
            var serviceBus = new ServiceBusClient("[connectionstring]", "[topic]");

            var producer = Task.Factory.StartNew(() =>
            {
                var tasks = new Task[1000];
                for (int i = 0; i < 1000; i++)
                {
                    tasks[i] = serviceBus.SendAsync($"{i};{DateTime.Now.ToString("o")}");
                    Thread.Sleep(60);
                }

                Task.WaitAll(tasks);
            });

            Task.WaitAll(producer);
        }
    }
}


问:
SQL STUFF and XML Path - Can't get space between results
SQL Server 2012

Goal: Combine multiple money rows into one string with a space between.

I have tried a variety of edits and modifications and I can't seem to get this correct.

Here is the data I'm looking at:

```<code>Table1.[Misc Amount]
Table2.Taxes
</code>```

My column name has a space which really made the xml path angry I guess.

Statement used:

```<code>DECLARE @Misc nvarchar(30)
SET @Misc = (SELECT [Misc Amount] FROM Table1 WHERE Order=33532)

SELECT @Misc + ' '+ STUFF((SELECT ' ' + SUM(TaxAmount ) AS [text()]
FROM Table2
WHERE Order=33532
GROUP BY Code FOR XML Path('')), 1,0,'')
</code>```

I also tried as string value, [node()], playing with the positions like 1,2, etc.

My resulting data is:

```<code>10.00 0.006.084.50
</code>```

What I want is

```<code>10.00 0.00 6.08 4.50
</code>```

I'd love to exclude the 0.00 but at the moment I'd be happy with just my spaces.... I really hate stuff statements. Any of you kind gurus have a way to help me?

答:
Your TaxAmount column is probably of a numerical data type. Therefore your string with the space in it is being omitted. Cast it to a string data type and your in business.</p>

```<code>CREATE TABLE #MiscAmount ([Order] int, [Misc Amount] money)
CREATE TABLE #Taxes ([Order] int, Code int, TaxAmount money)

INSERT INTO #MiscAmount ([Order], [Misc Amount]) VALUES (33532, 10.00)
INSERT INTO #Taxes ([Order], Code, TaxAmount) VALUES
(33532, 1, 0.00),
(33532, 2, 6.08),
(33532, 3, 4.50)

DECLARE @Misc nvarchar(30)
SET @Misc = (SELECT [Misc Amount] FROM #MiscAmount WHERE [Order] = 33532)

SELECT @Misc + ' '+ STUFF((SELECT ' ' + CAST(SUM(TaxAmount) AS varchar(50)) AS [text()]
FROM #Taxes
WHERE [Order] = 33532
GROUP BY Code FOR XML Path('')), 1,0,'')

DROP TABLE #MiscAmount
DROP TABLE #Taxes
</code>```

Body:
SQL Server 2012

Goal: Combine multiple money rows into one string with a space between.

I have tried a variety of edits and modifications and I can't seem to get this correct.

Here is the data I'm looking at:

Table1.[Misc Amount]
Table2.Taxes

My column name has a space which really made the xml path angry I guess.

Statement used:

DECLARE @Misc nvarchar(30)
SET @Misc = (SELECT [Misc Amount] FROM Table1 WHERE Order=33532)

SELECT @Misc + ' '+ STUFF((SELECT ' ' + SUM(TaxAmount ) AS [text()]
FROM Table2
WHERE Order=33532
GROUP BY Code FOR XML Path('')), 1,0,'')

I also tried as string value, [node()], playing with the positions like 1,2, etc.

My resulting data is:

10.00 0.006.084.50

What I want is

10.00 0.00 6.08 4.50

I'd love to exclude the 0.00 but at the moment I'd be happy with just my spaces.... I really hate stuff statements. Any of you kind gurus have a way to help me?

Body:
Your TaxAmount column is probably of a numerical data type. Therefore your string with the space in it is being omitted. Cast it to a string data type and your in business.

CREATE TABLE #MiscAmount ([Order] int, [Misc Amount] money)
CREATE TABLE #Taxes ([Order] int, Code int, TaxAmount money)

INSERT INTO #MiscAmount ([Order], [Misc Amount]) VALUES (33532, 10.00)
INSERT INTO #Taxes ([Order], Code, TaxAmount) VALUES
(33532, 1, 0.00),
(33532, 2, 6.08),
(33532, 3, 4.50)

DECLARE @Misc nvarchar(30)
SET @Misc = (SELECT [Misc Amount] FROM #MiscAmount WHERE [Order] = 33532)

SELECT @Misc + ' '+ STUFF((SELECT ' ' + CAST(SUM(TaxAmount) AS varchar(50)) AS [text()]
FROM #Taxes
WHERE [Order] = 33532
GROUP BY Code FOR XML Path('')), 1,0,'')

DROP TABLE #MiscAmount
DROP TABLE #Taxes


问:
My batch script doesn't work. Can anyone tell me why?
I need help with my script. All of the stuff keeps falling through and not doing the goto. Can you help?</p>

```<code>@ECHO OFF
goto joshua
:joshua
Echo Hello my name is Joshua.
echo What is yours?
set /p name=
cls
Echo Hello %name%.
cls
Echo How are you?
set /p feeling=
cls
echo Is this good?
echo Im sorry I am still learning human feelings.
set /p humanfeelings=Yes/No
if %humanfeelings%==Yes goto Good
if %humanfeelings%==No goto Bad
cls
:Good
Echo Well that is pleasent.
Echo Would you like to play a game %name%?
set /p answer=Yes/No
if %answer%==Yes goto startmenu
if %answer%== No goto quit
cls
:Bad
echo That is not good.
echo Would you like to play a game %name%?
set /p answera=Yes/No
if %answera%==Yes goto startmenu
if %answera%== No goto later
cls
:startmenu
start menu.bat
cls
:later
Echo That is fine %name%, maybe later
pause
exit
</code>```

答: Okay, from what I see wrong here is that you don't jump anywhere in the end of Good/Bad handling. This means that no matter if you type "Yes" or "No", Bad/startmenu/later blocks are always executed, one after another. Is that the problem you're having? Then just add some more goto-s.</p>

ContentLicense: CC BY-SA 2.5

Body:
I need help with my script. All of the stuff keeps falling through and not doing the goto. Can you help?

@ECHO OFF
goto joshua
:joshua
Echo Hello my name is Joshua.
echo What is yours?
set /p name=
cls
Echo Hello %name%.
cls
Echo How are you?
set /p feeling=
cls
echo Is this good?
echo Im sorry I am still learning human feelings.
set /p humanfeelings=Yes/No
if %humanfeelings%==Yes goto Good
if %humanfeelings%==No goto Bad
cls
:Good
Echo Well that is pleasent.
Echo Would you like to play a game %name%?
set /p answer=Yes/No
if %answer%==Yes goto startmenu
if %answer%== No goto quit
cls
:Bad
echo That is not good.
echo Would you like to play a game %name%?
set /p answera=Yes/No
if %answera%==Yes goto startmenu
if %answera%== No goto later
cls
:startmenu
start menu.bat
cls
:later
Echo That is fine %name%, maybe later
pause
exit


问:
Is my database in an elastic pool?
I am trying to set up an Azure SQL Database inside of an elastic pool. I'm not sure if I did it right.  Here's my dashboard:

And here's the actual database:

What makes me wonder if the database is actually inside the elastic pool is what's circled in red in the above screenshot.

No elastic pool

Here's the server:

And here's the elastic pool:

Another clue that the DB is not in the pool is that the pool shows no usage.

So, I'm pretty sure I did something wrong. But I can't seem to figure out HOW to put the database inside the pool.

Help!?!

答: You can add database to elastic pool as long as they are on the same logical server. Here's the article. Search for "Move a database into an elastic pool". I cannot really copy text from there to here as there is no text, only a bunch of images.</p>

Title: Is my database in an elastic pool?


问:
Azure queue trigger vs service bus queue trigger, which one do I need?
I'm trying to understand the difference between a queue trigger and a service bus queue trigger and which one I need!

I have a asp.net mvc site that is for creating and scheduling classes, which will be represented as a row in a db table. When a class is over I want to send an email to all students asking them to rate their teacher

As far as I'm aware the best way to do this is to create a Azure function that will create and send the emails, but where I'm lost is how to trigger that function at a specific date and time?

Do I use a queue trigger or a service bus queue trigger? What's the difference between the two and which one would be the best for my scenario?

I need to be able to cancel the message in the queue if the class is canceled.

答:
If cancelling scheduled messages is a hard requirement, only Service Bus allows doing that, see this blog.

However, it might be more practical to just add a check whether the class was cancelled at the beginning of your Azure Function, and quit if so.

For the rest of your scenarios, the services will both fit.

Generally, Service Bus has more advanced capabilities and guarantees, but costs more money if you send lots of messages. I usually pick Storage Queues unless I need any of those more advanced features.


问:
How do both these pieces of code have the same output, provided len>0
I understand the second piece of code, but not the first one.

First code:

```<code>int max(int a[], int len)
{
 if (len == 1)
  return a[0];
 int m = max(a+1, len-1);
 if (a[0] > m)
  return a[0];
 return m;
}
</code>```

Second code:

```<code>int max(int a[], int len) {
 int m = a[0];
 for (int i = 0; i < len; ++i)
  if (a[i] > m)
   m = a[i];
 return m;
}
</code>```

In the first piece of code, what value is m actually storing everytime the function max is called

答:
a+1 is the address of a[1], so the recursive call returns the maximum of the sub-array starting with the second element, and assigns that to m. If the first element is larger than that, it's the largest element of the array, otherwise the largest element is m.

Suppose your array is [1, 3, 6, 4, 2] and len = 5. The first time max() is called, it does:

```<code>m = max([3, 6, 4, 2], 4);
</code>```

This then does:

```<code>m = max([6, 4, 2], 3);
</code>```

This does:

```<code>m = max([4, 2], 2);
</code>```

which does:

```<code>m = max([2], 1);
</code>```

This last case makes the test if (len == 1) true, so it returns a[0], and the last m is set to 2. It then does:

```<code>if (a[0] > m) {
    return a[0];
}
</code>```

In that case, a[0] == 4, so this condition is successful and it returns 4 to the next m. In that caller, a[0] == 6, so the condition is again successful, so it returns 6 to its m.

In the next caller, a[0] == 3, so a[0] > m will be false, so it returns m, which is still 6.

And in the next caller, a[0] == 1, so a[0] > m will still be false, so it returns m, which is still 6, and that's the final result.

Body:
I understand the second piece of code, but not the first one.

First code:

int max(int a[], int len)
{
 if (len == 1)
  return a[0];
 int m = max(a+1, len-1);
 if (a[0] > m)
  return a[0];
 return m;
}

Second code:

int max(int a[], int len) {
 int m = a[0];
 for (int i = 0; i < len; ++i)
  if (a[i] > m)
   m = a[i];
 return m;
}

In the first piece of code, what value is m actually storing everytime the function max is called

Body:
a+1 is the address of a[1], so the recursive call returns the maximum of the sub-array starting with the second element, and assigns that to m. If the first element is larger than that, it's the largest element of the array, otherwise the largest element is m.

Suppose your array is [1, 3, 6, 4, 2] and len = 5. The first time max() is called, it does:

m = max([3, 6, 4, 2], 4);

This then does:

m = max([6, 4, 2], 3);

This does:

m = max([4, 2], 2);

which does:

m = max([2], 1);

This last case makes the test if (len == 1) true, so it returns a[0], and the last m is set to 2. It then does:

if (a[0] > m) {
    return a[0];
}

In that case, a[0] == 4, so this condition is successful and it returns 4 to the next m. In that caller, a[0] == 6, so the condition is again successful, so it returns 6 to its m.

In the next caller, a[0] == 3, so a[0] > m will be false, so it returns m, which is still 6.

And in the next caller, a[0] == 1, so a[0] > m will still be false, so it returns m, which is still 6, and that's the final result.


问:
sqlite3 nodejs - return data synchronously
Every example I can find on sqlite3 and nodejs just writes the data to the console, which is useless - how do I await a data and return it from a calling method ? Lets say I have :

```<code>exports.selectData = function(tableName, parameters, successHandler) {
  var dbConn = new sqlite3.Database('./data/myAppsData.db');
  dbConn.all("SELECT " + parameters + " FROM " + tableName + "", function(err, rows) {
    // what to do here ? or somewhere else ?
  });
}
</code>```

How do I get data (rows) to return from selectData ? Or alternatively, using successHandler callback ? (it is undefined where the comment is)

答:
```<code>  dbConn.all("SELECT " + parameters + " FROM " + tableName + "", function(err, rows) {
    return rows // could replace with JSON.stringify(rows) If you want to pass JSON data
  });
</code>```

Or as ionizer said you could return a promise. If you need to use async/await

```<code>exports.selectData = function(tableName, parameters, successHandler) {
  var dbConn = new sqlite3.Database('./data/myAppsData.db');
  return new Promise((resolve, reject) => {
   dbConn.all("SELECT " + parameters + " FROM " + tableName + "",
    function(err, rows) {
     if(err) {
       reject (err);
     } else {
       resolve(rows);
     }
   });
  });
}
</code>```

Body:
Every example I can find on sqlite3 and nodejs just writes the data to the console, which is useless - how do I await a data and return it from a calling method ? Lets say I have :

exports.selectData = function(tableName, parameters, successHandler) {
  var dbConn = new sqlite3.Database('./data/myAppsData.db');
  dbConn.all("SELECT " + parameters + " FROM " + tableName + "", function(err, rows) {
    // what to do here ? or somewhere else ?
  });
}

How do I get data (rows) to return from selectData ? Or alternatively, using successHandler callback ? (it is undefined where the comment is)

Body:
  dbConn.all("SELECT " + parameters + " FROM " + tableName + "", function(err, rows) {
    return rows // could replace with JSON.stringify(rows) If you want to pass JSON data
  });

Or as ionizer said you could return a promise. If you need to use async/await

exports.selectData = function(tableName, parameters, successHandler) {
  var dbConn = new sqlite3.Database('./data/myAppsData.db');
  return new Promise((resolve, reject) => {
   dbConn.all("SELECT " + parameters + " FROM " + tableName + "",
    function(err, rows) {
     if(err) {
       reject (err);
     } else {
       resolve(rows);
     }
   });
  });
}


问:
Dual Container View Animation iOS
So I've got a ViewController, which has two Container Views.  The top one is the main content.  The bottom one is a banner that will hide/show on certain events.

The bottom one is positioned such that it is under the tab bar until the event occurs.

When the event occurs, the frame of the main view is shrank and the frame of the banner is repositioned, such that it appears to 'slide' into the view and become available.

The problem I'm having is, unless I resize the main view in the storyboard (which is not what I want), any resizing I do in code DOES reveal the banner, but the banner does not respond to touches.  (Resizing in storyboard, it does respond.)  It seems that there's some other view in front of it that's intercepting the touches, but what, and how do I fix it?

The main view controller:

```<code>func hideBanner() {
    bannerViewController?.toggleBannerDisplay(show: false)
    contentTableViewController?.toggleBannerDisplay(show: false)
}
func showBanner() {
    bannerViewController?.toggleBannerDisplay(show: true)
    contentTableViewController?.toggleBannerDisplay(show: true)
}
</code>```

The content table view controller:

```<code>func toggleBannerDisplay(show: Bool) {
    let tableView = self.view as! UITableView

    UIView.animate(withDuration: 0.5, animations: {
        if self.cancelApplyShowing == false && show == true {
            let frame = tableView.frame
            let newFrame = CGRect(x:frame.origin.x , y: frame.origin.y, width: frame.size.width, height: frame.size.height - 48)
            tableView.contentSize = newFrame.size
            tableView.frame = newFrame
            self.cancelApplyShowing = true
        } else if self.cancelApplyShowing == true && show == false {
            let frame = tableView.frame
            let newFrame = CGRect(x:frame.origin.x , y: frame.origin.y, width: frame.size.width, height: frame.size.height + 48)
            tableView.contentSize = newFrame.size
            tableView.frame = newFrame
            self.cancelApplyShowing = false
        }
    })
}
</code>```

The banner:

```<code>func toggleBannerDisplay(show: Bool) {
    UIView.animate(withDuration: 0.5, animations: {
        if self.cancelApplyShowing == false && show == true {
            let frame = self.view.frame
            let newFrame = CGRect(x: frame.origin.x, y: frame.origin.y - 48, width: frame.size.width, height: frame.size.height)
            self.view.frame = newFrame
            self.cancelApplyShowing = true
        } else if self.cancelApplyShowing == true && show == false {
            self.view.frame.origin.y += 48
            self.cancelApplyShowing = false
        }
    })
}
</code>```

For some reason, if I resize that main view, the hidden view becomes responsive (after animations of course).

Vimeo video: https://vimeo.com/246496442

答:
I was trying to animate the embedded view controller's views, which did bring everything up and into place, but the container view was still sitting invisibly over the top.

I animated the container views and everything works fine now.

Title: Dual Container View Animation iOS

Body:
So I've got a ViewController, which has two Container Views.  The top one is the main content.  The bottom one is a banner that will hide/show on certain events.

The bottom one is positioned such that it is under the tab bar until the event occurs.

When the event occurs, the frame of the main view is shrank and the frame of the banner is repositioned, such that it appears to 'slide' into the view and become available.

The problem I'm having is, unless I resize the main view in the storyboard (which is not what I want), any resizing I do in code DOES reveal the banner, but the banner does not respond to touches.  (Resizing in storyboard, it does respond.)  It seems that there's some other view in front of it that's intercepting the touches, but what, and how do I fix it?

The main view controller:

func hideBanner() {
    bannerViewController?.toggleBannerDisplay(show: false)
    contentTableViewController?.toggleBannerDisplay(show: false)
}
func showBanner() {
    bannerViewController?.toggleBannerDisplay(show: true)
    contentTableViewController?.toggleBannerDisplay(show: true)
}

The content table view controller:

func toggleBannerDisplay(show: Bool) {
    let tableView = self.view as! UITableView

    UIView.animate(withDuration: 0.5, animations: {
        if self.cancelApplyShowing == false && show == true {
            let frame = tableView.frame
            let newFrame = CGRect(x:frame.origin.x , y: frame.origin.y, width: frame.size.width, height: frame.size.height - 48)
            tableView.contentSize = newFrame.size
            tableView.frame = newFrame
            self.cancelApplyShowing = true
        } else if self.cancelApplyShowing == true && show == false {
            let frame = tableView.frame
            let newFrame = CGRect(x:frame.origin.x , y: frame.origin.y, width: frame.size.width, height: frame.size.height + 48)
            tableView.contentSize = newFrame.size
            tableView.frame = newFrame
            self.cancelApplyShowing = false
        }
    })
}

The banner:

func toggleBannerDisplay(show: Bool) {
    UIView.animate(withDuration: 0.5, animations: {
        if self.cancelApplyShowing == false && show == true {
            let frame = self.view.frame
            let newFrame = CGRect(x: frame.origin.x, y: frame.origin.y - 48, width: frame.size.width, height: frame.size.height)
            self.view.frame = newFrame
            self.cancelApplyShowing = true
        } else if self.cancelApplyShowing == true && show == false {
            self.view.frame.origin.y += 48
            self.cancelApplyShowing = false
        }
    })
}

For some reason, if I resize that main view, the hidden view becomes responsive (after animations of course).

Vimeo video: https://vimeo.com/246496442


问:
Is there a way in HTML (or ColdFusion) to have a radio button trigger a hyperlink without having to submit a form?
I want to have a pair of radio buttons sitting over an HTML table so that whenever the rb is clicked it will cause the table to rebuild (rebuild the page) by submitting a different URL variable. Is there a way to do this without having to build a form and click a submit button? I'm pretty new to this stuff so please keep any answers basic and/or show samples of code. Thanks!</p>

答:
Yes there is, you can use Javascript event binding to help you achieve this. This will get you started. This adds an event binding so when you "change" or click the radio buttons, it can fire an event off.

From here you'd need to research how to rebuild the table data in JS if you don't already know.

```<code>$("input[@name='nameofinput']").change(function(){
    // Do something interesting here
});
</code>```

Body:
Yes there is, you can use Javascript event binding to help you achieve this. This will get you started. This adds an event binding so when you "change" or click the radio buttons, it can fire an event off.

From here you'd need to research how to rebuild the table data in JS if you don't already know.

$("input[@name='nameofinput']").change(function(){
    // Do something interesting here
});


问:
Include JavaDB into .jar file (Netbeans)
I have finally finished my project - a small multiple-choice/vocabulary trainer and I'd like to use it as a standalone jar now.
Problem now is: If I do start it within the build-folder (projectname/dist) everything runs fine.
But when I try to run it from somewhere else I can't connect to the database anymore.

Is there a way to include the DB-files to the .jar file? Or to just copy it to the same folder? Or do I need to have JavaDB installed on the PC's I run it on?

This is the way I do connect to the db:

```<code>Class.forName("org.apache.derby.jdbc.ClientDriver");
con = DriverManager.getConnection("jdbc:derby://localhost:1527/DataBase");
stmt = con.createStatement();
</code>```

So is there any chance I can create a portable app of this, which I can run eg from an usb-stick?

答: You do not install JavaDB. However, it will create files, if you tell it to, that hold your DB info. Look at the create=yes option on the JDBC URL. You will have to tell it where to put the files for the DB. They could be on a USB, as long as it is writable.</p>

Body:
I have finally finished my project - a small multiple-choice/vocabulary trainer and I'd like to use it as a standalone jar now.
Problem now is: If I do start it within the build-folder (projectname/dist) everything runs fine.
But when I try to run it from somewhere else I can't connect to the database anymore.

Is there a way to include the DB-files to the .jar file? Or to just copy it to the same folder? Or do I need to have JavaDB installed on the PC's I run it on?

This is the way I do connect to the db:

Class.forName("org.apache.derby.jdbc.ClientDriver");
con = DriverManager.getConnection("jdbc:derby://localhost:1527/DataBase");
stmt = con.createStatement();

So is there any chance I can create a portable app of this, which I can run eg from an usb-stick?


问:
in operator, float("NaN") and np.nan
I used to believe that in operator in Python checks the presence of element in some collection using equality checking ==, so element in some_list is roughly equivalent to any(x == element for x in some_list). For example:

```<code>True in [1, 2, 3]
# True because True == 1
</code>```

or

```<code>1 in [1., 2., 3.]
# also True because 1 == 1.
</code>```

However, it is well-known that NaN is not equal to itself. So I expected that float("NaN") in [float("NaN")] is False. And it is False indeed.

However, if we use numpy.nan instead of float("NaN"), the situation is quite different:

```<code>import numpy as np
np.nan in [np.nan, 1, 2]
# True
</code>```

But np.nan == np.nan still gives False!

How is it possible? What's the difference between np.nan and float("NaN")? How does in deal with np.nan?

答:
To check if the item is in the list, Python tests for object identity first, and then tests for equality only if the objects are different.1

float("NaN") in [float("NaN")] is False because two different NaN  objects are involved in the comparison. The test for identity therefore returns False, and then the test for equality also returns False since NaN != NaN.

np.nan in [np.nan, 1, 2] however is True because the same NaN object is involved in the comparison. The test for object identity returns True and so Python immediately recognises the item as being in the list.

The __contains__ method (invoked using in) for many of Python's other builtin Container types, such as tuples and sets, is implemented using the same check.

1 At least this is true in CPython. Object identity here means that the objects are found at the same memory address: the contains method for lists is performed using PyObject_RichCompareBool which quickly compares object pointers before a potentially more complicated object comparison. Other Python implementations may differ.

Title: in operator, float("NaN") and np.nan

Body:
I used to believe that in operator in Python checks the presence of element in some collection using equality checking ==, so element in some_list is roughly equivalent to any(x == element for x in some_list). For example:

True in [1, 2, 3]
# True because True == 1

or

1 in [1., 2., 3.]
# also True because 1 == 1.

However, it is well-known that NaN is not equal to itself. So I expected that float("NaN") in [float("NaN")] is False. And it is False indeed.

However, if we use numpy.nan instead of float("NaN"), the situation is quite different:

import numpy as np
np.nan in [np.nan, 1, 2]
# True

But np.nan == np.nan still gives False!

How is it possible? What's the difference between np.nan and float("NaN")? How does in deal with np.nan?


问:
Cannot unit test in Kotlin (ExecutionException, Aapt2Exception)
A simple test...

```<code>import org.junit.Test

class KotlinUnitTest {

    @Test
    fun test() {
        assert(true)
    }
}
</code>```

... results in the following...

```<code>Information:Gradle: Executing tasks: [:app:assembleDebug, :app:assembleDebugUnitTest]
Information:Kotlin: Kotlin JPS plugin is disabled
Information:Module "app" was fully rebuilt due to project configuration/dependencies changes
Information:06/12/2017 5:08 PM - Compilation completed with 3 errors and 0 warnings in 19s 962ms
Error:Gradle: java.util.concurrent.ExecutionException: java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
Error:Gradle: java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
Error:Gradle: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
</code>```

Adding android.enableAapt2=false to gradle.properties (or also gradle-wrapper.properties) made Android Studio halt indefinitely every time I ran the test.

This is weird because I'm able to...

Run my production app (filled with Kotlin files)

Unit test in Java

But, for whatever reason, I can't test in Kotlin

答:
I got same problem. for a simple test:

```<code>@RunWith(RobolectricTestRunner::class)
@Config(constants = BuildConfig::class)
class MainActivityTest {
    private lateinit var activityController: ActivityController<MainActivity>

    @Before
    @Throws(Exception::class)
    fun setUp() {
        activityController = Robolectric.buildActivity(MainActivity::class.java)

        activityController.create().start().resume()

    }

    @Test
    @Throws(Exception::class)
    fun testNotBeNull() {
        assertNotNull(activityController.get())
    }

}
</code>```

Update to latest Kotlin version to 1.1.60 and Gradle to 3.0.1 solve it.

Body:
A simple test...

import org.junit.Test

class KotlinUnitTest {

    @Test
    fun test() {
        assert(true)
    }
}

... results in the following...

Information:Gradle: Executing tasks: [:app:assembleDebug, :app:assembleDebugUnitTest]
Information:Kotlin: Kotlin JPS plugin is disabled
Information:Module "app" was fully rebuilt due to project configuration/dependencies changes
Information:06/12/2017 5:08 PM - Compilation completed with 3 errors and 0 warnings in 19s 962ms
Error:Gradle: java.util.concurrent.ExecutionException: java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
Error:Gradle: java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
Error:Gradle: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details

Adding android.enableAapt2=false to gradle.properties (or also gradle-wrapper.properties) made Android Studio halt indefinitely every time I ran the test.

This is weird because I'm able to...

Run my production app (filled with Kotlin files)

Unit test in Java

But, for whatever reason, I can't test in Kotlin

Body:
I got same problem. for a simple test:

@RunWith(RobolectricTestRunner::class)
@Config(constants = BuildConfig::class)
class MainActivityTest {
    private lateinit var activityController: ActivityController<MainActivity>

    @Before
    @Throws(Exception::class)
    fun setUp() {
        activityController = Robolectric.buildActivity(MainActivity::class.java)

        activityController.create().start().resume()

    }

    @Test
    @Throws(Exception::class)
    fun testNotBeNull() {
        assertNotNull(activityController.get())
    }

}

Update to latest Kotlin version to 1.1.60 and Gradle to 3.0.1 solve it.


问:
Map [Subjective Objective Assessment Plan] SOAP to HL7 - FHIR
Hello I am new to HL7 and FHIR , I am currently trying to find best resources to map SOAP [Subjective Objective Assessment Plan] documents into FHIR.

I have attached the example sample of SOAP document :

Key pieces are -> Patient Info, Clinic info, initial examination, goals, objective, assessment, Plan, Patient Problems , Procedures and Consent.

One of the idea is to use ClinicalImpression to do [Subjective, Objective, Assessment, Plan] but the maturity level is 0, are there more mature models that can be used instead? Or any examples on how it is solved at other places?

Also are there any mapping tools or other resources available that can be utilized for this issue?

Sample Document

Appreciate your help.

答:
Objective = Observations, Conditions, supported by FamilymemberHistory, Medication*, Immunization, DocumentReference etc.

Plan = CarePlan + a slew of supporting resources

Subjective/Assessment = ClinicalImpression. Yes, the maturity of this is 0. That represents two things:

the community has no heritage of interoperating with this kind of data

there's not much wide interest in doing that, compared to everything else.

I think (hope) this will come, after we've sorted out the other areas.


问:
JavaFX: save TextArea content to PDF?
I am trying to find a way to save the content of a TextArea to PDF. What do you suggest?</p>

答:
you need pdfbox-app-2.0.8.jar    from  https://pdfbox.apache.org/download.cgi#20x to run this code . it will crete a pdf with the areatext content in it .</p>

```<code> import java.io.IOException;
 import java.util.logging.Level;
 import java.util.logging.Logger;
 import javafx.application.Application;
 import javafx.event.ActionEvent;
 import javafx.event.EventHandler;
 import javafx.scene.Scene;
 import javafx.scene.control.Button;
 import javafx.scene.control.TextArea;
 import javafx.scene.layout.AnchorPane;
 import javafx.scene.layout.Pane;
 import javafx.scene.layout.StackPane;
 import javafx.stage.Stage;
 import org.apache.pdfbox.pdmodel.PDDocument;
 import org.apache.pdfbox.pdmodel.PDPage;
 import org.apache.pdfbox.pdmodel.PDPageContentStream;
 import org.apache.pdfbox.pdmodel.font.PDFont;
 import org.apache.pdfbox.pdmodel.font.PDType1Font;

 public class JavaFXApplication5 extends Application {

@Override
public void start(Stage primaryStage) {

    TextArea textarea = new TextArea();
    Pane pane = new AnchorPane(textarea);

    textarea.setPrefSize(100, 100);
    Button btn = new Button();
    btn.setText("To pdf");
    btn.setTranslateX(100);
    String text = textarea.getText();
    pane.getChildren().add(btn);

    btn.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent event) {
            System.out.println(text);

            PDFont font =  PDType1Font.HELVETICA_BOLD ;
             PDDocument doc    = new PDDocument();
             PDPage page = new PDPage();
             PDPageContentStream content;
            try {
                content = new PDPageContentStream(doc, page);
                content.beginText();
                content.moveTextPositionByAmount(300, 400);
                content.setFont(font, 40);
                content.drawString(textarea.getText());

               content.endText();
                content.close();
                doc.addPage(page);
                doc.save("example.pdf");
               } catch (IOException ex) {
                Logger.getLogger(JavaFXApplication5.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
    });

    StackPane root = new StackPane();
    root.getChildren().addAll(pane);

    Scene scene = new Scene(root, 300, 250);

    primaryStage.setTitle("Text to pdf example");
    primaryStage.setScene(scene);
    primaryStage.show();
}

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    launch(args);
}

}
</code>```

Title: JavaFX: save TextArea content to PDF?

Body:
you need pdfbox-app-2.0.8.jar    from  https://pdfbox.apache.org/download.cgi#20x to run this code . it will crete a pdf with the areatext content in it .

 import java.io.IOException;
 import java.util.logging.Level;
 import java.util.logging.Logger;
 import javafx.application.Application;
 import javafx.event.ActionEvent;
 import javafx.event.EventHandler;
 import javafx.scene.Scene;
 import javafx.scene.control.Button;
 import javafx.scene.control.TextArea;
 import javafx.scene.layout.AnchorPane;
 import javafx.scene.layout.Pane;
 import javafx.scene.layout.StackPane;
 import javafx.stage.Stage;
 import org.apache.pdfbox.pdmodel.PDDocument;
 import org.apache.pdfbox.pdmodel.PDPage;
 import org.apache.pdfbox.pdmodel.PDPageContentStream;
 import org.apache.pdfbox.pdmodel.font.PDFont;
 import org.apache.pdfbox.pdmodel.font.PDType1Font;

 public class JavaFXApplication5 extends Application {

@Override
public void start(Stage primaryStage) {

    TextArea textarea = new TextArea();
    Pane pane = new AnchorPane(textarea);

    textarea.setPrefSize(100, 100);
    Button btn = new Button();
    btn.setText("To pdf");
    btn.setTranslateX(100);
    String text = textarea.getText();
    pane.getChildren().add(btn);

    btn.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent event) {
            System.out.println(text);

            PDFont font =  PDType1Font.HELVETICA_BOLD ;
             PDDocument doc    = new PDDocument();
             PDPage page = new PDPage();
             PDPageContentStream content;
            try {
                content = new PDPageContentStream(doc, page);
                content.beginText();
                content.moveTextPositionByAmount(300, 400);
                content.setFont(font, 40);
                content.drawString(textarea.getText());

               content.endText();
                content.close();
                doc.addPage(page);
                doc.save("example.pdf");
               } catch (IOException ex) {
                Logger.getLogger(JavaFXApplication5.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
    });

    StackPane root = new StackPane();
    root.getChildren().addAll(pane);

    Scene scene = new Scene(root, 300, 250);

    primaryStage.setTitle("Text to pdf example");
    primaryStage.setScene(scene);
    primaryStage.show();
}

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    launch(args);
}

}


问:
Create an Spring Boot Executable jar AND a regular library jar
I have a regular Java project that creates a jar file that is a library of stuff that is used in a webapp. It's a Spring Boot starter that creates a jar.  Simple stuff.

I wanted to be able to run this as a stand alone executable jar file.  So I write a standard Application.java that implements CommandLineRunner and I add this to my plugins:

```<code><plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</code>```

and presto,  my jar is executable.

However,  that plugin changes the directory structure such that it is no longer a regular library jar,  and my webapplication fails to find the classes in it.  When I remove the plugin entry in my pom,  the webapp works fine,  but the jar is no longer executable.

Is it possible to do both? And if so, how?

答:
It was possible prior to Spring Boot 1.4.1, but not since.  1.4.1 changed the directory structure in an executable jar.  for 1.4.1 and after, a jar can be executable or a library but not both.

If you really need the same jar to be both executable and a library, you'll need to revert to Spring Boot 1.4.0 or earlier.

Body:
I have a regular Java project that creates a jar file that is a library of stuff that is used in a webapp. It's a Spring Boot starter that creates a jar.  Simple stuff.

I wanted to be able to run this as a stand alone executable jar file.  So I write a standard Application.java that implements CommandLineRunner and I add this to my plugins:

<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
</plugin>

and presto,  my jar is executable.

However,  that plugin changes the directory structure such that it is no longer a regular library jar,  and my webapplication fails to find the classes in it.  When I remove the plugin entry in my pom,  the webapp works fine,  but the jar is no longer executable.

Is it possible to do both? And if so, how?


问:
Get WebVR working with Chrome on Samsung S8
I found many websites that suggests WebVR works on Chrome since version 56. I have Chrome v.62 working on a Samsung S8 (I even tried Chrome Canary which v65) and when I execute the simple sample code like this is one for instance:

https://github.com/mdn/webvr-tests/blob/master/basic-display-info/index.html

```<code><!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width">

    <title>VRStageParameters basic test</title>

  </head>

  <body>
    <h1>VRStageParameters basic test</h1>

    <p id='toto'></p>
  </body>
  <script>
    var info = document.getElementById('toto');
    var vrDisplay;
    if(navigator.getVRDisplays) {
        reportStageParams();
    } else {
      info.innerHTML = 'WebVR API not supported by this browser.'
    }
    function reportStageParams() {
      info.innerHTML = 'IS WORKING SOMEHOW'
      navigator.getVRDisplays().then(function(displays) {
        vrDisplay = displays[0];
        var stageParams = vrDisplay.stageParameters;
        // stageParams is a VRStageParameters object
        if(stageParams === null) {
          info.textContent = 'Your VR Hardware does not support room-scale experiences.'
        } else {
          info.innerHTML = '<strong>Display stage parameters</strong>'
                       + '<br>Sitting to standing transform: ' + stageParams.sittingToStandingTransform
                       + '<br>Play area width (m): ' + stageParams.sizeX
                       + '<br>Play area depth (m): ' + stageParams.sizeY
        }
      });
    }
  </script>
</html>
</code>```

I keep getting the message WebVR API not supported by this browser.?? I don't understand why. Can someone with experience setting up WebVR please tell me what I need to do in order to make it work? I use a recent phone, the latest version of the browser, so it almost seems like I need to activate WebVR somewhere in some settings but can't find anything on the web.

答:
In fact this question was asked and already answers (to some extent):

How to enable WebVR on Google Chrome?

Strangely, this is really the first step in getting WebVR working and it's not explained in most tutorials and official websites on WebVR... so here is:

You need to go to chrome://flags

and then scroll down until you find WebVR specific features and enable the ones you want.

Body:
I found many websites that suggests WebVR works on Chrome since version 56. I have Chrome v.62 working on a Samsung S8 (I even tried Chrome Canary which v65) and when I execute the simple sample code like this is one for instance:

https://github.com/mdn/webvr-tests/blob/master/basic-display-info/index.html

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width">

    <title>VRStageParameters basic test</title>

VRStageParameters basic test

I keep getting the message WebVR API not supported by this browser.?? I don't understand why. Can someone with experience setting up WebVR please tell me what I need to do in order to make it work? I use a recent phone, the latest version of the browser, so it almost seems like I need to activate WebVR somewhere in some settings but can't find anything on the web.


问:
CMake add -ldl at end of link stage of add_library
I wrote/maintain a small unit test library on github https://github.com/acgreek/ExtremeCUnit built using cmake. You can checkout and run some  tests via 'cmake test' after checking out. It was working great on Cygwin and Ubuntu (my only home systems). I recent upgrade to ubuntu 13.10 and the library stopped linking with the test binary because the ExtremeUnitC library now needs to be linked with -ldl at the link stage (via add_library) and additionally the -ldl needs to be add to the end of the link line (some change to gcc it seems). In prior version of Ubuntu, the add_library target didn't need the -ldl  until the test object  was linked with the ExtremeUnitC library

Basically what I need is for the results of make VERBOSE=10, when it get to the following stage

```<code>Linking C shared library libExtremeCUnit.so
/usr/bin/cmake -E cmake_link_script CMakeFiles/ExtremeCUnit.dir/link.txt --verbose=10
/usr/bin/gcc  -fPIC -Wall -Wextra -ggdb3 -fPIC  -ldl   -shared -Wl,-    soname,libExtremeCUnit.so -o libExtremeCUnit.so CMakeFiles/ExtremeCUnit.dir/main.c.o CMakeFiles/ExtremeCUnit.dir/runner.c.o CMakeFiles/ExtremeCUnit.dir/util.c.o CMakeFiles/ExtremeCUnit.dir/findtest_names.c.o CMakeFiles/ExtremeCUnit.dir/assert_support.c.o
</code>```

I need it to be,

```<code>Linking C shared library libExtremeCUnit.so
/usr/bin/cmake -E cmake_link_script CMakeFiles/ExtremeCUnit.dir/link.txt --verbose=10
/usr/bin/gcc  -fPIC -Wall -Wextra -ggdb3 -fPIC  -ldl   -shared -Wl,-    soname,libExtremeCUnit.so -o libExtremeCUnit.so CMakeFiles/ExtremeCUnit.dir/main.c.o CMakeFiles/ExtremeCUnit.dir/runner.c.o CMakeFiles/ExtremeCUnit.dir/util.c.o CMakeFiles/ExtremeCUnit.dir/findtest_names.c.o CMakeFiles/ExtremeCUnit.dir/assert_support.c.o -ldl
</code>```

how should I edit my CMakeList.txt to that in a clean/portable way?

You can also send me a pull request so you can get the credit of fixing it.

答:
```<code>if(CMAKE_DL_LIBS)
    target_link_libraries(ExtremeCUnit ${CMAKE_DL_LIBS})
endif()
</code>```

Body:
I wrote/maintain a small unit test library on github https://github.com/acgreek/ExtremeCUnit built using cmake. You can checkout and run some  tests via 'cmake test' after checking out. It was working great on Cygwin and Ubuntu (my only home systems). I recent upgrade to ubuntu 13.10 and the library stopped linking with the test binary because the ExtremeUnitC library now needs to be linked with -ldl at the link stage (via add_library) and additionally the -ldl needs to be add to the end of the link line (some change to gcc it seems). In prior version of Ubuntu, the add_library target didn't need the -ldl  until the test object  was linked with the ExtremeUnitC library

Basically what I need is for the results of make VERBOSE=10, when it get to the following stage

Linking C shared library libExtremeCUnit.so
/usr/bin/cmake -E cmake_link_script CMakeFiles/ExtremeCUnit.dir/link.txt --verbose=10
/usr/bin/gcc  -fPIC -Wall -Wextra -ggdb3 -fPIC  -ldl   -shared -Wl,-    soname,libExtremeCUnit.so -o libExtremeCUnit.so CMakeFiles/ExtremeCUnit.dir/main.c.o CMakeFiles/ExtremeCUnit.dir/runner.c.o CMakeFiles/ExtremeCUnit.dir/util.c.o CMakeFiles/ExtremeCUnit.dir/findtest_names.c.o CMakeFiles/ExtremeCUnit.dir/assert_support.c.o

I need it to be,

Linking C shared library libExtremeCUnit.so
/usr/bin/cmake -E cmake_link_script CMakeFiles/ExtremeCUnit.dir/link.txt --verbose=10
/usr/bin/gcc  -fPIC -Wall -Wextra -ggdb3 -fPIC  -ldl   -shared -Wl,-    soname,libExtremeCUnit.so -o libExtremeCUnit.so CMakeFiles/ExtremeCUnit.dir/main.c.o CMakeFiles/ExtremeCUnit.dir/runner.c.o CMakeFiles/ExtremeCUnit.dir/util.c.o CMakeFiles/ExtremeCUnit.dir/findtest_names.c.o CMakeFiles/ExtremeCUnit.dir/assert_support.c.o -ldl

how should I edit my CMakeList.txt to that in a clean/portable way?

You can also send me a pull request so you can get the credit of fixing it.


问:
JavaScript functions help needed
I'm practicing JavaScript and have come up with a little project ... get the diameters of various bodies in our solar system when I click on corresponding buttons.

I've been able to do this, but not very efficiently. Currently, the only way my code works is with 11 functions. I also have two objects (one for the body names and the other for the body diameters).

Any feedback to make my code more efficient is very welcome. Thank you! :-)

//JavaScript

var bodyName = {
 su:"the Sun",
 me:"Mercury",
 ve:"Venus",
 ea:"Earth",
 mo:"the Moon",
 ma:"Mars",
 ju:"Jupiter",
 sa:"Saturn",
 ur:"Uranus",
 ne:"Neptune",
 pl:"Pluto"
 };

var bodyDiam = {
 su:864576,
 me:3032,
 ve:7521,
 ea:7918,
 mo:2159,
 ma:4212,
 ju:86881,
 sa:72367,
 ur:31518,
 ne:30599,
 pl:1475
};

function suInfo() {
 document.getElementById("bodyNameDisplay").innerHTML = bodyName.su;
 document.getElementById("bodyDiamDisplay").innerHTML = bodyDiam.su;
}

function meInfo() {
 document.getElementById("bodyNameDisplay").innerHTML = bodyName.me;
 document.getElementById("bodyDiamDisplay").innerHTML = bodyDiam.me;
}

function veInfo() {
 document.getElementById("bodyNameDisplay").innerHTML = bodyName.ve;
 document.getElementById("bodyDiamDisplay").innerHTML = bodyDiam.ve;
}

function eaInfo() {
 document.getElementById("bodyNameDisplay").innerHTML = bodyName.ea;
 document.getElementById("bodyDiamDisplay").innerHTML = bodyDiam.ea;
}

function moInfo() {
 document.getElementById("bodyNameDisplay").innerHTML = bodyName.mo;
 document.getElementById("bodyDiamDisplay").innerHTML = bodyDiam.mo;
}

function maInfo() {
 document.getElementById("bodyNameDisplay").innerHTML = bodyName.ma;
 document.getElementById("bodyDiamDisplay").innerHTML = bodyDiam.ma;
}

function juInfo() {
 document.getElementById("bodyNameDisplay").innerHTML = bodyName.ju;
 document.getElementById("bodyDiamDisplay").innerHTML = bodyDiam.ju;
}

function saInfo() {
 document.getElementById("bodyNameDisplay").innerHTML = bodyName.sa;
 document.getElementById("bodyDiamDisplay").innerHTML = bodyDiam.sa;
}

function urInfo() {
 document.getElementById("bodyNameDisplay").innerHTML = bodyName.ur;
 document.getElementById("bodyDiamDisplay").innerHTML = bodyDiam.ur;
}

function neInfo() {
 document.getElementById("bodyNameDisplay").innerHTML = bodyName.ne;
 document.getElementById("bodyDiamDisplay").innerHTML = bodyDiam.ne;
}

function plInfo() {
 document.getElementById("bodyNameDisplay").innerHTML = bodyName.pl;
 document.getElementById("bodyDiamDisplay").innerHTML = bodyDiam.pl;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code><!--CSS-->

p {
  font-family: arial, sans-serif;
  font-size: 1em;
}

.button {
  font-size: 1em;
  font-weight: bold;
  color: #fff;
  border: none;
  border-radius: 0;
  padding: 0.5em;
  margin: 0 0.25em 0.5em 0;
  background-color: #393;
}

.result {
  font-weight: bold;
  color: #e80;
}</code>```

<button type="button" class="button" id="suButton" onclick="suInfo()">Sun</button>
<button type="button" class="button" id="meButton" onclick="meInfo()">Mercury</button>
<button type="button" class="button" id="veButton" onclick="veInfo()">Venus</button>
<button type="button" class="button" id="eaButton" onclick="eaInfo()">Earth</button>
<button type="button" class="button" id="moButton" onclick="moInfo()">Moon</button>
<button type="button" class="button" id="maButton" onclick="maInfo()">Mars</button>
<button type="button" class="button" id="juButton" onclick="juInfo()">Jupiter</button>
<button type="button" class="button" id="saButton" onclick="saInfo()">Saturn</button>
<button type="button" class="button" id="urButton" onclick="urInfo()">Uranus</button>
<button type="button" class="button" id="neButton" onclick="neInfo()">Neptune</button>
<button type="button" class="button" id="plButton" onclick="plInfo()">Pluto</button>

The diameter of this body is this many miles.
 ```

答:
Convert the two sets of details into one array of objects that contain the details for that body.This way you can access all the information in a single function and simply pass a variable to the function that will access the index of the object within the array and return the name and diameter from a single object.

//JavaScript

var bodies = [
  {name:"the Sun", "diameter": 864576},
  {name:"Mercury", diameter: 3032},
  {name:"Venus", diameter: 7521},
  {name:"Earth", diameter: 7918},
  {name:"the Moon", diameter: 2159},
  {name:"Mars", diameter: 4212},
  {name:"Jupiter", diameter: 86881},
  {name:"Saturn", diameter: 72367},
  {name:"Uranus", diameter: 31518},
  {name:"Neptune", diameter: 30599},
  {name:"Pluto", diameter: 1475},
];

function setInfo(index) {
 document.getElementById("bodyNameDisplay").innerHTML = bodies[index].name;
 document.getElementById("bodyDiamDisplay").innerHTML = bodies[index].diameter;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code><!--CSS-->

p {
  font-family: arial, sans-serif;
  font-size: 1em;
}

.button {
  font-size: 1em;
  font-weight: bold;
  color: #fff;
  border: none;
  border-radius: 0;
  padding: 0.5em;
  margin: 0 0.25em 0.5em 0;
  background-color: #393;
  cursor: pointer;
}

.result {
  font-weight: bold;
  color: #e80;
}</code>```

<button type="button" class="button" onclick="setInfo(0)">Sun</button>
<button type="button" class="button" onclick="setInfo(1)">Mercury</button>
<button type="button" class="button" onclick="setInfo(2)">Venus</button>
<button type="button" class="button" onclick="setInfo(3)">Earth</button>
<button type="button" class="button" onclick="setInfo(4)">Moon</button>
<button type="button" class="button" onclick="setInfo(5)">Mars</button>
<button type="button" class="button" onclick="setInfo(6)">Jupiter</button>
<button type="button" class="button" onclick="setInfo(7)">Saturn</button>
<button type="button" class="button" onclick="setInfo(8)">Uranus</button>
<button type="button" class="button" onclick="setInfo(9)">Neptune</button>
<button type="button" class="button" onclick="setInfo(10)">Pluto</button>

The diameter of this body is this many miles.
```

Title: JavaScript functions help needed

Body:
I'm practicing JavaScript and have come up with a little project ... get the diameters of various bodies in our solar system when I click on corresponding buttons.

I've been able to do this, but not very efficiently. Currently, the only way my code works is with 11 functions. I also have two objects (one for the body names and the other for the body diameters).

Any feedback to make my code more efficient is very welcome. Thank you! :-)

//JavaScript

var bodyName = {
 su:"the Sun",
 me:"Mercury",
 ve:"Venus",
 ea:"Earth",
 mo:"the Moon",
 ma:"Mars",
 ju:"Jupiter",
 sa:"Saturn",
 ur:"Uranus",
 ne:"Neptune",
 pl:"Pluto"
 };

var bodyDiam = {
 su:864576,
 me:3032,
 ve:7521,
 ea:7918,
 mo:2159,
 ma:4212,
 ju:86881,
 sa:72367,
 ur:31518,
 ne:30599,
 pl:1475
};

function suInfo() {
 document.getElementById("bodyNameDisplay").innerHTML = bodyName.su;
 document.getElementById("bodyDiamDisplay").innerHTML = bodyDiam.su;
}

function meInfo() {
 document.getElementById("bodyNameDisplay").innerHTML = bodyName.me;
 document.getElementById("bodyDiamDisplay").innerHTML = bodyDiam.me;
}

function veInfo() {
 document.getElementById("bodyNameDisplay").innerHTML = bodyName.ve;
 document.getElementById("bodyDiamDisplay").innerHTML = bodyDiam.ve;
}

function eaInfo() {
 document.getElementById("bodyNameDisplay").innerHTML = bodyName.ea;
 document.getElementById("bodyDiamDisplay").innerHTML = bodyDiam.ea;
}

function moInfo() {
 document.getElementById("bodyNameDisplay").innerHTML = bodyName.mo;
 document.getElementById("bodyDiamDisplay").innerHTML = bodyDiam.mo;
}

function maInfo() {
 document.getElementById("bodyNameDisplay").innerHTML = bodyName.ma;
 document.getElementById("bodyDiamDisplay").innerHTML = bodyDiam.ma;
}

function juInfo() {
 document.getElementById("bodyNameDisplay").innerHTML = bodyName.ju;
 document.getElementById("bodyDiamDisplay").innerHTML = bodyDiam.ju;
}

function saInfo() {
 document.getElementById("bodyNameDisplay").innerHTML = bodyName.sa;
 document.getElementById("bodyDiamDisplay").innerHTML = bodyDiam.sa;
}

function urInfo() {
 document.getElementById("bodyNameDisplay").innerHTML = bodyName.ur;
 document.getElementById("bodyDiamDisplay").innerHTML = bodyDiam.ur;
}

function neInfo() {
 document.getElementById("bodyNameDisplay").innerHTML = bodyName.ne;
 document.getElementById("bodyDiamDisplay").innerHTML = bodyDiam.ne;
}

function plInfo() {
 document.getElementById("bodyNameDisplay").innerHTML = bodyName.pl;
 document.getElementById("bodyDiamDisplay").innerHTML = bodyDiam.pl;
}

p {
  font-family: arial, sans-serif;
  font-size: 1em;
}

.button {
  font-size: 1em;
  font-weight: bold;
  color: #fff;
  border: none;
  border-radius: 0;
  padding: 0.5em;
  margin: 0 0.25em 0.5em 0;
  background-color: #393;
}

.result {
  font-weight: bold;
  color: #e80;
}

<button type="button" class="button" id="suButton" onclick="suInfo()">Sun</button>
<button type="button" class="button" id="meButton" onclick="meInfo()">Mercury</button>
<button type="button" class="button" id="veButton" onclick="veInfo()">Venus</button>
<button type="button" class="button" id="eaButton" onclick="eaInfo()">Earth</button>
<button type="button" class="button" id="moButton" onclick="moInfo()">Moon</button>
<button type="button" class="button" id="maButton" onclick="maInfo()">Mars</button>
<button type="button" class="button" id="juButton" onclick="juInfo()">Jupiter</button>
<button type="button" class="button" id="saButton" onclick="saInfo()">Saturn</button>
<button type="button" class="button" id="urButton" onclick="urInfo()">Uranus</button>
<button type="button" class="button" id="neButton" onclick="neInfo()">Neptune</button>
<button type="button" class="button" id="plButton" onclick="plInfo()">Pluto</button>

The diameter of this body is this many miles.

Body:
Convert the two sets of details into one array of objects that contain the details for that body.This way you can access all the information in a single function and simply pass a variable to the function that will access the index of the object within the array and return the name and diameter from a single object.

//JavaScript

var bodies = [
  {name:"the Sun", "diameter": 864576},
  {name:"Mercury", diameter: 3032},
  {name:"Venus", diameter: 7521},
  {name:"Earth", diameter: 7918},
  {name:"the Moon", diameter: 2159},
  {name:"Mars", diameter: 4212},
  {name:"Jupiter", diameter: 86881},
  {name:"Saturn", diameter: 72367},
  {name:"Uranus", diameter: 31518},
  {name:"Neptune", diameter: 30599},
  {name:"Pluto", diameter: 1475},
];

function setInfo(index) {
 document.getElementById("bodyNameDisplay").innerHTML = bodies[index].name;
 document.getElementById("bodyDiamDisplay").innerHTML = bodies[index].diameter;
}

<!--CSS-->

p {
  font-family: arial, sans-serif;
  font-size: 1em;
}

.button {
  font-size: 1em;
  font-weight: bold;
  color: #fff;
  border: none;
  border-radius: 0;
  padding: 0.5em;
  margin: 0 0.25em 0.5em 0;
  background-color: #393;
  cursor: pointer;
}

.result {
  font-weight: bold;
  color: #e80;
}

<!--html-->

<!--buttons-->

<button type="button" class="button" onclick="setInfo(0)">Sun</button>
<button type="button" class="button" onclick="setInfo(1)">Mercury</button>
<button type="button" class="button" onclick="setInfo(2)">Venus</button>
<button type="button" class="button" onclick="setInfo(3)">Earth</button>
<button type="button" class="button" onclick="setInfo(4)">Moon</button>
<button type="button" class="button" onclick="setInfo(5)">Mars</button>
<button type="button" class="button" onclick="setInfo(6)">Jupiter</button>
<button type="button" class="button" onclick="setInfo(7)">Saturn</button>
<button type="button" class="button" onclick="setInfo(8)">Uranus</button>
<button type="button" class="button" onclick="setInfo(9)">Neptune</button>
<button type="button" class="button" onclick="setInfo(10)">Pluto</button>

<!--Information Display-->

<p>The diameter of <span class="result" id="bodyNameDisplay">this body</span> is <span class="result" id="bodyDiamDisplay">this many</span> miles.</p>


问:
Is using regex for a request handler in PHP bad?
I am working on a request handler to route every page call through my index page and have SEO friendly urls.

domain.com/account/settings

this would be easy to map to the correct page but some are more complex when there becomes an ID number or a page number in the uri.

So I see some people will use things like preg_match and cycle through an array of patterns ->  uri to get a match which is nice for when paging and id's come into play but from my experience, it seems like running preg_match on an array of say 20 items on every page load is not good for performace.

Please tell me your thought on this?

答:
A not-very-complex regex on a string as short as an URI will take very little time, even running 20 times through. If you have a) profiled or timed it to prove it's a performance problem, and b) a good alternative to use instead then you could try changing it around but otherwise I wouldn't worry to much about it. Tons of sites do something similar with mod_rewrite after all, checking the page URI against a series of regexes on every page load.

If need be, you could probably reduce that 20 times to less for each URI with a few simple strstr() checks to see what basic format the URI is in (whether it contains a id or not, a page number or not, etc). Optimizing your regexes, such as using the "start" ^ and "end" $ meta-characters wherever possible, will help too.


问:
How to query this with Laravel 5.5
I am working on a project. For now let's say I have 3 tables "districts", "crimes" and "cases". The cases table holds all the registered cases.

Case.php (EDIT : missing quote)

```<code>class Case extends Model
{
    protected $table = 'cases';
    protected $fillable = ['person_name','crime_id' ,'district_id','crime_date'];

    public function crime()
    {
        return $this->belongsTo('App\Crime');
    }

}
</code>```

District.php

```<code>class District extends Model
{
    protected $table = 'districts';
    protected $fillable = ['name']; // name of districts like "A district","B district" etc.

    public function cases()
    {
        return $this->hasMany('App\Case');
    }
}
</code>```

Crime.php

```<code>class Crime extends Model
{
    protected $table = 'crimes';
    protected $fillable = ['name']; // name of different types of crime like rape, murder etc.
}
</code>```

My output at the end of month should look like below in report.blade.php
for eg: Total crime in A district in Decemeber, Total crime of B district in December, Total crime of C district in December. Simillary for all districts in every month (jan-dec of every year)

```<code>  District name | total crime | crime
   A               3             rape
                                 murder
                                 attempt to murder

   B               1             rape

   C               0             No crime reported
</code>```

// ie: above is the data for december month of 2017 in every district

Controller: I need to modify this query to get above output because this give total crime and types of crime in each district but regardless of every month

```<code>public function index(){
    $districts =  District::with('cases.crime')->get();
    return $districts;
}
</code>```

on return I got this

```<code>[
{
id: 1,
name: "A",//name of district
created_at: "-0001-11-30 00:00:00",
updated_at: "-0001-11-30 00:00:00",
cases: [   //registered cases
    {
    id: 1,
    crime_id: 1,
    district_id: 1,
    crime_date: "2017-12-31 00:00:00",
    created_at: "-0001-11-30 00:00:00",
    updated_at: "-0001-11-30 00:00:00",
crime: {//name of crime from crimes table
id: 1,
name: "Rape",
created_at: "-0001-11-30 00:00:00",
updated_at: "-0001-11-30 00:00:00"
}
},
{
id: 3,
crime_id: 4,
district_id: 1,
crime_date: "2017-12-31 00:00:00",
created_at: "-0001-11-30 00:00:00",
updated_at: "-0001-11-30 00:00:00",
crime: {
id: 4,
name: "Women trafficking",
created_at: "-0001-11-30 00:00:00",
updated_at: "-0001-11-30 00:00:00"
}
},
{
id: 4,
crime_id: 3,
district_id: 1,
crime_date: "2017-12-31 00:00:00",
created_at: "-0001-11-30 00:00:00",
updated_at: "-0001-11-30 00:00:00",
crime: {
id: 3,
name: "Murder",
created_at: "-0001-11-30 00:00:00",
updated_at: "-0001-11-30 00:00:00"
}
}
]
},
{
id: 2,
name: "B",//name of district from districts table
created_at: "-0001-11-30 00:00:00",
updated_at: "-0001-11-30 00:00:00",
    cases: [
    {
    id: 2,
    crime_id: 1,
    district_id: 2,
    crime_date: "2017-12-31 00:00:00",
    created_at: "-0001-11-30 00:00:00",
    updated_at:  "-0001-11-30 00:00:00",
    crime: {
    id: 1,
    name: "Rape",
    created_at: "-0001-11-30 00:00:00",
    updated_at: "-0001-11-30 00:00:00"
}
}
]
}
]
</code>```

答:
This may help you :

```<code>$districts = District::with(['cases' => function ($query) use($startDate, $endDate) {
    $query->whereBetween('crime_date', [$startDate, $endDate]);
}, 'cases.crime'])->get();
</code>```

construct $startDate and $endDate from your Month and year.

for more info have a look at this : https://laravel.com/docs/5.5/eloquent-relationships#eager-loading
(Constraining Eager Loads section)

Title: How to query this with Laravel 5.5

Body:
I am working on a project. For now let's say I have 3 tables "districts", "crimes" and "cases". The cases table holds all the registered cases.

Case.php (EDIT : missing quote)

class Case extends Model
{
    protected $table = 'cases';
    protected $fillable = ['person_name','crime_id' ,'district_id','crime_date'];

    public function crime()
    {
        return $this->belongsTo('App\Crime');
    }

}

District.php

class District extends Model
{
    protected $table = 'districts';
    protected $fillable = ['name']; // name of districts like "A district","B district" etc.

    public function cases()
    {
        return $this->hasMany('App\Case');
    }
}

Crime.php

class Crime extends Model
{
    protected $table = 'crimes';
    protected $fillable = ['name']; // name of different types of crime like rape, murder etc.
}

My output at the end of month should look like below in report.blade.php
for eg: Total crime in A district in Decemeber, Total crime of B district in December, Total crime of C district in December. Simillary for all districts in every month (jan-dec of every year)

  District name | total crime | crime
   A               3             rape
                                 murder
                                 attempt to murder

   B               1             rape

   C               0             No crime reported

// ie: above is the data for december month of 2017 in every district

Controller: I need to modify this query to get above output because this give total crime and types of crime in each district but regardless of every month

public function index(){
    $districts =  District::with('cases.crime')->get();
    return $districts;
}

on return I got this

[
{
id: 1,
name: "A",//name of district
created_at: "-0001-11-30 00:00:00",
updated_at: "-0001-11-30 00:00:00",
cases: [   //registered cases
    {
    id: 1,
    crime_id: 1,
    district_id: 1,
    crime_date: "2017-12-31 00:00:00",
    created_at: "-0001-11-30 00:00:00",
    updated_at: "-0001-11-30 00:00:00",
crime: {//name of crime from crimes table
id: 1,
name: "Rape",
created_at: "-0001-11-30 00:00:00",
updated_at: "-0001-11-30 00:00:00"
}
},
{
id: 3,
crime_id: 4,
district_id: 1,
crime_date: "2017-12-31 00:00:00",
created_at: "-0001-11-30 00:00:00",
updated_at: "-0001-11-30 00:00:00",
crime: {
id: 4,
name: "Women trafficking",
created_at: "-0001-11-30 00:00:00",
updated_at: "-0001-11-30 00:00:00"
}
},
{
id: 4,
crime_id: 3,
district_id: 1,
crime_date: "2017-12-31 00:00:00",
created_at: "-0001-11-30 00:00:00",
updated_at: "-0001-11-30 00:00:00",
crime: {
id: 3,
name: "Murder",
created_at: "-0001-11-30 00:00:00",
updated_at: "-0001-11-30 00:00:00"
}
}
]
},
{
id: 2,
name: "B",//name of district from districts table
created_at: "-0001-11-30 00:00:00",
updated_at: "-0001-11-30 00:00:00",
    cases: [
    {
    id: 2,
    crime_id: 1,
    district_id: 2,
    crime_date: "2017-12-31 00:00:00",
    created_at: "-0001-11-30 00:00:00",
    updated_at:  "-0001-11-30 00:00:00",
    crime: {
    id: 1,
    name: "Rape",
    created_at: "-0001-11-30 00:00:00",
    updated_at: "-0001-11-30 00:00:00"
}
}
]
}
]

Body:
This may help you :

$districts = District::with(['cases' => function ($query) use($startDate, $endDate) {
    $query->whereBetween('crime_date', [$startDate, $endDate]);
}, 'cases.crime'])->get();

construct $startDate and $endDate from your Month and year.

for more info have a look at this : https://laravel.com/docs/5.5/eloquent-relationships#eager-loading
(Constraining Eager Loads section)


答:
The first uses recursion, it keeps calling max with the trailing portion of the array until it is down to just one element, it then compares the first element of each preceding portion to the maximum element found so far.

Imagine you have the array {1, 2, 5, 4, 10, -1 };

The first max() starts by calling itself again with the array now pointing at the second element and len of 5, this continues until len is 1 and the array holds -1. It returns -1 and then compares that 10with 1 that call returns the 10 and so on until the outermost call returns 10.

Title: How do both these pieces of code have the same output, provided len>0

Body:
I understand the second piece of code, but not the first one.

First code:

int max(int a[], int len)
{
 if (len == 1)
  return a[0];
 int m = max(a+1, len-1);
 if (a[0] > m)
  return a[0];
 return m;
}

Second code:

int max(int a[], int len) {
 int m = a[0];
 for (int i = 0; i < len; ++i)
  if (a[i] > m)
   m = a[i];
 return m;
}

In the first piece of code, what value is m actually storing everytime the function max is called


问:
Context is read only
Helo masters, I have to create a JNDI Datasource dynamically, I tried to do it with a listener called SetupApplicationListener. Here is the beginning of WEB-LIB/web.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee">

    <display-name>pri-web</display-name>

    <!-- Listeners -->
    <listener>
        <listener-class>org.apache.myfaces.webapp.StartupServletContextListener</listener-class>
    </listener>
    <listener>
        <listener-class>myapp.SetupApplicationListener</listener-class>
    </listener>
</code>```

The code of the listener:

```<code>public class SetupApplicationListener implements ServletContextListener {

    public static Log LOG = null;

    public void contextInitialized(ServletContextEvent ctx){
        try {
            createOracleDataSource();
.....
        }
    }

    private void createOracleDataSource() throws SQLException, NamingException {
        OracleDataSource ds = new OracleDataSource();
        ds.setDriverType(...);
        ds.setServerName(...);
        ds.setPortNumber(...);
        ds.setDatabaseName(...);
        ds.setUser(...);
        ds.setPassword(...);

        new InitialContext().bind("java:comp/env/jdbc/myDS", ds);
    }

.....
}
</code>```

And there is the error:

```<code>[ERROR] 29/01/2013 09:44:50,517 (SetupApplicationListener.java:86) -> Error
javax.naming.NamingException: Context is read only
    at org.apache.naming.NamingContext.checkWritable(NamingContext.java:903)
    at org.apache.naming.NamingContext.bind(NamingContext.java:831)
    at org.apache.naming.NamingContext.bind(NamingContext.java:171)
    at org.apache.naming.NamingContext.bind(NamingContext.java:187)
    at org.apache.naming.SelectorContext.bind(SelectorContext.java:186)
    at javax.naming.InitialContext.bind(InitialContext.java:359)
    at myapp.SetupApplicationListener.createOracleDataSource(SetupApplicationListener.java:102)
</code>```

Can I set the read-only properties of the Context to "true"? Thanks! :)

```<code>Tomcat 6.0
Oracle 11g
jdk1.5
</code>```

EDIT: Don't need to be dynamically, i have to define a jndi datasource internally I can't modify the server files because it is a shared server. It must be jndi because other modules use it in that way, thanks.

答: I also had this problem, but being new to Tomee, I didn't know that there is a simple solution. When I deployed my web app to the webapps folder, the app worked fine, but when I deployed it to a service folder, I got the same abort. The problem was that the folder name did not match the war name (minus the .war). Once I fixed that, the app worked fine. Make sure the war name, folder name and service name are identical. This problem produces several different errors, including Context is read only and Error merging Java EE JNDI entries.</p>

Title: Context is read only

Body:
Helo masters, I have to create a JNDI Datasource dynamically, I tried to do it with a listener called SetupApplicationListener. Here is the beginning of WEB-LIB/web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee">

    <display-name>pri-web</display-name>

    <listener>
        <listener-class>org.apache.myfaces.webapp.StartupServletContextListener</listener-class>
    </listener>
    <listener>
        <listener-class>myapp.SetupApplicationListener</listener-class>
    </listener>

The code of the listener:

public class SetupApplicationListener implements ServletContextListener {

    public static Log LOG = null;

    public void contextInitialized(ServletContextEvent ctx){
        try {
            createOracleDataSource();
.....
        }
    }

    private void createOracleDataSource() throws SQLException, NamingException {
        OracleDataSource ds = new OracleDataSource();
        ds.setDriverType(...);
        ds.setServerName(...);
        ds.setPortNumber(...);
        ds.setDatabaseName(...);
        ds.setUser(...);
        ds.setPassword(...);

        new InitialContext().bind("java:comp/env/jdbc/myDS", ds);
    }

.....
}

And there is the error:

[ERROR] 29/01/2013 09:44:50,517 (SetupApplicationListener.java:86) -> Error
javax.naming.NamingException: Context is read only
    at org.apache.naming.NamingContext.checkWritable(NamingContext.java:903)
    at org.apache.naming.NamingContext.bind(NamingContext.java:831)
    at org.apache.naming.NamingContext.bind(NamingContext.java:171)
    at org.apache.naming.NamingContext.bind(NamingContext.java:187)
    at org.apache.naming.SelectorContext.bind(SelectorContext.java:186)
    at javax.naming.InitialContext.bind(InitialContext.java:359)
    at myapp.SetupApplicationListener.createOracleDataSource(SetupApplicationListener.java:102)

Can I set the read-only properties of the Context to "true"? Thanks! :)

Tomcat 6.0
Oracle 11g
jdk1.5

EDIT: Don't need to be dynamically, i have to define a jndi datasource internally I can't modify the server files because it is a shared server. It must be jndi because other modules use it in that way, thanks.


问:
ExtJs best practices
it seems that most ExtJS books and ExtJS introductions just focus on showing all the nice features but most of them don't really explain how to build stable, maintainable layouts / applications with ExtJS. And how to write them without creating an unreadable mess...

I've no specific application in mind, I'm just wondering how I can "beatify" my ExtJS code. So if you need an example, a "regular" application for item management (library) or something like a job board would best describe what I was thinking of.

So can anyone share some good links or advices on how to structure such applications when I want to build them with ExtJS for the client side code?

Thanks in advance,
Cheers

答:
In my company main code reviewer enforcing:

As component always talk to PAPA - never to you sibling (own children offcourse allowed)

Try to avoid bubblling

If you follow #1 you do not have need to use Ext.getCmp () it too expensive, so DO NOT

Consider each component reusable by someone else in your team

Use proper hierarchy in namespaces (and use namespaces)

As only a few main rules on top of follow documentation... :)

Title: ExtJs best practices


答:
To trim the definitions using a text editor to x decimal places you can simply use the Regular Expression Search Mode of Notepad++ :

Open Find and Replace With Ctrl+H

Change the search mode to Regular Expression

Put (\d+\.\d{x})\d* in the Find What ( Replace x by the number of digits that you want)

Put \1 in Replace With

Press Replace All

Result With your Example :

Before :

After :

You can download the latest version of Notepad++ here.

Title: Trim Decimal Places from Numbers in a Text Editor

Body:
I have a set of SVG definition exported from Inkspace and as anyone who has done this themselves will know the resulting definition often contains far more accuracy that is actually justified. For example for a 32 x32 icon definition shown below, Inkspace has generated 6 (or more!) decimal places of accuracy per pixel. Now I know that means it will scale but in my case I would rather save space in my app which requires input of hundreds of such icon definitions.

<svg width="32" height="32"><path d="M 14.576172 5.453125 L 13.78125 8.8222656 L 12.464844 9.3691406 L 9.5625 7.5898438 L 7.5898438 9.5351562 L 9.3691406 12.576172 L 8.8222656 13.78125 L 5.4785156 14.630859 L 5.4785156 17.369141 L 8.8496094 18.246094 L 9.3691406 19.507812 L 7.5625 22.464844 L 9.5351562 24.410156 L 12.548828 22.658203 L 13.808594 23.177734 L 14.603516 26.494141 L 17.396484 26.521484 L 18.191406 23.177734 L 19.505859 22.658203 L 22.410156 24.410156 L 24.355469 22.410156 L 22.658203 19.451172 L 23.150391 18.191406 L 26.492188 17.369141 L 26.492188 14.630859 L 23.123047 13.726562 L 22.630859 12.521484 L 24.410156 9.5351562 L 22.410156 7.5898438 L 19.451172 9.3417969 L 18.246094 8.8222656 L 17.396484 5.453125 L 14.576172 5.453125 z M 15.984375 12.082031 A 3.9078221 3.9078221 0 0 1 19.892578 15.988281 A 3.9078221 3.9078221 0 0 1 15.984375 19.896484 A 3.9078221 3.9078221 0 0 1 12.078125 15.988281 A 3.9078221 3.9078221 0 0 1 15.984375 12.082031 Z" fill="#f9f9f9" /></svg>

So my question is how can I trim the definitions using a text editor to say 2 decimal places.

I have found that by using TextWrangler with the following grep search and replace string

(\.[0-9][0-9])([0-9][0-9][0-9][0-9][0-9][0-9])
\1

that I can search for all 6 decimal places strings and replace them with 2 decimal places. Then I can change the search and replace to

(\.[0-9][0-9])([0-9][0-9][0-9][0-9][0-9])
\1

and then to

(\.[0-9][0-9])([0-9][0-9][0-9][0-9])
\1

and finally to

(\.[0-9][0-9])([0-9][0-9][0-9])
\1

and this works.

However if someone with slightly (or a lot) more brain pixels than me, could show me how to do all of the above with just one search and replace operation, I would be very happy.


问:
Error when installing postgis extension to postgresql database
Im having problem installing postgis to an existing database.
but getting error like this:

```<code>ERROR:  could not load library "/usr/local/pgsql/lib/postgis-2.0.so": libgeos_c.so.1: cannot open shared object file: No such file or directory
</code>```

the postgis-2.0.so is in /usr/local/pgsql/lib/postgis-2.0.so no problem. the libgeos_c.so.1 is installed in /usr/local/lib.

So, what is the problem here?

Any help would be appreciated.

Thanks.

BTW, I installed all these followed by this tutorial:

http://www.codingsteps.com/installing-and-configuring-postgresql-in-amazon-linux-ami/

update

```<code>$ ldd /usr/local/lib/libgeos_c.so.1
linux-vdso.so.1 =>  (0x00007fff6f55b000)
libgeos-3.3.7.so => /usr/local/lib/libgeos-3.3.7.so (0x00007f53700d9000)
libstdc++.so.6 => /usr/lib64/libstdc++.so.6 (0x00007f536fdd0000)
libm.so.6 => /lib64/libm.so.6 (0x00007f536fb4c000)
libc.so.6 => /lib64/libc.so.6 (0x00007f536f7c0000)
libgcc_s.so.1 => /lib64/libgcc_s.so.1 (0x00007f536f5ab000)
/lib64/ld-linux-x86-64.so.2 (0x00007f537068d000)
</code>```

答:
/etc/ld.so.conf.d/ should contain paths for postgresql libs dir and geos libs.

Example for postgresql 9.6.6 on Amazon linux:

-create postgresql-pgdg-libs.conf with "/usr/lib64/pgsql96/" path
-create libgeos.conf with "/usr/local/lib/" path
-check the geos library present in
 ldconfig -v | grep geos
- if yes compile the extension
sudo -u postgres -- psql -c "CREATE EXTENSION postgis;"
```

Body:
Im having problem installing postgis to an existing database.
but getting error like this:

ERROR:  could not load library "/usr/local/pgsql/lib/postgis-2.0.so": libgeos_c.so.1: cannot open shared object file: No such file or directory

the postgis-2.0.so is in /usr/local/pgsql/lib/postgis-2.0.so no problem. the libgeos_c.so.1 is installed in /usr/local/lib.

So, what is the problem here?

Any help would be appreciated.

Thanks.

BTW, I installed all these followed by this tutorial:

http://www.codingsteps.com/installing-and-configuring-postgresql-in-amazon-linux-ami/

update

$ ldd /usr/local/lib/libgeos_c.so.1
linux-vdso.so.1 =>  (0x00007fff6f55b000)
libgeos-3.3.7.so => /usr/local/lib/libgeos-3.3.7.so (0x00007f53700d9000)
libstdc++.so.6 => /usr/lib64/libstdc++.so.6 (0x00007f536fdd0000)
libm.so.6 => /lib64/libm.so.6 (0x00007f536fb4c000)
libc.so.6 => /lib64/libc.so.6 (0x00007f536f7c0000)
libgcc_s.so.1 => /lib64/libgcc_s.so.1 (0x00007f536f5ab000)
/lib64/ld-linux-x86-64.so.2 (0x00007f537068d000)

ContentLicense: CC BY-SA 4.0


问:
Do While with Multiple Conditions
Simple Question, I must just be missing something obvious.

I am trying to create a subroutine that polls for a window to be open and I am aiming to accomplish this by a loop that will run while two conditions are met. I keep getting an error:

Run time error 13: Type Mismatch

On the Do while loop, and after searching through the similar issues on SO I still am not quite sure what I am doing wrong.

Here is the line that keeps erroring out:

```<code>Sub FindHWND()
    Dim HWNDOut as string
    Dim Timer as Date
    Timer = Now()
    'This following line is the one erroring out.
    Do While ((Now() < Timer + TimeValue("00:00:10")) And (HWNDOut = 0))
        HWNDOut = CStr(Hex(FindWindowEx(0&, 0, "SunAwtFrame", "Graph.graphml - yEd")))
        Debug.Print HWNDOut
        Sleep (100)
    Loop
    'Other, following sub and code that is not relevant
End Sub
</code>```

Where Timer is the Now() at moment before the loop starts, and HWNDOut is the handle for the window I am looking for, which will be found in the loop.

All this loop does is look every 100 MS to see if the window to a third party program has opened, in order to prevent the loss of commands in the next subroutines.

Post Script: If anyone has any suggestions how to do this better, I'm all ears. This is my first time using UI Automation so I'm still learning.
Edit: Added more code to the block for context.

答:
With:

```<code>And (HWNDOut = 0))
</code>```

you are comparing a String to a numeric value..............this will fail.

Title: Do While with Multiple Conditions

Body:
Simple Question, I must just be missing something obvious.

I am trying to create a subroutine that polls for a window to be open and I am aiming to accomplish this by a loop that will run while two conditions are met. I keep getting an error:

Run time error 13: Type Mismatch

On the Do while loop, and after searching through the similar issues on SO I still am not quite sure what I am doing wrong.

Here is the line that keeps erroring out:

Sub FindHWND()
    Dim HWNDOut as string
    Dim Timer as Date
    Timer = Now()
    'This following line is the one erroring out.
    Do While ((Now() < Timer + TimeValue("00:00:10")) And (HWNDOut = 0))
        HWNDOut = CStr(Hex(FindWindowEx(0&, 0, "SunAwtFrame", "Graph.graphml - yEd")))
        Debug.Print HWNDOut
        Sleep (100)
    Loop
    'Other, following sub and code that is not relevant
End Sub

Where Timer is the Now() at moment before the loop starts, and HWNDOut is the handle for the window I am looking for, which will be found in the loop.

All this loop does is look every 100 MS to see if the window to a third party program has opened, in order to prevent the loss of commands in the next subroutines.

Post Script: If anyone has any suggestions how to do this better, I'm all ears. This is my first time using UI Automation so I'm still learning.
Edit: Added more code to the block for context.

Body:
With:

And (HWNDOut = 0))

you are comparing a String to a numeric value..............this will fail.


问:
MIPS division of signed integers
I'm wondering if anyone might know how to perform a division between two signed integers in MIPS, WITHOUT using the built in division operations.

In the problem specs, I'm told the divisor register, ALU, and quotient register are all 32 bits wide, and the remainder register is 64 bits.

答:
Think of how you'd perform a binary division by hand:

```<code># a/b, where a=2011 and b=18

            1101111 ←quotient
      ┌────────────         ↓
10010 │ 11111011011  a
       -10010↓↓↓↓↓↓  -64b × 1
       ───────↓↓↓↓↓
         11010↓↓↓↓↓
        -10010↓↓↓↓↓  -32b × 1
        ───────↓↓↓↓
          10001↓↓↓↓
         -00000↓↓↓↓  -16b × 0
         ───────↓↓↓
          100011↓↓↓
          -10010↓↓↓   -8b × 1
          ───────↓↓
           100010↓↓
           -10010↓↓   -4b × 1
           ───────↓
            100001↓
            -10010↓   -2b × 1
            ───────
              11111
             -10010   -1b × 1
             ──────
               1101  remainder
</code>```

This “grade school” long division algorithm can be written (in Python — I'll let you convert it to MIPS) as:

```<code>def unsigned_divide(dividend, divisor):
    if divisor == 0:
        raise ZeroDivisionError()
    if dividend < divisor:
        return 0
    # Determine the position of the first digit of the quotient
    shift_amt = dividend.bit_length() - divisor.bit_length()
    # Loop to find each bit of the quotient
    quotient = 0
    while shift_amt >= 0:
        # Calculate one bit of the quotient
        if dividend >= (divisor << shift_amt):
             # new bit is 1
             dividend -= (divisor << shift_amt)
             quotient |= (1 << shift_amt)
        # Move to the next digit
        shift_amt -= 1
    return quotient
</code>```

For signed division, you can just divide the absolute values while keeping track of the sign (assuming you want C-style truncating division):

```<code>def signed_divide(dividend, divisor):
    is_negative = (dividend < 0) ^ (divisor < 0)
    abs_quotient = unsigned_divide(abs(dividend), abs(divisor))
    return -abs_quotient if is_negative else abs_quotient
</code>```

Title: MIPS division of signed integers

Body:
Think of how you'd perform a binary division by hand:

# a/b, where a=2011 and b=18

            1101111 ←quotient
      ┌────────────         ↓
10010 │ 11111011011  a
       -10010↓↓↓↓↓↓  -64b × 1
       ───────↓↓↓↓↓
         11010↓↓↓↓↓
        -10010↓↓↓↓↓  -32b × 1
        ───────↓↓↓↓
          10001↓↓↓↓
         -00000↓↓↓↓  -16b × 0
         ───────↓↓↓
          100011↓↓↓
          -10010↓↓↓   -8b × 1
          ───────↓↓
           100010↓↓
           -10010↓↓   -4b × 1
           ───────↓
            100001↓
            -10010↓   -2b × 1
            ───────
              11111
             -10010   -1b × 1
             ──────
               1101  remainder

This “grade school” long division algorithm can be written (in Python — I'll let you convert it to MIPS) as:

def unsigned_divide(dividend, divisor):
    if divisor == 0:
        raise ZeroDivisionError()
    if dividend < divisor:
        return 0
    # Determine the position of the first digit of the quotient
    shift_amt = dividend.bit_length() - divisor.bit_length()
    # Loop to find each bit of the quotient
    quotient = 0
    while shift_amt >= 0:
        # Calculate one bit of the quotient
        if dividend >= (divisor << shift_amt):
             # new bit is 1
             dividend -= (divisor << shift_amt)
             quotient |= (1 << shift_amt)
        # Move to the next digit
        shift_amt -= 1
    return quotient

For signed division, you can just divide the absolute values while keeping track of the sign (assuming you want C-style truncating division):

def signed_divide(dividend, divisor):
    is_negative = (dividend < 0) ^ (divisor < 0)
    abs_quotient = unsigned_divide(abs(dividend), abs(divisor))
    return -abs_quotient if is_negative else abs_quotient