问:
How to fix NodeJS underutilizing CPU Cores?
According to this page Go vs Node.js, Node.js is not showing to be taking full advantage of CPU cores when running cpu-intensive code.

If I use virtualization and simply add more Node.js instances, will I achieve the same performance as Go? I suppose there still will be overheads and one won't be able to achieve the same performance.

答: You need to install Cluster module of nodejs in order to take full advantage of CPU cores when running cpu-intensive code. </p>


来源: stackexchange

问:
Nested static libraries in Visual Studio?
I have a static library for a Vector implementation in C.

I am now making a new library that is going to rely on the Vector in order to function property. This new library is called String. Both are static libraries created in Visual Studio with their own .c and .h files.

I do the following just like I would when referencing any other static library

Create new static library. Create .c and .h files in it.

project -> properties -> C/C++ -> Additional include directories and set as the folder that contains the .c and .h files for my Vector

File -> Add -> Existing Project and set the .vcxproj file of the Vector project.

In my solution explorer, I went under my String solution and right clicked References and then check-marked the Vector box that shows up.

At this point, my String is now correctly able to see Vector.

The problem

When I open a new project, repeat those same steps except with String as the target library, I get the following error:

```<code>Severity    Code    Description Project File    Line    Suppression State
Error   MSB8006 The Platform for project 'C-DataStructuresLib.vcxproj' is invalid.  Platform='HPD'. This error may also appear if some other project is trying to follow a project-to-project reference to this project, this project has been unloaded or is not included in the solution, and the referencing project does not build using the same or an equivalent Platform.    CStringLib  C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V140\Microsoft.Cpp.InvalidPlatform.Targets    21
</code>```

The line:

This error may also appear if some other project is trying to follow a project-to-project reference to this project, this project has been unloaded or is not included in the solution, and the referencing project does not build using the same or an equivalent Platform

Is correct because that's exactly what I'm trying to do. How can this be fixed?

答:
Are you trying to compile as 64-bit project?

Check in the property page the section: Linker -> Advanced -> Target Machine

ContentLicense: CC BY-SA 3.0

Body:
I have a static library for a Vector implementation in C.

I am now making a new library that is going to rely on the Vector in order to function property. This new library is called String. Both are static libraries created in Visual Studio with their own .c and .h files.

I do the following just like I would when referencing any other static library

Create new static library. Create .c and .h files in it.

project -> properties -> C/C++ -> Additional include directories and set as the folder that contains the .c and .h files for my Vector

File -> Add -> Existing Project and set the .vcxproj file of the Vector project.

In my solution explorer, I went under my String solution and right clicked References and then check-marked the Vector box that shows up.

At this point, my String is now correctly able to see Vector.

The problem

When I open a new project, repeat those same steps except with String as the target library, I get the following error:

Severity    Code    Description Project File    Line    Suppression State
Error   MSB8006 The Platform for project 'C-DataStructuresLib.vcxproj' is invalid.  Platform='HPD'. This error may also appear if some other project is trying to follow a project-to-project reference to this project, this project has been unloaded or is not included in the solution, and the referencing project does not build using the same or an equivalent Platform.    CStringLib  C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V140\Microsoft.Cpp.InvalidPlatform.Targets    21

The line:

This error may also appear if some other project is trying to follow a project-to-project reference to this project, this project has been unloaded or is not included in the solution, and the referencing project does not build using the same or an equivalent Platform

Is correct because that's exactly what I'm trying to do. How can this be fixed?


问:
Regular expression month validation with text-mask directive
I'm using text-mask angular2 directive with ionic2.I have a month JS regular expression like this /^(0[1-9]|1[0-2])$/.It is working fine.But now I need to apply this for above directive.I have tried like below.But it is not working.Can you tell me why?

```<code>   mask: Array<string | RegExp>;

   constructor(){
     this.mask = [/0[1-9]/, /1[0-2]/];//not working
     //this.mask = [/[1-9]/, /\d/]; //this is working
    }
</code>```

答:
Each element in the mask array restrict on what character a user can input. For example, mark =  [/[1-9]/, /\d/] means the user can enter only a number between 1 and 9 in the first placeholder, and only a digit in the placeholders after that.

In your case, each element of your mark (/0[1-9]/, /1[0-2]/) defined an valid pattern for entire input string, not for each character. That why it didn't work.

According to text-mask angular2 document, you can also pass a function as the mask. You should try something like this

```<code>this.mask = function(rawValue) {
        // add logic to generate your mask array
        if (rawValue && rawValue.length > 0) {
            if (rawValue[0] == '0') {
                return [/[01]/, /[1-9]/];
            } else {
                return [/[01]/, /[0-2]/];
            }
        }
        return [/[01]/, /[0-9]/];
   }
</code>```

Body:
I'm using text-mask angular2 directive with ionic2.I have a month JS regular expression like this /^(0[1-9]|1[0-2])$/.It is working fine.But now I need to apply this for above directive.I have tried like below.But it is not working.Can you tell me why?

   mask: Array<string | RegExp>;

   constructor(){
     this.mask = [/0[1-9]/, /1[0-2]/];//not working
     //this.mask = [/[1-9]/, /\d/]; //this is working
    }

Body:
Each element in the mask array restrict on what character a user can input. For example, mark =  [/[1-9]/, /\d/] means the user can enter only a number between 1 and 9 in the first placeholder, and only a digit in the placeholders after that.

In your case, each element of your mark (/0[1-9]/, /1[0-2]/) defined an valid pattern for entire input string, not for each character. That why it didn't work.

According to text-mask angular2 document, you can also pass a function as the mask. You should try something like this

this.mask = function(rawValue) {
        // add logic to generate your mask array
        if (rawValue && rawValue.length > 0) {
            if (rawValue[0] == '0') {
                return [/[01]/, /[1-9]/];
            } else {
                return [/[01]/, /[0-2]/];
            }
        }
        return [/[01]/, /[0-9]/];
   }


问:
How to pass bitset of any size to a function?
The following program compiles fine.

```<code>#include <iostream>
#include <bitset>

void foo(std::bitset<10> n)
{
    std::cout << n.size() << "\n";
}

int main()
{
    std::bitset<10> n;
    foo(n);
}
</code>```

```<code>$ g++ -std=c++11 -Wall -Wextra -pedantic foo.cpp
$ ./a.out
10
</code>```

How can I modify the foo() function such that it can accept bitset of any size?

答:
You also can use auto, much less code then template declaration

```<code>#include <iostream>
#include <bitset>

void foo(auto n)
{
    std::cout << n.size() << "\n";
}

int main()
{
    std::bitset<15> n;
    foo(n);
}
</code>```

Body:
The following program compiles fine.

#include <iostream>
#include <bitset>

void foo(std::bitset<10> n)
{
    std::cout << n.size() << "\n";
}

int main()
{
    std::bitset<10> n;
    foo(n);
}

$ g++ -std=c++11 -Wall -Wextra -pedantic foo.cpp
$ ./a.out
10

How can I modify the foo() function such that it can accept bitset of any size?

Body:
You also can use auto, much less code then template declaration

#include <iostream>
#include <bitset>

void foo(auto n)
{
    std::cout << n.size() << "\n";
}

int main()
{
    std::bitset<15> n;
    foo(n);
}


问:
How can I estimate the disk size of a string with JavaScript?
I need to try to estimate the DISK size of a text string (which could be raw text or a Base64 encoded string for an image/audio/etc) in JavaScript. I'm not sure how to estimate this. The only thing when Googling i can find is .length so i thought maybe someone on StackOverflow might know...

The reason i need to know is i have a localStorage script that needs (or would love to have) the ability to check when a user is nearing his 5MB (or 10MB in IE) quota and prompt them to increase the max size for the domain. So, if a user hits, lets say, 4.5MBs of data it'd prompt with

You're nearing your browsers 5MB data cap. Please increase your max data by... [instructions on increasing it for the browser]

答:
It is going to depend on your character encoding. If you use ASCII encoding, it's going to be str.length bytes. If you use UTF-16, it's going to be (str.length * 2) bytes. If you use UTF-8, it is going to depend on the characters in the string. (Some characters will only take 1 byte, but others could take up to 4 bytes.) If you're dealing with Base64-encoded data, the characters are all within the ASCII range and therefore would occupy str.length bytes on disk. If you decode them first and save as binary, it would take (str.length * 3/4) bytes. (With Base64, 3 uncoded bytes become 4 coded bytes.)

BTW - If you haven't read Joel Spolsky's The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!), you should do so immediately.

http://www.joelonsoftware.com/articles/Unicode.html

UPDATE: If you're using localStorage, I assume that you're familiar with window.localStorage.length, though this only tells you how much has been used, not whether your new data will fit. I would also highly recommend reading Dive into HTML5, especially the section on storage:

http://diveintohtml5.ep.io/storage.html

Unless something has changed since its writing, I'm not sure what you can do as localStorage limits you to 5MB per domain with no way for the user to increase it.

ContentLicense: CC BY-SA 2.5


问:
MS Access currentdb.excute has different result than Docmd.RunSQL
I use VBA to run an INSERT INTO ... SELECT... SQL query with Currentdb.Execute command. However, I have trouble with the result. There are some rows missing the data.

The result is correct when using Docmd.RunSQL with the same SQL, but I don't want the warning message for inserting data into the table.

I also tried using only the SELECT... with Currentdb.Execute and print the result on the debug window. The result is correct, no missing data.

Here's my code:

```<code>strsql = strsql & "INSERT INTO tempLineItems (OrderNo, PositionNo, PartNo, [Description], PlannedDeliveryDate, Qty, Unit, Price, Curr, txta, LineItemText, Discount, Tax) "
strsql = strsql & "SELECT dbo_ttdsls041600.t_orno, dbo_ttdsls041600.t_pono, dbo_ttdsls041600.t_item, IIF(dbo_ttipcs021600.t_dsca is null,dbo_ttiitm001600.t_dsca,dbo_ttipcs021600.t_dsca) AS t_dsca, dbo_ttdsls041600.t_ddta, dbo_ttdsls041600.t_oqua, dbo_ttdsls041600.t_cups, dbo_ttdsls041600.t_pric, dbo_ttdsls040600.t_ccur, dbo_ttdsls041600.t_txta, Null AS LineItemText, dbo_ttdsls041600.t_disc_1, dbo_ttdsls041600.t_cvat "
strsql = strsql & "FROM dbo_ttdsls040600 INNER JOIN ((dbo_ttipcs021600 RIGHT JOIN dbo_ttdsls041600 ON (dbo_ttipcs021600.t_item = dbo_ttdsls041600.t_item) AND (dbo_ttipcs021600.t_cprj = dbo_ttdsls041600.t_cprj)) LEFT JOIN dbo_ttiitm001600 ON dbo_ttdsls041600.t_item = dbo_ttiitm001600.t_item) ON dbo_ttdsls040600.t_orno = dbo_ttdsls041600.t_orno "
strsql = strsql & "WHERE (((dbo_ttdsls041600.t_orno)=" & Me.txtSalesOrderNo.Value & ") AND ((dbo_ttdsls041600.t_pono)>0)) "
strsql = strsql & "ORDER BY dbo_ttdsls041600.t_pono;"
</code>```

The problem is on the

```<code>IIF(dbo_ttipcs021600.t_dsca is null,dbo_ttiitm001600.t_dsca,dbo_ttipcs021600.t_dsca) AS t_dsca
</code>```

I used ISNULL() function, and it has the same result as using Is Null

3/28/2017 Update:
Those tables are linked tables from the SQL Server. I created local tables based on a subset data of those linked ones, and there's no missing data at all.

答:
Very odd. But I've never had to work much with SQLServer tables. To use RunSQL and not get warnings, turn them off and on.</p>

```<code>DoCmd.SetWarnings False
DoCmd.RunSQL ...
DoCmd.SetWarnings True
</code>```

Body:
I use VBA to run an INSERT INTO ... SELECT... SQL query with Currentdb.Execute command. However, I have trouble with the result. There are some rows missing the data.

The result is correct when using Docmd.RunSQL with the same SQL, but I don't want the warning message for inserting data into the table.

I also tried using only the SELECT... with Currentdb.Execute and print the result on the debug window. The result is correct, no missing data.

Here's my code:

strsql = strsql & "INSERT INTO tempLineItems (OrderNo, PositionNo, PartNo, [Description], PlannedDeliveryDate, Qty, Unit, Price, Curr, txta, LineItemText, Discount, Tax) "
strsql = strsql & "SELECT dbo_ttdsls041600.t_orno, dbo_ttdsls041600.t_pono, dbo_ttdsls041600.t_item, IIF(dbo_ttipcs021600.t_dsca is null,dbo_ttiitm001600.t_dsca,dbo_ttipcs021600.t_dsca) AS t_dsca, dbo_ttdsls041600.t_ddta, dbo_ttdsls041600.t_oqua, dbo_ttdsls041600.t_cups, dbo_ttdsls041600.t_pric, dbo_ttdsls040600.t_ccur, dbo_ttdsls041600.t_txta, Null AS LineItemText, dbo_ttdsls041600.t_disc_1, dbo_ttdsls041600.t_cvat "
strsql = strsql & "FROM dbo_ttdsls040600 INNER JOIN ((dbo_ttipcs021600 RIGHT JOIN dbo_ttdsls041600 ON (dbo_ttipcs021600.t_item = dbo_ttdsls041600.t_item) AND (dbo_ttipcs021600.t_cprj = dbo_ttdsls041600.t_cprj)) LEFT JOIN dbo_ttiitm001600 ON dbo_ttdsls041600.t_item = dbo_ttiitm001600.t_item) ON dbo_ttdsls040600.t_orno = dbo_ttdsls041600.t_orno "
strsql = strsql & "WHERE (((dbo_ttdsls041600.t_orno)=" & Me.txtSalesOrderNo.Value & ") AND ((dbo_ttdsls041600.t_pono)>0)) "
strsql = strsql & "ORDER BY dbo_ttdsls041600.t_pono;"

The problem is on the

IIF(dbo_ttipcs021600.t_dsca is null,dbo_ttiitm001600.t_dsca,dbo_ttipcs021600.t_dsca) AS t_dsca

I used ISNULL() function, and it has the same result as using Is Null

3/28/2017 Update:
Those tables are linked tables from the SQL Server. I created local tables based on a subset data of those linked ones, and there's no missing data at all.

Body:
Very odd. But I've never had to work much with SQLServer tables. To use RunSQL and not get warnings, turn them off and on.

DoCmd.SetWarnings False
DoCmd.RunSQL ...
DoCmd.SetWarnings True


问:
XAML Path - Draw a Circle without using Arcs
In a WPF application, I understand I can draw a Circle using the following Path Syntax:

```<code><Path
    Stretch="Fill"
    StrokeThickness="1"
    Data="M -1,0 A 1,1 0 1 1 1,0 M -1,0 A 1,1 0 1 0 1,0" />
</code>```

However, I am working in a compiler that does not yet support Arcs (C# & XAML for HTML5).

How would I draw this circle without using Arcs?
Is the solution to draw a point-by-point item - essentially a Hexagon, give or take?

答:
if you want to draw a circle you can draw Ellpise as @lokusking  mentioned in comments. You can make it like this.

```<code> <Ellipse Stroke="Black" StrokeThickness="1" Fill="Black"></Ellipse>
</code>```

If you want to draw somthing more complicated, please use canvas and draw figure line by line. Here is example for hexagon.

```<code><Viewbox Width="200" Height="200">
      <Canvas Width="400" Height="400">
         <Line
            Stroke="Black"
            StrokeThickness="2"
            X1="0"
            X2="200"
            Y1="100"
            Y2="0"/>
         <Line
            Stroke="Black"
            StrokeThickness="2"
            X1="200"
            X2="400"
            Y1="0"
            Y2="100"/>
         <Line
            Stroke="Black"
            StrokeThickness="2"
            X1="400"
            X2="400"
            Y1="100"
            Y2="300"/>
         <Line
            Stroke="Black"
            StrokeThickness="2"
            X1="400"
            X2="200"
            Y1="300"
            Y2="400"/>
         <Line
            Stroke="Black"
            StrokeThickness="2"
            X1="200"
            X2="0"
            Y1="400"
            Y2="300"/>
         <Line
            Stroke="Black"
            StrokeThickness="2"
            X1="0"
            X2="0"
            Y1="300"
            Y2="100"/>
      </Canvas>
   </Viewbox>
</code>```

Hope it helps.

Body:
In a WPF application, I understand I can draw a Circle using the following Path Syntax:

<Path
    Stretch="Fill"
    StrokeThickness="1"
    Data="M -1,0 A 1,1 0 1 1 1,0 M -1,0 A 1,1 0 1 0 1,0" />

However, I am working in a compiler that does not yet support Arcs (C# & XAML for HTML5).

How would I draw this circle without using Arcs?
Is the solution to draw a point-by-point item - essentially a Hexagon, give or take?

Body:
if you want to draw a circle you can draw Ellpise as @lokusking  mentioned in comments. You can make it like this.

 <Ellipse Stroke="Black" StrokeThickness="1" Fill="Black"></Ellipse>

If you want to draw somthing more complicated, please use canvas and draw figure line by line. Here is example for hexagon.

<Viewbox Width="200" Height="200">
      <Canvas Width="400" Height="400">
         <Line
            Stroke="Black"
            StrokeThickness="2"
            X1="0"
            X2="200"
            Y1="100"
            Y2="0"/>
         <Line
            Stroke="Black"
            StrokeThickness="2"
            X1="200"
            X2="400"
            Y1="0"
            Y2="100"/>
         <Line
            Stroke="Black"
            StrokeThickness="2"
            X1="400"
            X2="400"
            Y1="100"
            Y2="300"/>
         <Line
            Stroke="Black"
            StrokeThickness="2"
            X1="400"
            X2="200"
            Y1="300"
            Y2="400"/>
         <Line
            Stroke="Black"
            StrokeThickness="2"
            X1="200"
            X2="0"
            Y1="400"
            Y2="300"/>
         <Line
            Stroke="Black"
            StrokeThickness="2"
            X1="0"
            X2="0"
            Y1="300"
            Y2="100"/>
      </Canvas>
   </Viewbox>

Hope it helps.


问:
selenium.common.exceptions.WebDriverException: Message: unknown error: cannot focus element
I wanna scrape the site.

When I executed my code I got a problem.

Here is my code.

```<code>class good_auction(object):

    def __init__(self):
        self.driverPath = r"D:\python code\NaverBlogCralwer\NaverBlogCralwer\chromedriver.exe"
        self.driver = webdriver.Chrome(self.driverPath)

    def main_scrape(self):
        self.driver.get('http://www.goodauction.com/index.php')
        time.sleep(5)
        self.driver.find_element_by_name('client_id').send_keys("myid")
        self.driver.find_element_by_id("pwd_dummy").send_keys('mypassword')

if __name__ == '__main__':
    scraper = good_auction()
    scraper.main_scrape()
</code>```

and I got this error

```<code>Traceback (most recent call last):
  File "D:/python code/auction_crawl/auction_crawler.py", line 36, in <module>
    scraper.main_scrape()
  File "D:/python code/auction_crawl/auction_crawler.py", line 27, in main_scrape
self.driver.find_element_by_id("pwd_dummy").send_keys('k1150719!!!')
  File "C:\Users\Hyun Mo\Anaconda3\lib\site-packages\selenium\webdriver\remote\webelement.py", line 347, in send_keys
    self._execute(Command.SEND_KEYS_TO_ELEMENT, {'value': keys_to_typing(value)})
  File "C:\Users\Hyun Mo\Anaconda3\lib\site-packages\selenium\webdriver\remote\webelement.py", line 491, in _execute
    return self._parent.execute(command, params)
  File "C:\Users\Hyun Mo\Anaconda3\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 238, in execute
    self.error_handler.check_response(response)
  File "C:\Users\Hyun Mo\Anaconda3\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 193, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: unknown error: cannot focus element
  (Session info: chrome=56.0.2924.87)
  (Driver info: chromedriver=2.25.426923 (0390b88869384d6eb0d5d09729679f934aab9eed),platform=Windows NT 10.0.14393 x86_64)
</code>```

How can I fix it??
Will I change my driver?? or Will I search for execute_script?? But I don't know javascript

答:
I solve this problems.

```<code>password = self.driver.find_element_by_id("pwd_dummy")
actions = webdriver.ActionChains(self.driver)
actions.move_to_element(password)
actions.click()
actions.send_keys("mypassword")  # Replace with whichever keys you want.
actions.perform()
</code>```

I use above code instead of below code.

```<code>self.driver.find_element_by_id("pwd_dummy").clear()
self.driver.find_element_by_id("pwd_dummy").send_keys('mypassword')
</code>```

Body:
I wanna scrape the site.

When I executed my code I got a problem.

Here is my code.

class good_auction(object):

    def __init__(self):
        self.driverPath = r"D:\python code\NaverBlogCralwer\NaverBlogCralwer\chromedriver.exe"
        self.driver = webdriver.Chrome(self.driverPath)

    def main_scrape(self):
        self.driver.get('http://www.goodauction.com/index.php')
        time.sleep(5)
        self.driver.find_element_by_name('client_id').send_keys("myid")
        self.driver.find_element_by_id("pwd_dummy").send_keys('mypassword')

if __name__ == '__main__':
    scraper = good_auction()
    scraper.main_scrape()

and I got this error

Traceback (most recent call last):
  File "D:/python code/auction_crawl/auction_crawler.py", line 36, in <module>
    scraper.main_scrape()
  File "D:/python code/auction_crawl/auction_crawler.py", line 27, in main_scrape
self.driver.find_element_by_id("pwd_dummy").send_keys('k1150719!!!')
  File "C:\Users\Hyun Mo\Anaconda3\lib\site-packages\selenium\webdriver\remote\webelement.py", line 347, in send_keys
    self._execute(Command.SEND_KEYS_TO_ELEMENT, {'value': keys_to_typing(value)})
  File "C:\Users\Hyun Mo\Anaconda3\lib\site-packages\selenium\webdriver\remote\webelement.py", line 491, in _execute
    return self._parent.execute(command, params)
  File "C:\Users\Hyun Mo\Anaconda3\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 238, in execute
    self.error_handler.check_response(response)
  File "C:\Users\Hyun Mo\Anaconda3\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 193, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: unknown error: cannot focus element
  (Session info: chrome=56.0.2924.87)
  (Driver info: chromedriver=2.25.426923 (0390b88869384d6eb0d5d09729679f934aab9eed),platform=Windows NT 10.0.14393 x86_64)

How can I fix it??
Will I change my driver?? or Will I search for execute_script?? But I don't know javascript

Body:
I solve this problems.

password = self.driver.find_element_by_id("pwd_dummy")
actions = webdriver.ActionChains(self.driver)
actions.move_to_element(password)
actions.click()
actions.send_keys("mypassword")  # Replace with whichever keys you want.
actions.perform()

I use above code instead of below code.

self.driver.find_element_by_id("pwd_dummy").clear()
self.driver.find_element_by_id("pwd_dummy").send_keys('mypassword')


问:
Sending SMS, MMS messages from mobile device and getting that message to a Java application server
I've been tasked with a project where the customer would like to send SMS, MMS messages from a mobile device.  They would like to have a dedicated phone number to send these messages to.  We would like these messages get routed through a gateway so it can be processed in a Java Application Server and have the server generate a response that will make its way back to the users mobile device.  The server side of this will be done in Java.

I'm new to this and trying to understand the best approach.  Please let me know what services and APIs are available that will allow me to do this.  It seems like there are plenty of services available to get the message from the server to the phone, but I'm not clear on the mechanism for getting the message from the device routed to the Java application server.

Any suggestions are greatly appreciated.

Thanks in advance.

Seth

答:
There are some services which allow you to define a callback URL, so when their server receives an SMS, they forward the data to you via HTTP POST. Of course, there are several proprietary protocols, and SMPP (e.g. http://opensmpp.logica.com/), but that's a lot more complicated.

An example of such a service is http://www.textmagic.com/app/pages/en/products/bulk-sms-gateway-api


问:
VBA: Deny long response by using UNC Path and FileSystemObject
I try to get a directory which is in the network by using a UNC Path and the FileSystemObject, but if the network directory is not available the response takes so much time. I guess this is because of scanning the a lot of the network and or sends some more pings at this point.
So is there a method which I could use for check faster the exist of a network-directory before using the FSO?</p>

答:
I've added a file check (and an example of it being called from a subroutine), then a folder check.  Both are called in the same way, and both utilise the Dir function.  I added an error handler in the filecheck, it's worth adding this for the folder checker too:

```<code>Sub Main()
    if FileExists("O:\Filenamehere") = TRUE then
        'do stuff
    end if
End Sub

'For a file
Function FileExists(ByVal FullPath As String) As Boolean
    On Error GoTo Hand
    If Dir(FullPath) <> "" Then
        FileExists = True
    Else
        FileExists = False
    End If
    Exit Function
Hand:
    Select Case Err.Number
        Case 52
            FileExists = False
    End Select
End Function

'For a directory
Function DirectoryExists(ByVal FullPath As String) As Boolean
    If Dir(FullPath, vbDirectory) <> "" Then DirectoryExists = True Else DirectoryExists = False
End Function
</code>```

Body:
I've added a file check (and an example of it being called from a subroutine), then a folder check.  Both are called in the same way, and both utilise the Dir function.  I added an error handler in the filecheck, it's worth adding this for the folder checker too:

Sub Main()
    if FileExists("O:\Filenamehere") = TRUE then
        'do stuff
    end if
End Sub

'For a file
Function FileExists(ByVal FullPath As String) As Boolean
    On Error GoTo Hand
    If Dir(FullPath) <> "" Then
        FileExists = True
    Else
        FileExists = False
    End If
    Exit Function
Hand:
    Select Case Err.Number
        Case 52
            FileExists = False
    End Select
End Function

'For a directory
Function DirectoryExists(ByVal FullPath As String) As Boolean
    If Dir(FullPath, vbDirectory) <> "" Then DirectoryExists = True Else DirectoryExists = False
End Function


问:
Generating a new variable using the difference between 2 existing variable.
I have two variables named "systolic bp" and "diastolic bp", and I want to get "systolic bp - diastolic bp" for a new variable called "Pulse pressure", but the Stata said there's "too many variables specified". Is there any way to solve this??? </p>

<p>thanks in advance </p>

答:
Before opening your dataset try to increase the memory size:</p>

```<code>set mem 100m
set matsize 800
</code>```

Body:
I have two variables named "systolic bp" and "diastolic bp", and I want to get "systolic bp - diastolic bp" for a new variable called "Pulse pressure", but the Stata said there's "too many variables specified". Is there any way to solve this???

thanks in advance

Body:
Before opening your dataset try to increase the memory size:

set mem 100m
set matsize 800


问:
Start Activity from within ArrayAdapter
I have a custom adapter that extends ArrayAdapter. I want to go to MapActivity when the EMAIL is clicked. If I remove the intent part a toast appears with the correct position of the item clicked. However, if I add the startActivity function, the app crashes (no toast). I removed the irrelevant code such as getting distance and setters.getters. Any help or pointer would be appreciated!

ArrayAdapter code

```<code>import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.firebase.client.ChildEventListener;
import com.firebase.client.DataSnapshot;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.firebase.client.ValueEventListener;
import com.google.android.gms.maps.model.LatLng;
import com.google.firebase.auth.FirebaseAuth;

import java.util.ArrayList;
import java.util.List;

public class TrackAdapter extends ArrayAdapter{

    private Context c;
    //ArrayLists to save items

    public TrackAdapter(Context context, int resource)
    {
        super(context, resource);
        this.c = context;
    }

    public void add(/*items to be added*/)
    {
       //add to ArrayLists and super.add()
    }

    static class RowHolder
    {
        TextView EMAIL;
        TextView DISTANCE;
    }

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

    @Override
    public Object getItem(int position)
    {
        return this.email.get(position);
    }

    /*other setters and getters*/

    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        View row;
        row = convertView;
        RowHolder holder;

        final int currentPosition = position;

        if (convertView == null)
        {
            LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row = inflater.inflate(R.layout.track_item, parent, false);

            holder = new RowHolder();

            holder.EMAIL = (TextView) row.findViewById(R.id.track_item_text);
            holder.DISTANCE = (TextView) row.findViewById(R.id.track_item_distance);

            holder.EMAIL.setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View v)
                {
                    Toast.makeText(c, "item at position " + currentPosition, Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(c, MapActivity.class);
                    c.startActivity(intent);
                }
            });

            row.setTag(holder);
        }
        else
        {
            holder = (RowHolder) row.getTag();
        }

        String EM = (String) getItem(position);
        holder.EMAIL.setText(EM);

        //calculate and display distance

        return row;

    }
}
</code>```

I also tried replacing c with c.getApplicationContext() and v.getContext(), which also doesn't work.

EDIT- I ran the app on an emulator, and it goes to the MapActivity. However, when  ran on an android device connected by USB, the app crashes

EDIT2 - Here is the crash report

```<code>--------- beginning of crash
03-29 03:23:42.036 7768-7768/com.example.*******
E/AndroidRuntime: FATAL EXCEPTION: main

                                                                                android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
                                                                                at android.app.ContextImpl.startActivity(ContextImpl.java:672)
                                                                                at android.app.ContextImpl.startActivity(ContextImpl.java:659)
                                                                                at android.content.ContextWrapper.startActivity(ContextWrapper.java:331)
                                                                                at com.example.ankit.findyourfellow.TrackAdapter$1.onClick(TrackAdapter.java:127)
                                                                                at android.view.View.performClick(View.java:5204)
                                                                                at android.view.View$PerformClick.run(View.java:21153)
                                                                                at android.os.Handler.handleCallback(Handler.java:739)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
</code>```

答:
Even if it works I am not sure if intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); is desired solution!

Where did you instantiated ArrayAdapter? Can you just try to cast context to activity?

Intent intent = new Intent((Activity)c, MapActivity.class);

Also I wonder why new Intent(v.getContext(), MapActivity.class); doesn't work?

UPDATE:

I found what's the problem... you need to start activity from context other then applicationContext!

Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag

It seems that your Context c is actually aplication context...

So here is the working code to put in onClick

```<code>Intent intent = new Intent(c, MapActivity.class);
v.getContext().startActivity(intent);
</code>```

Title: Start Activity from within ArrayAdapter

Body:
I have a custom adapter that extends ArrayAdapter. I want to go to MapActivity when the EMAIL is clicked. If I remove the intent part a toast appears with the correct position of the item clicked. However, if I add the startActivity function, the app crashes (no toast). I removed the irrelevant code such as getting distance and setters.getters. Any help or pointer would be appreciated!

ArrayAdapter code

import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.firebase.client.ChildEventListener;
import com.firebase.client.DataSnapshot;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.firebase.client.ValueEventListener;
import com.google.android.gms.maps.model.LatLng;
import com.google.firebase.auth.FirebaseAuth;

import java.util.ArrayList;
import java.util.List;

public class TrackAdapter extends ArrayAdapter{

    private Context c;
    //ArrayLists to save items

    public TrackAdapter(Context context, int resource)
    {
        super(context, resource);
        this.c = context;
    }

    public void add(/*items to be added*/)
    {
       //add to ArrayLists and super.add()
    }

    static class RowHolder
    {
        TextView EMAIL;
        TextView DISTANCE;
    }

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

    @Override
    public Object getItem(int position)
    {
        return this.email.get(position);
    }

    /*other setters and getters*/

    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        View row;
        row = convertView;
        RowHolder holder;

        final int currentPosition = position;

        if (convertView == null)
        {
            LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row = inflater.inflate(R.layout.track_item, parent, false);

            holder = new RowHolder();

            holder.EMAIL = (TextView) row.findViewById(R.id.track_item_text);
            holder.DISTANCE = (TextView) row.findViewById(R.id.track_item_distance);

            holder.EMAIL.setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View v)
                {
                    Toast.makeText(c, "item at position " + currentPosition, Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(c, MapActivity.class);
                    c.startActivity(intent);
                }
            });

            row.setTag(holder);
        }
        else
        {
            holder = (RowHolder) row.getTag();
        }

        String EM = (String) getItem(position);
        holder.EMAIL.setText(EM);

        //calculate and display distance

        return row;

    }
}

I also tried replacing c with c.getApplicationContext() and v.getContext(), which also doesn't work.

EDIT- I ran the app on an emulator, and it goes to the MapActivity. However, when  ran on an android device connected by USB, the app crashes

EDIT2 - Here is the crash report

--------- beginning of crash
03-29 03:23:42.036 7768-7768/com.example.*******
E/AndroidRuntime: FATAL EXCEPTION: main

                                                                                android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
                                                                                at android.app.ContextImpl.startActivity(ContextImpl.java:672)
                                                                                at android.app.ContextImpl.startActivity(ContextImpl.java:659)
                                                                                at android.content.ContextWrapper.startActivity(ContextWrapper.java:331)
                                                                                at com.example.ankit.findyourfellow.TrackAdapter$1.onClick(TrackAdapter.java:127)
                                                                                at android.view.View.performClick(View.java:5204)
                                                                                at android.view.View$PerformClick.run(View.java:21153)
                                                                                at android.os.Handler.handleCallback(Handler.java:739)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Body:
Even if it works I am not sure if intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); is desired solution!

Where did you instantiated ArrayAdapter? Can you just try to cast context to activity?

Intent intent = new Intent((Activity)c, MapActivity.class);

Also I wonder why new Intent(v.getContext(), MapActivity.class); doesn't work?

UPDATE:

I found what's the problem... you need to start activity from context other then applicationContext!

Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag

It seems that your Context c is actually aplication context...

So here is the working code to put in onClick

Intent intent = new Intent(c, MapActivity.class);
v.getContext().startActivity(intent);


问:
sort array of objects by defined list of values
Ok, I am sure that this has already been answered somewhere and I apologise for posting such a fundamental question, but I can't seem to find the answer anywhere... I'm only just dipping my big toe into php for the first time and spend most of my time in Javascript, so be nice to me :-)

I have an array of objects that is of the structure:

```<code>[
  {
    title: 'one',
    type: 'cat'
  },
  {
    title: 'two',
    type: 'dog'
  },
  {
    title: 'three',
    type: 'snake'
  },
  {
    title: 'four',
    type: 'dog'
  }
]
</code>```

And I'd like to order them in the order ['dog', 'snake', 'cat] so I get:

```<code>[
  {
    title: 'two',
    type: 'dog'
  }
  {
    title: 'four',
    type: 'dog'
  },
  {
    title: 'three',
    type: 'snake'
  },
  {
    title: 'one',
    type: 'cat'
  }
]
</code>```

How do I do this?

答:
```<code>$order = array_flip(['dog', 'snake', 'cat']);

usort($data, function($a, $b) use($order) {
    $aType = $a->type;
    $bType = $b->type;

    if (!isset($order[$aType]) && !isset($order[$bType])) {
        return strcmp($aType, $bType);
    }
    $aOrder = $order[$aType] ?? 0;
    $bOrder = $order[$bType] ?? 0;

    return $aOrder - $bOrder;
});
</code>```

Edit: if you know for sure 'type' could only be one of the ['dog', 'snake', 'cat'] you could simplify it:

```<code>usort($data, function($a, $b) use($order) {
    return $order[$a->type] - $order[$b->type];
});
</code>```

Body:
Ok, I am sure that this has already been answered somewhere and I apologise for posting such a fundamental question, but I can't seem to find the answer anywhere... I'm only just dipping my big toe into php for the first time and spend most of my time in Javascript, so be nice to me :-)

I have an array of objects that is of the structure:

[
  {
    title: 'one',
    type: 'cat'
  },
  {
    title: 'two',
    type: 'dog'
  },
  {
    title: 'three',
    type: 'snake'
  },
  {
    title: 'four',
    type: 'dog'
  }
]

And I'd like to order them in the order ['dog', 'snake', 'cat] so I get:

[
  {
    title: 'two',
    type: 'dog'
  }
  {
    title: 'four',
    type: 'dog'
  },
  {
    title: 'three',
    type: 'snake'
  },
  {
    title: 'one',
    type: 'cat'
  }
]

How do I do this?

Body:
$order = array_flip(['dog', 'snake', 'cat']);

usort($data, function($a, $b) use($order) {
    $aType = $a->type;
    $bType = $b->type;

    if (!isset($order[$aType]) && !isset($order[$bType])) {
        return strcmp($aType, $bType);
    }
    $aOrder = $order[$aType] ?? 0;
    $bOrder = $order[$bType] ?? 0;

    return $aOrder - $bOrder;
});

Edit: if you know for sure 'type' could only be one of the ['dog', 'snake', 'cat'] you could simplify it:

usort($data, function($a, $b) use($order) {
    return $order[$a->type] - $order[$b->type];
});


问:
Convolve2d just by using Numpy
I am studying image-processing using NumPy and facing a problem with filtering with convolution.

I would like to convolve a gray-scale image. (convolve a 2d Array with a smaller 2d Array)

Does anyone have an idea to refine my method?

I know that SciPy supports convolve2d but I want to make a convolve2d only by using NumPy.

What I have done

First, I made a 2d array the submatrices.

```<code>a = np.arange(25).reshape(5,5) # original matrix

submatrices = np.array([
     [a[:-2,:-2], a[:-2,1:-1], a[:-2,2:]],
     [a[1:-1,:-2], a[1:-1,1:-1], a[1:-1,2:]],
     [a[2:,:-2], a[2:,1:-1], a[2:,2:]]])
</code>```

the submatrices seems complicated but what I am doing is shown in the following drawing.

Next, I multiplied each submatrices with a filter.

```<code>conv_filter = np.array([[0,-1,0],[-1,4,-1],[0,-1,0]])
multiplied_subs = np.einsum('ij,ijkl->ijkl',conv_filter,submatrices)
</code>```

and summed them.

```<code>np.sum(np.sum(multiplied_subs, axis = -3), axis = -3)
#array([[ 6,  7,  8],
#       [11, 12, 13],
#       [16, 17, 18]])
</code>```

Thus this procedure can be called my convolve2d.

```<code>def my_convolve2d(a, conv_filter):
    submatrices = np.array([
         [a[:-2,:-2], a[:-2,1:-1], a[:-2,2:]],
         [a[1:-1,:-2], a[1:-1,1:-1], a[1:-1,2:]],
         [a[2:,:-2], a[2:,1:-1], a[2:,2:]]])
    multiplied_subs = np.einsum('ij,ijkl->ijkl',conv_filter,submatrices)
    return np.sum(np.sum(multiplied_subs, axis = -3), axis = -3)
</code>```

However, I find this my_convolve2d troublesome for 3 reasons.

Generation of the submatrices is too awkward that is difficult to read and can only be used when the filter is 3*3

The size of the variant submatrices seems to be too big, since it is approximately 9 folds bigger than the original matrix.

The summing seems a little non intuitive. Simply said, ugly.

Thank you for reading this far.

Kind of update. I wrote a conv3d for myself. I will leave this as a public domain.

```<code>def convolve3d(img, kernel):
    # calc the size of the array of submatrices
    sub_shape = tuple(np.subtract(img.shape, kernel.shape) + 1)

    # alias for the function
    strd = np.lib.stride_tricks.as_strided

    # make an array of submatrices
    submatrices = strd(img,kernel.shape + sub_shape,img.strides * 2)

    # sum the submatrices and kernel
    convolved_matrix = np.einsum('hij,hijklm->klm', kernel, submatrices)

    return convolved_matrix
</code>```

答:
You could generate the subarrays using as_strided:

```<code>import numpy as np

a = np.array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24]])

sub_shape = (3,3)
view_shape = tuple(np.subtract(a.shape, sub_shape) + 1) + sub_shape
strides = a.strides + a.strides

sub_matrices = np.lib.stride_tricks.as_strided(a,view_shape,strides)
</code>```

To get rid of your second "ugly" sum, alter your einsum so that the output array only has j and k. This implies your second summation.

```<code>conv_filter = np.array([[0,-1,0],[-1,5,-1],[0,-1,0]])
m = np.einsum('ij,ijkl->kl',conv_filter,sub_matrices)

# [[ 6  7  8]
#  [11 12 13]
#  [16 17 18]]
</code>```

ContentLicense: CC BY-SA 4.0

Title: Convolve2d just by using Numpy

Body:
I am studying image-processing using NumPy and facing a problem with filtering with convolution.

I would like to convolve a gray-scale image. (convolve a 2d Array with a smaller 2d Array)

Does anyone have an idea to refine my method?

I know that SciPy supports convolve2d but I want to make a convolve2d only by using NumPy.

What I have done

First, I made a 2d array the submatrices.

a = np.arange(25).reshape(5,5) # original matrix

submatrices = np.array([
     [a[:-2,:-2], a[:-2,1:-1], a[:-2,2:]],
     [a[1:-1,:-2], a[1:-1,1:-1], a[1:-1,2:]],
     [a[2:,:-2], a[2:,1:-1], a[2:,2:]]])

the submatrices seems complicated but what I am doing is shown in the following drawing.

Next, I multiplied each submatrices with a filter.

conv_filter = np.array([[0,-1,0],[-1,4,-1],[0,-1,0]])
multiplied_subs = np.einsum('ij,ijkl->ijkl',conv_filter,submatrices)

and summed them.

np.sum(np.sum(multiplied_subs, axis = -3), axis = -3)
#array([[ 6,  7,  8],
#       [11, 12, 13],
#       [16, 17, 18]])

Thus this procedure can be called my convolve2d.

def my_convolve2d(a, conv_filter):
    submatrices = np.array([
         [a[:-2,:-2], a[:-2,1:-1], a[:-2,2:]],
         [a[1:-1,:-2], a[1:-1,1:-1], a[1:-1,2:]],
         [a[2:,:-2], a[2:,1:-1], a[2:,2:]]])
    multiplied_subs = np.einsum('ij,ijkl->ijkl',conv_filter,submatrices)
    return np.sum(np.sum(multiplied_subs, axis = -3), axis = -3)

However, I find this my_convolve2d troublesome for 3 reasons.

Generation of the submatrices is too awkward that is difficult to read and can only be used when the filter is 3*3

The size of the variant submatrices seems to be too big, since it is approximately 9 folds bigger than the original matrix.

The summing seems a little non intuitive. Simply said, ugly.

Thank you for reading this far.

Kind of update. I wrote a conv3d for myself. I will leave this as a public domain.

def convolve3d(img, kernel):
    # calc the size of the array of submatrices
    sub_shape = tuple(np.subtract(img.shape, kernel.shape) + 1)

    # alias for the function
    strd = np.lib.stride_tricks.as_strided

    # make an array of submatrices
    submatrices = strd(img,kernel.shape + sub_shape,img.strides * 2)

    # sum the submatrices and kernel
    convolved_matrix = np.einsum('hij,hijklm->klm', kernel, submatrices)

    return convolved_matrix

Body:
You could generate the subarrays using as_strided:

import numpy as np

a = np.array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24]])

sub_shape = (3,3)
view_shape = tuple(np.subtract(a.shape, sub_shape) + 1) + sub_shape
strides = a.strides + a.strides

sub_matrices = np.lib.stride_tricks.as_strided(a,view_shape,strides)

To get rid of your second "ugly" sum, alter your einsum so that the output array only has j and k. This implies your second summation.

conv_filter = np.array([[0,-1,0],[-1,5,-1],[0,-1,0]])
m = np.einsum('ij,ijkl->kl',conv_filter,sub_matrices)

# [[ 6  7  8]
#  [11 12 13]
#  [16 17 18]]


问:
C Pointers about the different data type
Pointer always stores a integer value i.e address so why do we need to declare them with different data type.

Like

```<code>int a=3,*p=&a;
char c=r,*cha=&r;
</code>```

why can't we do like

```<code>int *c;
char r=a;
c=&r;
</code>```

答:
Of course you can assign an address value to any type pointers.

```<code>int d;
char* cp = (char*)&d;     // OK
float* fp = (float*)&d;   // OK
</code>```

But when you get content from the address, you MUST know the type. Otherwise the compiler will not know how to interpret it.

Body:
Pointer always stores a integer value i.e address so why do we need to declare them with different data type.

Like

int a=3,*p=&a;
char c=r,*cha=&r;

why can't we do like

int *c;
char r=a;
c=&r;

Body:
Of course you can assign an address value to any type pointers.

int d;
char* cp = (char*)&d;     // OK
float* fp = (float*)&d;   // OK

But when you get content from the address, you MUST know the type. Otherwise the compiler will not know how to interpret it.


问:
Ruby - Sum of pairs in an array that add to a certain given input
I'm doing a ruby problem and my solution works. However, it does not work on bigger test cases because it takes too long to process.

The method takes two inputs, an array of numbers and a number.

The goal is to find the first two numbers in the array whose sum is the number provided in the input.

The first pair means that the highest index of the pair is lower than the highest index of any other pairs in the array that add to the number.

Example - ([10, 5, 2, 3, 7, 5], 10)

The answer should be [3, 7] while [5, 5] also sums to 10, the index of the last 5 is 5 and the index of 7 is 4, so [3, 7] comes first.

```<code>def sum_pairs(ints, s)
  return nil if ints.empty? || ints.nil?

  x = ints.combination(2).select {|x, y| x + y == s}

  return nil if x.nil? || x.empty?

  ints.rindex(x[0][1]) > ints.rindex(x[-1][1]) ? x.last : x.first

end
</code>```

My code worked for all test cases besides those with large arrays.

I was wondering if there was a built in method to help or if I needed to loop through the array differently.

答:
With a Set, only one pass is needed for this problem :

```<code>require 'set'

def sum_pairs(ints, s)
  already_seen = Set.new
  ints.each do |int|
    return [s - int, int] if already_seen.include?(s - int)
    already_seen.add(int)
  end
  nil
end

sum_pairs([10, 5, 2, 3, 7, 5], 10)
# [3, 7]
sum_pairs([10, 5, 2, 3, 7, 5], 20)
# nil
</code>```

It outputs the result in the correct order and will be much faster than the other solutions.

Body:
I'm doing a ruby problem and my solution works. However, it does not work on bigger test cases because it takes too long to process.

The method takes two inputs, an array of numbers and a number.

The goal is to find the first two numbers in the array whose sum is the number provided in the input.

The first pair means that the highest index of the pair is lower than the highest index of any other pairs in the array that add to the number.

Example - ([10, 5, 2, 3, 7, 5], 10)

The answer should be [3, 7] while [5, 5] also sums to 10, the index of the last 5 is 5 and the index of 7 is 4, so [3, 7] comes first.

def sum_pairs(ints, s)
  return nil if ints.empty? || ints.nil?

  x = ints.combination(2).select {|x, y| x + y == s}

  return nil if x.nil? || x.empty?

  ints.rindex(x[0][1]) > ints.rindex(x[-1][1]) ? x.last : x.first

end

My code worked for all test cases besides those with large arrays.

I was wondering if there was a built in method to help or if I needed to loop through the array differently.

Body:
With a Set, only one pass is needed for this problem :

require 'set'

def sum_pairs(ints, s)
  already_seen = Set.new
  ints.each do |int|
    return [s - int, int] if already_seen.include?(s - int)
    already_seen.add(int)
  end
  nil
end

sum_pairs([10, 5, 2, 3, 7, 5], 10)
# [3, 7]
sum_pairs([10, 5, 2, 3, 7, 5], 20)
# nil

It outputs the result in the correct order and will be much faster than the other solutions.


问:
Rails select_date form name
As much as I love rails, I've always hated dealing with dates in an html form...especially when the date isn't an object's property.

The select_date helper is nice, but it always generates this:

```<code><select name="date[year]" id="date_year">
<select name="date[month]" id="date_month">
<select name="date[day]" id="date_day">
</code>```

And I can't figure out a way to change the name prefix from "date" to something else. Is there a way to do this? What do you all use for date inputs when they're not an object property?

答:
You can use the :prefix option to do this.

```<code><%= select_date(nil, :prefix => 'payday') %>
</code>```

Which generates this:

```<code><select id="payday_year" name="payday[year]">
<select id="payday_month" name="payday[month]">
<select id="payday_day" name="payday[day]">
</code>```

More examples here

http://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html#method-i-select_date

Title: Rails select_date form name

Body:
As much as I love rails, I've always hated dealing with dates in an html form...especially when the date isn't an object's property.

The select_date helper is nice, but it always generates this:

<select name="date[year]" id="date_year">
<select name="date[month]" id="date_month">
<select name="date[day]" id="date_day">

And I can't figure out a way to change the name prefix from "date" to something else. Is there a way to do this? What do you all use for date inputs when they're not an object property?

Body:
You can use the :prefix option to do this.

<%= select_date(nil, :prefix => 'payday') %>

Which generates this:

<select id="payday_year" name="payday[year]">
<select id="payday_month" name="payday[month]">
<select id="payday_day" name="payday[day]">

More examples here

http://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html#method-i-select_date


问:
Assets behaviour in multiplatform libGDX application
What is the best practice to store resources in libGDX library. I'm know that I can use AssetManager and also e.g. I can link the resources from android folder into iOS, but I dont know how it will behaviour on multiplatform devices. The resources are scale according to screen size/operating system, or I need to manually set diffrent size or resulution in each platform resource folder.I want to avoid any ovelaying or stretch behaviour.

答:
There are many ways to go about this and there is no "best" solution. However if you do already build for android just use the android assets folder. This is the default and will be used for other builds (due to the default libgdx project configurations).

The resources only scale if you tell them too. You can choose to use a viewport (a fit/fill viewport will not stretch but can add black/background bars that do not have the default aspect ratio). But you can also choose to implement screen dependency yourself by using the aspect ratio and the scale.

For instance:

A 1080x1920 mobile phone vs a 1440x1920 tablet
If you use a fit viewport you will have unused space on the tablet. if you use a fillviewport you might lose stuff on the phone. But if you take the phone as a default aspect ratio and calculate the width offset for the tablet (1440-1080/2) you can use this value to choose to put actors/sprites on the same location as on the prone (by using this offset) or relative to the screen edge (by using the screen size). I personally use this to place the UI relative to the screen and the game itself the same as on the phone. You can even choose to use a different layout depending on the aspect ratio.

Do note that in this way you will also have to calculate a global scale and use this everywhere in your application. This can be tedious to implement but gives you much more control!

So if you have a simple game and you don't care about tablets or different screen sizes I suggest you start with a fit viewport.

p.s. Not sure what you mean by "multiplatform devices", but as I said, the default libGDX setup does the heavy lifting here, so I suggest you use it!


问:
The "appengine.applications.get" permission is required
I am trying to deploy my first app engine spring boot project using gradle and I am running into the following error when I run "gradle appengineDeploy":

```<code>ERROR: (gcloud.app.deploy) Error Response: [403] Operation not allowed
Details: [
  [
    {
      "@type": "type.googleapis.com/google.rpc.ResourceInfo",
      "description": "The \"appengine.applications.get\" permission is required.",
      "resourceType": "gae.api"
    }
  ]
]
</code>```

Here is my build.gradle:

```<code>    buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:1.5.2.RELEASE")
        classpath("com.google.cloud.tools:appengine-gradle-plugin:+")
    }
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'
apply plugin: 'com.google.cloud.tools.appengine'
jar {
    baseName = 'gs-spring-boot'
    version =  '0.1.0'
}
repositories {
    mavenCentral()
    maven {
      url 'https://maven-central.storage.googleapis.com'
    }
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
dependencies {
    compile("org.springframework.boot:spring-boot-starter-web")
    // tag::actuator[]
    compile("org.springframework.boot:spring-boot-starter-actuator")
    // end::actuator[]
    // tag::tests[]
    testCompile("org.springframework.boot:spring-boot-starter-test")
    // end::tests[]
    //compile("com.google.cloud.tools:appengine-maven-plugin:1.0.0")
    //appengineSdk 'com.google.appengine:appengine-java-sdk:1.9.50'
    compile('com.google.appengine:appengine:+')
}
appengine {
  deploy {   // deploy configuration
    stopPreviousVersion = true  // default - stop the current version
    promote = true              // default - & make this the current version
  }
}
</code>```

Please let me know how to proceed.

答: I got this after updating the google cloud sdk. I just run gcloud init again and entered the same choices.

Body:
I am trying to deploy my first app engine spring boot project using gradle and I am running into the following error when I run "gradle appengineDeploy":

ERROR: (gcloud.app.deploy) Error Response: [403] Operation not allowed
Details: [
  [
    {
      "@type": "type.googleapis.com/google.rpc.ResourceInfo",
      "description": "The \"appengine.applications.get\" permission is required.",
      "resourceType": "gae.api"
    }
  ]
]

Here is my build.gradle:

    buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:1.5.2.RELEASE")
        classpath("com.google.cloud.tools:appengine-gradle-plugin:+")
    }
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'
apply plugin: 'com.google.cloud.tools.appengine'
jar {
    baseName = 'gs-spring-boot'
    version =  '0.1.0'
}
repositories {
    mavenCentral()
    maven {
      url 'https://maven-central.storage.googleapis.com'
    }
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
dependencies {
    compile("org.springframework.boot:spring-boot-starter-web")
    // tag::actuator[]
    compile("org.springframework.boot:spring-boot-starter-actuator")
    // end::actuator[]
    // tag::tests[]
    testCompile("org.springframework.boot:spring-boot-starter-test")
    // end::tests[]
    //compile("com.google.cloud.tools:appengine-maven-plugin:1.0.0")
    //appengineSdk 'com.google.appengine:appengine-java-sdk:1.9.50'
    compile('com.google.appengine:appengine:+')
}
appengine {
  deploy {   // deploy configuration
    stopPreviousVersion = true  // default - stop the current version
    promote = true              // default - & make this the current version
  }
}

Please let me know how to proceed.


问:
How can a Windows Phone 7 application register for push service updates when the phone starts?
I have a WP7 app and want it to register for push notifications when the phone starts up?

Image I have some kind of messaging app, and don't want to force the user to click the tile to sign in and register for push notifications.

Are there any events that happen on startup that would give me access to my application?

I'm extremely lazy, and if I had a WP7 phone I wouldn't want to have to click on a ton of tiles just to log in if I have saved my credentials in isolated storage and had the ability to 'sign in when the phone starts'.

答:
Your user will need to run your application at least once, so you can fire your code off to register the push notifications channel with your server.

With that done, your server can push updates down to the device whether it's running or not.


问:
Defining a function on KnockoutJS ViewModel
In KnockoutJs, I have the following ViewModel for an Admin page I'm working on:

```<code>function UsersViewModel() {
    var self = this;
    self.users = ko.observableArray([]);
    self.roles = ko.observableArray([]);

    $.post('http://localhost:23926/admin/acl/getroles',
        function(data) {
            const availableRoles = $.map(data,
                function(role) {
                    return new Role(role);
                });
            self.roles(availableRoles);
        },
        'json');

    $.post('http://localhost:23926/admin/acl/getuserroles',
        function(data) {
            const usersWithRoles = $.map(data,
                function(userWithRole) {
                    return new User(userWithRole);
                });
            self.users(usersWithRoles);
        },
        'json');

    self.selectedUser = ko.observable(self.users[0]);

    // operations
    self.setCurrentUser = function (user) {
        self.selectedUser(user);
    }

    self.SelectedUserHasRoles = ko.computed(function() {
        return self.selectedUser().roles().length > 0;
    });
}
</code>```

And in my HTML, I have the following:

```<code><div class="col-md-6" data-bind="if: $root.SelectedUserHasRoles()">
  <h4><i class="fa fa-shield" aria-hidden="true"></i> Roles</h4>
  <hr />
  <div id="roles-wrapper" data-bind="foreach: $root.selectedUser().roles">
      <div class="role-token" data-bind="text: name"></div>
  </div>
</div>
</code>```

And I think that should work! I'm trying to say:

If the selected User has roles, then loop through and show each role

If this worked, I'd see Users on the left, and the roles for the selected user on the right:

The above doesn't seem to work, and I'm not sure why! I get the error:

And line 343 is the return here:

```<code>self.SelectedUserHasRoles = ko.computed(function() {
    return self.selectedUser().roles().length > 0;
});
</code>```

What am I doing wrong?

答:
Your problem comes from the fact that your selectedUser is null, as you initalize it with the first element of an empty array :

```<code>self.users = ko.observableArray([]);
// => self.users[0] === null, and maybe you should use self.users()[0]
self.selectedUser = ko.observable(self.users[0]);
</code>```

To avoid this issue, you could either add a loading boolean to indicate that your application is not done loading the users, or add a Promise.all call and then add your initalizing logic.

Using promises:

```<code>var promises = [$.post(...), $.post(...)]
Promise.all(promises).then(function(data) {
  // ... users and roles initalisation
  self.selectedUser(self.users()[0]);
})

// or via chained done method
$.post(...).done(function() {
  self.selectedUser(self.users()[0]);
})
</code>```

or using a boolean logic (you may optimized this untested code):

```<code>self.loading = ko.observableArray(false)
self.isLoaded = ko.pureComputed(function() {
    return self.loading().all(function(x) { return x }) // ES5 syntax
})

self.selectedUser = ko.pureComputed(function() {
  if (self.isLoaded()) return users()[0]
  return null
})
$.post('..roles', function() {
  // ...
  self.loading()[0] = true
})
$.post('..users', function() {
  // ...
  self.loading()[1] = true
})
</code>```

and in your HTML:

```<code><div class="col-md-6" data-bind="if: $root.SelectedUserHasRoles()">
  <h4><i class="fa fa-shield" aria-hidden="true"></i> Roles</h4>
  <hr />
  <!-- ko if: !isLoaded() -->
  <span>Loading !</span>
  <!-- /ko -->
  <!-- ko if: isLoaded() -->
  <div id="roles-wrapper" data-bind="foreach: $root.selectedUser().roles">
      <div class="role-token" data-bind="text: name"></div>
  </div>
  <!-- /ko -->
</div>
</code>```

Body:
In KnockoutJs, I have the following ViewModel for an Admin page I'm working on:

function UsersViewModel() {
    var self = this;
    self.users = ko.observableArray([]);
    self.roles = ko.observableArray([]);

    $.post('http://localhost:23926/admin/acl/getroles',
        function(data) {
            const availableRoles = $.map(data,
                function(role) {
                    return new Role(role);
                });
            self.roles(availableRoles);
        },
        'json');

    $.post('http://localhost:23926/admin/acl/getuserroles',
        function(data) {
            const usersWithRoles = $.map(data,
                function(userWithRole) {
                    return new User(userWithRole);
                });
            self.users(usersWithRoles);
        },
        'json');

    self.selectedUser = ko.observable(self.users[0]);

    // operations
    self.setCurrentUser = function (user) {
        self.selectedUser(user);
    }

    self.SelectedUserHasRoles = ko.computed(function() {
        return self.selectedUser().roles().length > 0;
    });
}

And in my HTML, I have the following:

 Roles

And I think that should work! I'm trying to say:

If the selected User has roles, then loop through and show each role

If this worked, I'd see Users on the left, and the roles for the selected user on the right:

The above doesn't seem to work, and I'm not sure why! I get the error:

And line 343 is the return here:

self.SelectedUserHasRoles = ko.computed(function() {
    return self.selectedUser().roles().length > 0;
});

What am I doing wrong?

Body:
Your problem comes from the fact that your selectedUser is null, as you initalize it with the first element of an empty array :

self.users = ko.observableArray([]);
// => self.users[0] === null, and maybe you should use self.users()[0]
self.selectedUser = ko.observable(self.users[0]);

To avoid this issue, you could either add a loading boolean to indicate that your application is not done loading the users, or add a Promise.all call and then add your initalizing logic.

Using promises:

var promises = [$.post(...), $.post(...)]
Promise.all(promises).then(function(data) {
  // ... users and roles initalisation
  self.selectedUser(self.users()[0]);
})

// or via chained done method
$.post(...).done(function() {
  self.selectedUser(self.users()[0]);
})

or using a boolean logic (you may optimized this untested code):

self.loading = ko.observableArray(false)
self.isLoaded = ko.pureComputed(function() {
    return self.loading().all(function(x) { return x }) // ES5 syntax
})

self.selectedUser = ko.pureComputed(function() {
  if (self.isLoaded()) return users()[0]
  return null
})
$.post('..roles', function() {
  // ...
  self.loading()[0] = true
})
$.post('..users', function() {
  // ...
  self.loading()[1] = true
})

and in your HTML:

<div class="col-md-6" data-bind="if: $root.SelectedUserHasRoles()">
  <h4><i class="fa fa-shield" aria-hidden="true"></i> Roles</h4>
  <hr />
  <!-- ko if: !isLoaded() -->
  <span>Loading !</span>
  <!-- /ko -->
  <!-- ko if: isLoaded() -->
  <div id="roles-wrapper" data-bind="foreach: $root.selectedUser().roles">
      <div class="role-token" data-bind="text: name"></div>
  </div>
  <!-- /ko -->
</div>


问:
I want to filter the JSON data based on checkbox clicked but it is working only when more than one checkbox is clicked
```<code><!doctype html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>
<script>
var myApp = angular.module('myApp', []);

myApp.controller('checkBoxController', function ($scope) {

        //JSON data to be filtered based on last four properties
        $scope.patients=[{
        "id": 160,
        "email": "test.lnt.hillrom+StephenMurphy904@gmail.com",
        "firstName": "Stephen",
        "lastName": "Murphy",
        "isDeleted": false,
        "zipcode": 55110,
        "address": "39 Xswhss lane ",
        "city": "White Bear Lake",
        "dob": "12/21/1947",
        "gender": "Male",
        "title": null,
        "hillromId": "46399",
        "langKey": null,
        "middleName": null,
        "state": "MN",
        "mobilePhone": null,
        "primaryPhone": null,
        "createdAt": 1490167354000,
        "isActivated": true,
        "adherence": 98,
        "lastTransmissionDate": "2017-03-20",
        "lastLoggedInAt": null,
        "clinics": [],
        "hcp": null,
        "clinicMRNId": {
        },
        "clinicNamesCSV": "Jeffrey,Cathy General Hospital",
        "hcpNamesCSV": null,
        "mrnId": null,
        "hoursOfUsage": 0.0,
        "serialNumber": null,
        "deviceType": "VEST",
        "expired": false,
        "isSettingsDeviated": false,
        "isHMRNonCompliant": true,
        "isMissedTherapy": false,
        "isNoEvent": false,
        "deviceTypeVest": true,
        "deviceTypeMonarch": false
    },
    {
        "id": 639,
        "email": "test.lnt.hillrom+ThomasPrice986@gmail.com",
        "firstName": "Thomas",
        "lastName": "Price",
        "isDeleted": false,
        "zipcode": 54214,
        "address": "57 Emwzfe lane ",
        "city": null,
        "dob": "04/18/1955",
        "gender": null,
        "title": null,
        "hillromId": "22038",
        "langKey": null,
        "middleName": null,
        "state": null,
        "mobilePhone": null,
        "primaryPhone": null,
        "createdAt": 1490167354000,
        "isActivated": true,
        "adherence": 92,
        "lastTransmissionDate": "2017-03-20",
        "lastLoggedInAt": null,
        "clinics": [],
        "hcp": null,
        "clinicMRNId": {
        },
        "clinicNamesCSV": "Matthew,Cathy General Hospital",
        "hcpNamesCSV": null,
        "mrnId": null,
        "hoursOfUsage": 0.0,
        "serialNumber": null,
        "deviceType": "VEST",
        "expired": false,
        "isDeleted": false,
        "isSettingsDeviated": false,
        "isHMRNonCompliant": true,
        "isMissedTherapy": false,
        "isNoEvent": false,
        "deviceTypeVest": true,
        "deviceTypeMonarch": false
    },
    {
        "id": 43,
        "email": "test.lnt.hillrom+TimothyTaylor314@gmail.com",
        "firstName": "Timothy",
        "lastName": "Taylor",
        "isDeleted": false,
        "zipcode": 92647,
        "address": "9 Jcktpp lane ",
        "city": null,
        "dob": "11/12/1930",
        "gender": null,
        "title": null,
        "hillromId": "10640",
        "langKey": null,
        "middleName": null,
        "state": null,
        "mobilePhone": null,
        "primaryPhone": null,
        "createdAt": 1490167354000,
        "isActivated": true,
        "adherence": 98,
        "lastTransmissionDate": "2017-03-20",
        "lastLoggedInAt": null,
        "clinics": [],
        "hcp": null,
        "clinicMRNId": {
        },
        "clinicNamesCSV": "Michelle,Cathy General Hospital",
        "hcpNamesCSV": null,
        "mrnId": null,
        "hoursOfUsage": 0.0,
        "serialNumber": null,
        "deviceType": "BOTH",
        "expired": false,
        "isSettingsDeviated": false,
        "isHMRNonCompliant": true,
        "isMissedTherapy": false,
        "isNoEvent": false,
        "deviceTypeVest": true,
        "deviceTypeMonarch": true
    },
    {
        "id": 642,
        "email": "test.lnt.hillrom+WilliamTorres381@gmail.com",
        "firstName": "William",
        "lastName": "Torres",
        "isDeleted": false,
        "zipcode": 68124,
        "address": "97 Qxqkcg park ",
        "city": null,
        "dob": "12/18/1953",
        "gender": null,
        "title": null,
        "hillromId": "56209",
        "langKey": null,
        "middleName": null,
        "state": null,
        "mobilePhone": null,
        "primaryPhone": null,
        "createdAt": 1490167354000,
        "isActivated": true,
        "adherence": 72,
        "lastTransmissionDate": "2017-03-20",
        "lastLoggedInAt": null,
        "clinics": [],
        "hcp": null,
        "clinicMRNId": {
        },
        "clinicNamesCSV": "Janet,Cathy General Hospital",
        "hcpNamesCSV": null,
        "mrnId": null,
        "hoursOfUsage": 0.0,
        "serialNumber": null,
        "deviceType": "MONARCH",
        "expired": false,
        "isSettingsDeviated": false,
        "isHMRNonCompliant": false,
        "isMissedTherapy": false,
        "isNoEvent": false,
        "deviceTypeVest": false,
        "deviceTypeMonarch": true
    },
    {
        "id": 92,
        "email": "test.lnt.hillrom+NancyWashington265@gmail.com",
        "firstName": "Nancy",
        "lastName": "Washington",
        "isDeleted": false,
        "zipcode": 55373,
        "address": "28 Huekni street ",
        "city": "Rockford",
        "dob": "02/16/1968",
        "gender": null,
        "title": null,
        "hillromId": "87291",
        "langKey": null,
        "middleName": null,
        "state": "MN",
        "mobilePhone": null,
        "primaryPhone": null,
        "createdAt": 1490167354000,
        "isActivated": true,
        "adherence": 96,
        "lastTransmissionDate": "2017-03-19",
        "lastLoggedInAt": null,
        "clinics": [],
        "hcp": null,
        "clinicMRNId": {
        },
        "clinicNamesCSV": "Jeffrey,Cathy General Hospital",
        "hcpNamesCSV": null,
        "mrnId": null,
        "hoursOfUsage": 0.0,
        "serialNumber": null,
        "deviceType": "MONARCH",
        "expired": false,
        "isSettingsDeviated": false,
        "isHMRNonCompliant": false,
        "isMissedTherapy": true,
        "isNoEvent": false,
        "deviceTypeVest": true,
        "deviceTypeMonarch": true
    }];
    var init = function () {
    $scope.searchFilter = {};
    $scope.searchFilter.isHMRNonCompliant = false;
    $scope.searchFilter.isSettingsDeviated = false;
    $scope.searchFilter.isMissedTherapy = false;
    $scope.searchFilter.isNoEvent = false;
    $scope.searchFilter.deviceTypeVest = false;
    $scope.searchFilter.deviceTypeMonarch = false;
    };
    init();
});
</script>
</head>
<body ng-app="myApp">
<div ng-controller="checkBoxController">
    <h3 style="text-align:center;">AngularJS - Retrieve Multiple Checkbox Selected Options</h3>

    <div>
        <div>
            <div>
                <input type="checkbox" ng-model="searchFilter.isSettingsDeviated" />isSettingsDeviated
                <input type="checkbox" ng-model="searchFilter.isHMRNonCompliant" />isHMRNonCompliant
                <input type="checkbox" ng-model="searchFilter.isMissedTherapy" />isMissedTherapy
                <input type="checkbox" ng-model="searchFilter.isNoEvent" />isNoEvent
                <input type="checkbox" ng-model="searchFilter.deviceTypeVest" />deviceTypeVest
                <input type="checkbox" ng-model="searchFilter.deviceTypeMonarch" />deviceTypeMonarch
                <p ng-repeat="patient in patients  | filter: { isNoEvent:searchFilter.isNoEvent,isSettingsDeviated:searchFilter.isSettingsDeviated,isMissedTherapy:searchFilter.isMissedTherapy,isHMRNonCompliant:searchFilter.isHMRNonCompliant,deviceTypeVest:searchFilter.deviceTypeVest,deviceTypeMonarch:searchFilter.deviceTypeMonarch }">{{patient.lastName}}, {{patient.firstName}}</p>

</div>
        </div>
    </div>

</div>
</body>
</html>
</code>```

答:
You have to individually add different filters for the options you have provided. I have added a minimal version of your requirement in the fiddle. Please take a look at fiddle. In HTML, you have to call like this.</p>

```<code><p ng-repeat="patient in patients  | isNoEvent:searchFilter.isNoEvent   | isSettingsDeviated:searchFilter.isSettingsDeviated ">{{patient.lastName}}, {{patient.firstName}}</p>
</code>```

Body:
<!doctype html>

AngularJS - Retrieve Multiple Checkbox Selected Options

                <input type="checkbox" ng-model="searchFilter.isSettingsDeviated" />isSettingsDeviated
                <input type="checkbox" ng-model="searchFilter.isHMRNonCompliant" />isHMRNonCompliant
                <input type="checkbox" ng-model="searchFilter.isMissedTherapy" />isMissedTherapy
                <input type="checkbox" ng-model="searchFilter.isNoEvent" />isNoEvent
                <input type="checkbox" ng-model="searchFilter.deviceTypeVest" />deviceTypeVest
                <input type="checkbox" ng-model="searchFilter.deviceTypeMonarch" />deviceTypeMonarch

{{patient.lastName}}, {{patient.firstName}}

Body:
You have to individually add different filters for the options you have provided. I have added a minimal version of your requirement in the fiddle. Please take a look at fiddle. In HTML, you have to call like this.

<p ng-repeat="patient in patients  | isNoEvent:searchFilter.isNoEvent   | isSettingsDeviated:searchFilter.isSettingsDeviated ">{{patient.lastName}}, {{patient.firstName}}</p>


问:
Laravel 5.0 query database using a form
I am new to Laravel 5.0 and I'm having trouble using a form to query a database and return the results to a view. Form accepts user input for week number and this week number should be used to query the database table. Any help would be appreciated.

Form inside my view

```<code><form action="" method="get">
    {{ csrf_field() }}
    <div class="input-group">
       <input type="text" class="form-control" name="weekNum" placeholder="Typein Week Number">
       <span class="input-group-btn">
           <button type="submit" class="btn btn-default">
               <span class="glyphicon glyphicon-search"></span>
           </button>
       </span>
   </div>
</form>
</code>```

Route::get('/search', 'shopsalescontroller@index');

Controller

```<code>class shopsalescontroller extends Controller
{
    public function index()
    {
        $weekNum = Request::input('WeekNumber');
        $result = shopsales::where('WeekNumber','=',$weekNum)->get();
        return $result;
    }
}
</code>```

答: try to change your form action to this action="{{ url('/search') }}"

Title: Laravel 5.0 query database using a form

Body:
I am new to Laravel 5.0 and I'm having trouble using a form to query a database and return the results to a view. Form accepts user input for week number and this week number should be used to query the database table. Any help would be appreciated.

Form inside my view

<form action="" method="get">
    {{ csrf_field() }}

       <input type="text" class="form-control" name="weekNum" placeholder="Typein Week Number">

           <button type="submit" class="btn btn-default">

           </button>

</form>

Route::get('/search', 'shopsalescontroller@index');

Controller

class shopsalescontroller extends Controller
{
    public function index()
    {
        $weekNum = Request::input('WeekNumber');
        $result = shopsales::where('WeekNumber','=',$weekNum)->get();
        return $result;
    }
}


问:
@Rollback is not working in Spring+Hibernate+Junit testing
while testing a DAO function in spring+hibernate application, data rollback is not happening. I am trying to do the rollback a junit test case by @Rollback annotation

transactionManager config:

```<code><bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="emf" />
</bean>
</code>```

In my main code I am using hibernateTemplate() to do CRUD operations

test code:

```<code>@Test
@Transactional
@Rollback(true)
public void test_populateObject() throws Exception {

    // TransactionDefinition def = new DefaultTransactionDefinition();
    // TransactionStatus status = transactionManager.getTransaction(def);

    manualObj= new ManualObj();

    manualObj.setName("TestObj001");
    manualObj.setRefId("TestObj001");
    manualObj.setCallback("TestObj001");
    m
    TestObject obj=orderService.createTestObject(manualObj);

    Assert.assertNotNull(obj);

    // transactionManager.rollback(status);

}
</code>```

The created object is not being deleted by rollback.

So, What could be the reason that @Rollback is n't happening?

Edit 1:

I am using Spring Data JPA and hibernateTemplate based data access in same application. Both using the same transaction manager specified like the above bean config.

答:
Did you configure your test to use the xml configuration, and did you specify the SpringJUnit4ClassRunner to run your test?
You can do it like this:</p>

```<code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"testContext.xml"})
@Transactional
public class YourTest{ ... }
</code>```

Body:
while testing a DAO function in spring+hibernate application, data rollback is not happening. I am trying to do the rollback a junit test case by @Rollback annotation

transactionManager config:

<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="emf" />
</bean>

In my main code I am using hibernateTemplate() to do CRUD operations

test code:

@Test
@Transactional
@Rollback(true)
public void test_populateObject() throws Exception {

    // TransactionDefinition def = new DefaultTransactionDefinition();
    // TransactionStatus status = transactionManager.getTransaction(def);

    manualObj= new ManualObj();

    manualObj.setName("TestObj001");
    manualObj.setRefId("TestObj001");
    manualObj.setCallback("TestObj001");
    m
    TestObject obj=orderService.createTestObject(manualObj);

    Assert.assertNotNull(obj);

    // transactionManager.rollback(status);

}

The created object is not being deleted by rollback.

So, What could be the reason that @Rollback is n't happening?

Edit 1:

I am using Spring Data JPA and hibernateTemplate based data access in same application. Both using the same transaction manager specified like the above bean config.

Body:
Did you configure your test to use the xml configuration, and did you specify the SpringJUnit4ClassRunner to run your test?
You can do it like this:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"testContext.xml"})
@Transactional
public class YourTest{ ... }


问:
Append wearable APK file to handheld APK file using Eclipse
Does somebody know a solution how can I build APK file using Eclipse or manually for both handheld and wearable usage? As I know Android Studio gradle script copies apk into raw folder. Is it enough? Are there the other rules for such build? </p>

答:
You may follow this tutorial with steps on how to setup and package an Android Wear app using Eclipse.

Prerequisites:

Make sure that you already have Eclipse setup with the latest ADT (Android Development Tools). If not, you can find the steps here.

Download the latest Android SDK.

Add Android Wear Support library (android.support.wearable) to your workspace. Go to your Android SDK folder, and find this file, ./extras/google/m2repository/com/google/android/support/wearable/1.0.0/wearable-1.0.0.aar. Copy the wearable-1.0.0.aar to a new location that you preferred. Then rename it to zip file before extracting it. After you extract it, create a libs folder and copy classes.jar into the libs folder.

Add this Android Wear Support library to your Eclipse workspace.

To package your app, follow these steps:

Open your WearApp AndroidManifest.xml file and pay attention to the Version Code and Version Name.

Create a new Project (WearAppOnPhone) for your Android app that will be installed on your phone. Please make sure the package name should be the same as your Android Wear app.

Import/Add Google Play Services to this project.

Open back your WearApp project and generate the signed APK file and rename it to wearable_app.apk.

Copy this file and put it into your WearAppOnPhone project at folder /WearAppOnPhone/res/raw/.

On DemoWearAppOnPhone project, create a new xml file, wearable_app_desc.xml at res/xml/ folder.

Open the AndroidManifest.xml file for WearAppOnPhone project.

Add in the 2 extra meta-data block. No changes required.

<meta-data android:name="package name"
android:resource="@xml/wearable_app_desc"/>

<meta-data android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version"/>

Double check your WearAppOnPhone project structure. It should be like this:

Finally, generate a signed APK for WearAppOnPhone and you are ready to release your first Android Wear app.

Hope this helps!


答:
You need to call your route in your view. Add the following

```<code><form action="{{ url('/search') }}" method="get">
   {{ csrf_field() }}
   <div class="input-group">
       <input type="text" class="form-control" name="weekNum" placeholder="Typein Week Number">
       <span class="input-group-btn">
           <button type="submit" class="btn btn-default">
               <span class="glyphicon glyphicon-search"></span>
           </button>
       </span>
   </div>
</form>
</code>```

You could also use the route helper if you added a name to your route

Title: Laravel 5.0 query database using a form

Body:
You need to call your route in your view. Add the following

<form action="{{ url('/search') }}" method="get">
   {{ csrf_field() }}
   <div class="input-group">
       <input type="text" class="form-control" name="weekNum" placeholder="Typein Week Number">
       <span class="input-group-btn">
           <button type="submit" class="btn btn-default">
               <span class="glyphicon glyphicon-search"></span>
           </button>
       </span>
   </div>
</form>

You could also use the route helper if you added a name to your route


问:
JavaScript expression parser in Silverlight
Hey everybody! I have a Silverlight project that needs to help users create JavaScript logical expressions (e.g. "var1 != var2 && var3 >= var4"). Very simple. The problem is that I do not have much time to create one myself because tweaking the transition table would be a little time consuming.

So I was searching online for one, but all I found was a couple classes that help you validate the JavaScript, but I need a way to load it, parse it and then write it back. So I was wondering if anyone has any ideas about how I can do it. I am assuming it will not require much code, and it does not have to be a C# example either. If only you could give me some ideas in C++ or even pseudo code, that would help a lot.

Thank you,

Vladimir

答:
I did something like this in flash/actionscrpt. I assume it's pretty much the same in Silverlight. After a quick google search I see that RegisterScriptableObject is similar to ActionScript's ExternalInterface. Anyway, here is my example.

This Silverlight example comes pretty close to doing the same thing.


问:
Select odd numbers and does not contain special characters
This is Table WWE :

```<code>    |**Col A**  | **Col B** |
   -+-----------+-----------+-
    | Hello     | 9%15A     |
    | World     | 2*10      |
    | Cat       | 12        |
    | Dog       | 13        |
</code>```

Col B is Varchar (100)

How do I select all rows consist of ODD NUMBERS ONLY and does not contain '%' or '*' or alphabets??

I know how to get ODD NUMBERS : colB % 2 <> 0

But I don't know how to EXCLUDE the special characters and to calculate the number as NUMBER since they're stored in VARCHAR

For example in this table, the output will be

```<code>| Dog | 13 |
</code>```

答:
You can check both conditions with a single regular expression:

```<code>SELECT * FROM WWE WHERE colB REGEXP '^[[:digit:]]*[13579]$';
</code>```

Which could be read as:

Starts with a digit, followed by any number of digits and finishing with any one of these characters (1,3,5,7)

For this sample data

```<code>    |**Col A**  | **Col B** |
   -+-----------+-----------+-
    | Hello     | 9%15A     |
    | World     | 2*10      |
    | Cat       | 12        |
    | Dog       | 13        |
</code>```

Returns

```<code>    |**Col A**  | **Col B** |
   -+-----------+-----------+-
    | Dog       | 13        |
</code>```

Updated to account for single digits, thanks to @Thorsten Kettner

Body:
This is Table WWE :

    |**Col A**  | **Col B** |
   -+-----------+-----------+-
    | Hello     | 9%15A     |
    | World     | 2*10      |
    | Cat       | 12        |
    | Dog       | 13        |

Col B is Varchar (100)

How do I select all rows consist of ODD NUMBERS ONLY and does not contain '%' or '*' or alphabets??

I know how to get ODD NUMBERS : colB % 2 <> 0

But I don't know how to EXCLUDE the special characters and to calculate the number as NUMBER since they're stored in VARCHAR

For example in this table, the output will be

| Dog | 13 |

Body:
You can check both conditions with a single regular expression:

SELECT * FROM WWE WHERE colB REGEXP '^[[:digit:]]*[13579]$';

Which could be read as:

Starts with a digit, followed by any number of digits and finishing with any one of these characters (1,3,5,7)

For this sample data

    |**Col A**  | **Col B** |
   -+-----------+-----------+-
    | Hello     | 9%15A     |
    | World     | 2*10      |
    | Cat       | 12        |
    | Dog       | 13        |

Returns

    |**Col A**  | **Col B** |
   -+-----------+-----------+-
    | Dog       | 13        |

Updated to account for single digits, thanks to @Thorsten Kettner


问:
Gmail API - Is there a way to list messages in sorted order w.r.t. receive time?
Is there a way to list Gmail mails using Google Mail APIs in sorted order of receive time?

Although the API returns the mails in reverse chronological order. For a very small data set like 10 mails, I am finding a discrepancy.

Response of mail list API:

```<code> {
 "messages": [
  {
   "id": "15afb61b8d220a19",
   "threadId": "15afb61b8d220a19"
  },
  {
   "id": "15afb618f941d73f",
   "threadId": "15afb618f941d73f"
  },
  {
   "id": "15afb6174711c7af",
   "threadId": "15afb6174711c7af"
  },

  ...
  ...
  {
   "id": "159bc283f63d5eb7",
   "threadId": "159bc283f63d5eb7"
  },
  {
   "id": "159bc283dc97cd87",
   "threadId": "159bc283dc97cd87"
  },
  {
   "id": "159bc283d95f097c",
   "threadId": "159bc283d95f097c"
  }
 ],
 "resultSizeEstimate": 9
}
</code>```

First message in response(most recent):

```<code>Id: 15afb61b8d220a19
Date: "Thu, 23 Mar 2017 19:06:08 +0530"
internalDate: "1490276168000"
</code>```

Second mail in list:

```<code>Id: 15afb618f941d73f
Date: "Thu, 23 Mar 2017 19:05:58 +0530"
internalDate: "1490276158000"
</code>```

...
...
Second last mail in the list:

```<code>Id: 159bc283dc97cd87
Date: "Fri, 20 Jan 2017 05:54:30 -0800"
internalDate: "1484920470000"
</code>```

Last mail in the list(should be oldest, but is not):

```<code>Id: 159bc283d95f097c
Date: "Fri, 20 Jan 2017 05:54:31 -0800"
internalDate: "1484920471000"
</code>```

答:
I guess it's the expected behavior based from this thread.

...messages.list does NOT return in date ASC or date DESC. They are returned randomly as far as I can tell.

You can also use the search syntax to filter by email's date.

Body:
Is there a way to list Gmail mails using Google Mail APIs in sorted order of receive time?

Although the API returns the mails in reverse chronological order. For a very small data set like 10 mails, I am finding a discrepancy.

Response of mail list API:

 {
 "messages": [
  {
   "id": "15afb61b8d220a19",
   "threadId": "15afb61b8d220a19"
  },
  {
   "id": "15afb618f941d73f",
   "threadId": "15afb618f941d73f"
  },
  {
   "id": "15afb6174711c7af",
   "threadId": "15afb6174711c7af"
  },

  ...
  ...
  {
   "id": "159bc283f63d5eb7",
   "threadId": "159bc283f63d5eb7"
  },
  {
   "id": "159bc283dc97cd87",
   "threadId": "159bc283dc97cd87"
  },
  {
   "id": "159bc283d95f097c",
   "threadId": "159bc283d95f097c"
  }
 ],
 "resultSizeEstimate": 9
}

First message in response(most recent):

Id: 15afb61b8d220a19
Date: "Thu, 23 Mar 2017 19:06:08 +0530"
internalDate: "1490276168000"

Second mail in list:

Id: 15afb618f941d73f
Date: "Thu, 23 Mar 2017 19:05:58 +0530"
internalDate: "1490276158000"

...
...
Second last mail in the list:

Id: 159bc283dc97cd87
Date: "Fri, 20 Jan 2017 05:54:30 -0800"
internalDate: "1484920470000"

Last mail in the list(should be oldest, but is not):

Id: 159bc283d95f097c
Date: "Fri, 20 Jan 2017 05:54:31 -0800"
internalDate: "1484920471000"


问:
How to publish multiple NPM modules from a single node project?
The question is pretty straightforward: Is there some way to publish two different NPM modules to the npmjs registry from a single nodejs project?

But for those of you wondering why the heck would someone even want to do that? ... the motivation behind this question may not be too obvious. So allow me to explain:

I use something akin to an app-server called loopback. And my nodejs app is neatly distributed into client, common and server folders.

I often need to reuse the models in my common folder across other projects as well. And although I can publish just that folder as a separate NPM module by using .npmignore to remove the other stuff:

/*
/common/utils
/common/models/*.js
!/common/models/*.json

I cannot remove the clutter from my current package.json, which is needed to actually run my app, from what has been published.

$ npm pack
$ tree -L 2 ~/dev/w2/node_modules/warehouse
~/dev/w2/node_modules/warehouse
├── README.md
├── common
│   └── models
├── node_modules
│   ├── ...
│   └── ...
└── package.json

As things stand, I filtered out everything other than my common/models folder but since I'm not sure how to dynamically tweak the package.json file before packing it or as part of packing it ... an npm install will put down the dependencies that really aren't required.

I am not thrilled at the alternative of creating a separate project solely with models in it as that forces me to add it as a dependency to the core project and active development gets split across 2 projects where it used to be just one. npm link etc is a good approach to get around it but it adds complexity to developer setup when onboarding new folks and making sure that nobody checks in the wrong thing.

So is there some way to publish two different NPM modules to the npmjs registry from a single nodejs project? Or some way to use different package.json file for a separate publication but all from one project?

Update: What is my goal?

To reuse the models from my core project, across other projects, by publishing them as a NPM module. WITHOUT giving up the convenience of continuing to develop my core project as ONE atomic entity without npm link etc. as that gets messy fast when more than just one person is working on it.

答:
Having a similar question, I recently discovered: https://github.com/lerna/lerna, which may be of use to you.

From the readme:

Splitting up large codebases into separate independently versioned
  packages is extremely useful for code sharing. However, making changes
  across many repositories is messy and difficult to track, and testing
  across repositories gets complicated really fast.

To solve these (and many other) problems, some projects will organize
  their codebases into multi-package repositories (sometimes called
  monorepos). Projects like Babel, React, Angular, Ember, Meteor, Jest,
  and many others develop all of their packages within a single
  repository.

Lerna is a tool that optimizes the workflow around managing
  multi-package repositories with git and npm.