Q: Unable to Open new browser after each scenario in Cucumber-Protractor I had automated all my scenarios using cucumber-protractor framework. All this scenarios run fine when executed individually i.e. closes the browser once scenario is complete but when ran together I am unable to open new browser window after each scenario. It just continues in same browser. Due to SSO login, I have to restart browser after each scenario.
I tried using maxSession, maxInstance in protractor but of no help. Though maxIntance opens new browser, it doesn't close old one and neither passes control to new one. I tried using getWindowHandler as well but that also didn't worked.
Any help is greatly appreciated as I am stuck on this for long time.

A: It seems juliemr answers your question:

tests are sharded by file, not by scenario, so you'll need to split the scenarios into separate files.

https://github.com/angular/protractor/issues/864#issuecomment-45571006
So you'll need to split the scenarios into separate feature files and, if desired, set maxInstances to however many you want to run at once. For example:
capabilities: {
    'browserName': 'chrome',
    'shardTestFiles': true,
    'maxInstances': 10
}

A: Add a hook after each scenario to close the browser:
this.After(function(scenario, done) {
  this.quit(done);
});


Q: Which member in PROCESS_MEMORY_COUNTERS structure gives the current used memory Following is the PROCESS_MEMORY_COUNTERS structure
typedef struct _PROCESS_MEMORY_COUNTERS {
  DWORD  cb;
  DWORD  PageFaultCount;
  SIZE_T PeakWorkingSetSize;
  SIZE_T WorkingSetSize;
  SIZE_T QuotaPeakPagedPoolUsage;
  SIZE_T QuotaPagedPoolUsage;
  SIZE_T QuotaPeakNonPagedPoolUsage;
  SIZE_T QuotaNonPagedPoolUsage;
  SIZE_T PagefileUsage;
  SIZE_T PeakPagefileUsage;
} PROCESS_MEMORY_COUNTERS, *PPROCESS_MEMORY_COUNTERS;

Which member of the structure gives the current used memory of the specific process?

A: The structure member
WorkingSetSize

gives the current used memory.

The working set is the amount of memory physically mapped to the
  process context at a given time.

Ref.:Process Memory Usage Information.


Q: Create another symbol in specific point in a line graph I would like to have another symbol in a specific point of line graphs where the x axis has value of 1. In my graph, all the points in the line have circle as a symbol, but I would like to have a triangle where the value of the x axis is 1.
So far, I found this post when it creates an X symbol, but when I use it on my code, it creates an X mark on top the circle while I want an entirely new symbol.
Here is the code:
library(ggplot2)

wd = "path/"

block.data = read.csv(paste0(wd, "block.data.csv"))

ggplot(data = block.data, aes(x = PSF, y = CC, group = 1)) +
  geom_line() +
  geom_point(size = 2) +
  theme_bw() +
  theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
        panel.background = element_blank(), axis.line = element_line(colour = "black")) +
  scale_x_continuous(breaks = seq(0, 2, .2)) +
  scale_y_continuous(breaks = seq(0.08, 23, .01))

And the dataset:
structure(list(PSF = c(0, 0.2, 0.4, 0.6, 0.8, 1, 1.2, 1.4, 1.6,  1.8, 2), CC = c(0.08278661, 0.1866827, 0.2051862, 0.218509, 0.2247673,  0.2268575, 0.2265966, 0.22522, 0.223409, 0.2213272, 0.2192285 )), class = "data.frame", row.names = c(NA, -11L))

A: One option would be to map a condition, i.e. PSF != 1 on the shape aes and set your desired shape using scale_shape_manual:
library(ggplot2)

ggplot(data = block.data, aes(x = PSF, y = CC, group = 1)) +
  geom_line() +
  geom_point(aes(shape = PSF != 1), size = 3) +
  scale_shape_manual(values = c(17, 16)) +
  theme_bw() +
  theme(
    panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
    panel.background = element_blank(), axis.line = element_line(colour = "black")
  ) +
  scale_x_continuous(breaks = seq(0, 2, .2)) +
  scale_y_continuous(breaks = seq(0.08, 23, .01)) +
  guides(shape = "none")


Q: Why do I keep getting ArrayIndexOutOfBoundsException? I know that the ArrayIndexOutOfBoundsException means that you're trying to access something not defined in the array, and tried to look up solutions. All the solutions say that you need to use < rather than =<, but that's about it. I don't understand why my loop below keeps giving me ArrayIndexOutOfBoundsException erros.
 for (int i=0; i < myMessage.length(); ){
                eInteger = eNumbers[i];
                myInteger = numbers[i];
                System.out.println(eInteger + " " + myInteger);
                character = myInteger - eInteger;
                stringCharacter = Integer.toString(character);
                //decryptedMessage = decryptedMessage + " " + stringCharacter;
                System.out.println(character);
                i++;
            }

I've tried int i=0, int i = 1, myMessage.length() - 1. It shouldn't be attempting to give me something further than the array, but I don't know.
Full code:
    public class Decrypt {
    private String myMessage;
    private String e = "2718281828459045235360287471352662497757247093699959574966967627724076630353547594571382178525166427427466391932003059921817413596629043572900334295260595630738132328627943490763233829880753195251019011573834187930702154089149934884167509244761460668082264800168477411853742345442437107539077744992069551702761838606261331384583000752044933826560297606737113200709328709127443747047230696977209310141692836819025515108657463772111252389784425056953696770785449969967946864454905987931636889230098793127736178215424999229576351482208269895193668033182528869398496465105820939239829488793320362509443117301238197068416140397019837679320683282376464804295311802328782509819455815301756717361332069811250996181881593041690351598888519345807273866738589422879228499892086805825749279610484198444363463244968487560233624827041978623209002160990235304369941849146314093431738143640546253152096183690888707016768396424378140592714563549061303107208510383750510115747704171898610687396965521267154688957035035402123407849819334321068170121005627880235193033224745015853904730419957777093503660416997329725088687696640355570716226844716256079882651787134195124665201030592123667719432527867539855894489697096409754591856956380236370162112047742722836489613422516445078182442352948636372141740238893441247963574370263755294448337";
    private String stringCharacter;
    private int character;
    private int myInteger;
    private int eInteger;
    private String decryptedMessage = "";

    public Decrypt(String myMessage){
        this.myMessage = myMessage;
    }

    public String Decryption(){

        String[] splitMessage = myMessage.split(" ");
        int[] numbers = Arrays.stream(splitMessage)
                .mapToInt(Integer::parseInt).toArray();

        String[] eMessage = e.split("");
        int[] eNumbers = Arrays.stream(eMessage)
                .mapToInt(Integer::parseInt).toArray();

        for (int i=0; i < myMessage.length(); ){
            eInteger = eNumbers[i];
            myInteger = numbers[i];
            System.out.println(eInteger + " " + myInteger);
            character = myInteger - eInteger;
            stringCharacter = Integer.toString(character);
            //decryptedMessage = decryptedMessage + " " + stringCharacter;
            System.out.println(character);
            i++;
        }
        return stringCharacter;
    }

    public String toString(){
        return "Message: " + Decryption();
    }

}

When I run my program (the extra code is in a driver) I get the following:
Welcome to this cryptographic program! Would you like to encrypt or decrypt a message?
Please enter 1 to encrypt, and 2 to decrypt.
2
Thank you! Please type the message you would like to encrypt or decrypt.
22 12 20 28
2 22
Exception in thread "main" 20
7 12
5
1 20
19
8 28
20
java.lang.ArrayIndexOutOfBoundsException: 4
    at Program4.Decrypt.Decryption(Decrypt.java:30)
    at Program4.Decrypt.toString(Decrypt.java:42)
    at java.lang.String.valueOf(Unknown Source)
    at java.io.PrintStream.println(Unknown Source)
    at Program4.Driver.main(Driver.java:28)

A: The problem is that myMessage.length() is the number of characters in myMessage, whereas numbers.size is the number of integers represented in myMessage.
In your example run, myMessage is "22 12 20 28", which has 11 characters so you are iterating from 0 to 10; but numbers is an array of just four numbers (0 through 3), so numbers[i] will raise this exception for any i greater than 3.
If I'm understanding correctly what you are trying to do, you just need to change this:
        for (int i=0; i < myMessage.length(); ){

to this:
        for (int i=0; i < numbers.size; ){


Q: Display rss xml index in html I am adding an RSS feed to my website.  I created the RSS.xml index file and next I want to display its contents in a nicely formatted way in a webpage.
Using PHP, I can do this:
$index = file_get_contents ($path . 'RSS.xml');
echo $index;

But all that does is dump the contents as a long stream of text with the tags removed.
I know that treating RSS.xml as a link, like this:

  Blog Index

causes my browser to parse and display it in a reasonable way when the user clicks on the link.  However I want to embed it directly in the web page and not make the user go through another click.
What is the proper way to do what I want?

A: Use the following code:
 include_once('Simple/autoloader.php');
    $feed = new SimplePie();
    $feed->set_feed_url($url);
    $feed->enable_cache(false);
    $feed->set_output_encoding('utf-8');
    $feed->init();

     $i=0;
    $items = $feed->get_items();
    foreach ($items as $item) {
    $i++;
   /*You are getting title,description,date of your rss by the following code*/
    $title = $item->get_title();
    $url   = $item->get_permalink();
    $desc  = $item->get_description();
    $date  = $item->get_date();
    }

Download the Simple folder data from : https://github.com/jewelhuq/Online-News-Grabber/tree/master/worldnews/Simple
Hope it will work for you. There $url mean your rss feed url. If you works then response.

A: Turns out, it's simple by using the PHP xml parer function:
$xml = simplexml_load_file ($path . 'RSS.xml');
$channel = $xml->channel;
$channel_title = $channel->title;
$channel_description = $channel->description;

echo "
$channel_title
";
echo "
$channel_description
";

foreach ($channel->item as $item)
{
  $title = $item->title;
  $link = $item->link;
  $descr = $item->description;

  echo "
$title
";
  echo "
$descr
";
}


Q: How to set a default row for a query that returns no rows? I need to know how to return a default row if no rows exist in a table. What would be the best way to do this? I'm only returning a single column from this particular table to get its value.
Edit: This would be SQL Server.

A: One approach for Oracle:
SELECT val
FROM myTable
UNION ALL
SELECT 'DEFAULT'
FROM dual
WHERE NOT EXISTS (SELECT * FROM myTable)

Or alternatively in Oracle:
SELECT NVL(MIN(val), 'DEFAULT')
FROM myTable

Or alternatively in SqlServer:
SELECT ISNULL(MIN(val), 'DEFAULT')
FROM myTable

These use the fact that MIN() returns NULL when there are no rows.

A: How about this:
SELECT DEF.Rate, ACTUAL.Rate, COALESCE(ACTUAL.Rate, DEF.Rate) AS UseThisRate
FROM
  (SELECT 0) DEF (Rate) -- This is your default rate
LEFT JOIN (
  select rate
  from d_payment_index
  --WHERE 1=2   -- Uncomment this line to simulate a missing value

  --...HERE IF YOUR ACTUAL WHERE CLAUSE. Removed for testing purposes...
  --where fy = 2007
  -- and payment_year = 2008
  --  and program_id = 18
) ACTUAL (Rate) ON 1=1

Results
Valid Rate Exists
Rate        Rate        UseThisRate
----------- ----------- -----------
0           1           1

Default Rate Used
Rate        Rate        UseThisRate
----------- ----------- -----------
0           NULL        0

Test DDL
CREATE TABLE d_payment_index (rate int NOT NULL)
INSERT INTO d_payment_index VALUES (1)

A: This snippet uses Common Table Expressions to reduce redundant code and to improve readability. It is a variation of John Baughman's answer.
The syntax is for SQL Server.
WITH products AS (
            SELECT prod_name,
                   price
              FROM Products_Table
             WHERE prod_name LIKE '%foo%'
     ),
     defaults AS (
            SELECT '-' AS prod_name,
                   0   AS price
     )

SELECT * FROM products
UNION ALL
SELECT * FROM defaults
 WHERE NOT EXISTS ( SELECT * FROM products );

A: *SQL solution
Suppose you have a review table which has primary key "id".
SELECT * FROM review WHERE id = 1555
UNION ALL
SELECT * FROM review WHERE NOT EXISTS ( SELECT * FROM review where id = 1555 ) AND id = 1

if table doesn't have review with 1555 id then this query will provide a review of id 1.

A: I figured it out, and it should also work for other systems too. It's a variation of WW's answer.
select rate
from d_payment_index
where fy = 2007
  and payment_year = 2008
  and program_id = 18
union
select 0 as rate
from d_payment_index
where not exists( select rate
                  from d_payment_index
                  where fy = 2007
                    and payment_year = 2008
                    and program_id = 18 )

A: One table scan method using a left join from defaults to actuals:
CREATE TABLE [stackoverflow-285666] (k int, val varchar(255))

INSERT  INTO [stackoverflow-285666]
VALUES  (1, '1-1')
INSERT  INTO [stackoverflow-285666]
VALUES  (1, '1-2')
INSERT  INTO [stackoverflow-285666]
VALUES  (1, '1-3')
INSERT  INTO [stackoverflow-285666]
VALUES  (2, '2-1')
INSERT  INTO [stackoverflow-285666]
VALUES  (2, '2-2')

DECLARE @k AS int
SET @k = 0

WHILE @k < 3
    BEGIN
        SELECT  @k AS k
               ,COALESCE(ActualValue, DefaultValue) AS [Value]
        FROM    (
                 SELECT 'DefaultValue' AS DefaultValue
                ) AS Defaults
        LEFT JOIN (
                   SELECT   val AS ActualValue
                   FROM     [stackoverflow-285666]
                   WHERE    k = @k
                  ) AS [Values]
                ON 1 = 1

        SET @k = @k + 1
    END

DROP TABLE [stackoverflow-285666]

Gives output:
k           Value
----------- ------------
0           DefaultValue

k           Value
----------- ------------
1           1-1
1           1-2
1           1-3

k           Value
----------- ------------
2           2-1
2           2-2

A: Assuming there is a table config with unique index on config_code column:
CONFIG_CODE     PARAM1   PARAM2
--------------- -------- --------
default_config  def      000
config1         abc      123
config2         def      456

This query returns line for config1 values, because it exists in the table:
SELECT *
  FROM (SELECT *
          FROM config
         WHERE config_code = 'config1'
            OR config_code = 'default_config'
         ORDER BY CASE config_code WHEN 'default_config' THEN 999 ELSE 1 END)
 WHERE rownum = 1;

CONFIG_CODE     PARAM1   PARAM2
--------------- -------- --------
config1         abc      123

This one returns default record as config3 doesn't exist in the table:
SELECT *
  FROM (SELECT *
          FROM config
         WHERE config_code = 'config3'
            OR config_code = 'default_config'
         ORDER BY CASE config_code WHEN 'default_config' THEN 999 ELSE 1 END)
 WHERE rownum = 1;

CONFIG_CODE     PARAM1   PARAM2
--------------- -------- --------
default_config  def      000

In comparison with other solutions this one queries table config only once.

A: If your base query is expected to return only one row, then you could use this trick:
select NVL( MIN(rate), 0 ) AS rate
from d_payment_index
where fy = 2007
  and payment_year = 2008
  and program_id = 18

(Oracle code, not sure if NVL is the right function for SQL Server.)

A: This would be eliminate the select query from running twice and be better for performance:
Declare @rate int

select
    @rate = rate
from
    d_payment_index
where
    fy = 2007
    and payment_year = 2008
    and program_id = 18

IF @@rowcount = 0
    Set @rate = 0

Select @rate 'rate'

A: Do you want to return a full row?  Does the default row need to have default values or can it be an empty row?  Do you want the default row to have the same column structure as the table in question?
Depending on your requirements, you might do something like this:
1)  run the query and put results in a temp table (or table variable)
2)  check to see if the temp table has results
3)  if not, return an empty row by performing a select statement similar to this (in SQL Server):
select '' as columnA, '' as columnB, '' as columnC from #tempTable

Where columnA, columnB and columnC are your actual column names.

A: Insert your default values into a table variable, then update this tableVar's single row with a match from your actual table. If a row is found, tableVar will be updated; if not, the default value remains. Return the table variable.
    ---=== The table & its data
    CREATE TABLE dbo.Rates (
        PkId int,
        name varchar(10),
        rate decimal(10,2)
    )
    INSERT INTO dbo.Rates(PkId, name, rate) VALUES (1, 'Schedule 1', 0.1)
    INSERT INTO dbo.Rates(PkId, name, rate) VALUES (2, 'Schedule 2', 0.2)

Here's the solution:
---=== The solution
CREATE PROCEDURE dbo.GetRate
  @PkId int
AS
BEGIN
  DECLARE @tempTable TABLE (
    PkId int,
    name varchar(10),
    rate decimal(10,2)
 )

 --- [1] Insert default values into @tempTable. PkId=0 is dummy value
 INSERT INTO @tempTable(PkId, name, rate) VALUES (0, 'DEFAULT', 0.00)

 --- [2] Update the single row in @tempTable with the actual value.
 ---     This only happens if a match is found
 UPDATE @tempTable
    SET t.PkId=x.PkId, t.name=x.name, t.rate = x.rate
    FROM @tempTable t INNER JOIN dbo.Rates x
    ON t.PkId = 0
    WHERE x.PkId = @PkId

 SELECT * FROM @tempTable
END

Test the code:
EXEC dbo.GetRate @PkId=1     --- returns values for PkId=1
EXEC dbo.GetRate @PkId=12314 --- returns default values

A: This is what I used for getting a default value if no values are present.

    SELECT IF (
        (SELECT COUNT(*) FROM tbs.replication_status) > 0,
        (SELECT rs.last_replication_end_date FROM tbs.replication_status AS rs
            WHERE rs.last_replication_start_date IS NOT NULL
                AND rs.last_replication_end_date IS NOT NULL
                AND rs.table = '%s' ORDER BY id DESC LIMIT 1),
        (SELECT CAST(UNIX_TIMESTAMP (CURRENT_TIMESTAMP(6)) AS UNSIGNED))
    ) AS ts;


Q: Extracting HTML input string into Python I'm currently trying to grab a string that a user would put in an HTML form, and set that equal to a variable in a python program after the 'search' button has been clicked. I'm using flask to run the html code just on localhost. How would I go about implementing this?
The code I have for the search bar so far is below.

        <input type="text" class="form-control" placeholder="Enter a string...">

            <button class="btn btn-success" type="submit">
              Search
            </button>


Q: pass url from one js page to another and extract exact value how can i pass this url="https://www.google.com/finance?q=tcs&ei=I7dtWaHxOJCuuATHoZaoCA" from store.js page and getting exact stock price of tcs on my another app.js page using chatbot and nodejs.


Q: Application.Match vs Find I want to write a macro that will get the last item in column A and check if it exists anywhere in columns B to D. However, the following code never finds a match and returns "Doesn't exist":
Sub MatchInRange()

Dim LastItem As Range
Set LastItem = Range("A1").End(xlDown)

If Not IsError(Application.Match(LastItem, "B:D", 0)) Then
    MsgBox "Exists in range"
Else
    MsgBox "Doesn't exist"
End If
End Sub

But it works when rewritten using Find:
Sub FindInRange()

Dim LastItem As Range
Set LastItem = Range("A1").End(xlDown)

If Not Range("B:D").Find(LastItem) Is Nothing Then
    MsgBox "Exists in range"
Else
    MsgBox "Doesn't exist"
End If
End Sub

Can anyone tell me what am I doing wrong with the first code?

A: Match works on 1 row or column. You are using 3 - B,C and D. Rewrite the first formula like this:
Sub TestMe()
    Debug.Print WorksheetFunction.match("TestValue", Range("B:B"), 0)
End Sub


Q: NSURLConnection JSON doesn't post data I'm creating a login Page in my iPhone app and I use Json to call a PHP page to connect to a MySql database.
I have the connection with the PHP page but my program doesn't post anything.
- (IBAction)login:(id)sender{

        //Alloc dictionary
        jsonDictionaryLogin = [[NSDictionary alloc] initWithObjectsAndKeys: securityCode, @"hash_app", loginTextField.text, @"app_email", passwordTextField.text, @"app_password", nil];

        NSError *jsonError = nil;
        jsonDataLogin = [NSJSONSerialization dataWithJSONObject:jsonDictionaryLogin
                                                        options:kNilOptions error:&jsonError];

        if(!jsonError) {

            NSString *serJSON = [[NSString alloc] initWithData:jsonDataLogin encoding:NSUTF8StringEncoding];
            NSLog(@"\n\nSerialized JSON: %@", serJSON);

        } else {

            NSLog(@"JSON Encoding Failed: %@", [jsonError localizedDescription]);
        }

        NSURL *url = [NSURL URLWithString:@"http://www.mywebsite.com/mypage.php"];

        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];

        [request setHTTPMethod:@"POST"];
        [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
        [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        [request addValue:[NSString stringWithFormat:@"%d", [jsonDataLogin length]] forHTTPHeaderField:@"content-Length"];

        [request setHTTPBody:jsonDataLogin];
        NSLog(@"jsonData: %@",jsonDataLogin);

        NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:true];

        [connection start];
    }

After, in my delegate method:
-   (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)theData{

    NSLog(@"String sent from server %@",[[NSString alloc] initWithData:theData encoding:NSUTF8StringEncoding]);

}

My PHP code:
<?
    $hash = $_POST['hash_app'];

    echo json_encode(array("TEST" => "swrao")); //RETURN swrao

    echo json_encode($hash); //RETURN null

        if($hash == "string_sended")
    {

         echo json_encode(array("TEST" => "YOU ARE IN")); //NO RETURN

        }

?>

The String from the NSLog give some message that i have written in PHP page, but the PHP page doesn't not receive the data sended.
Some idea?


Q: Google Translator API "Too Large URL" I have recently started working on Translator API and I am getting the ERROR Too Large URL when my input text exceeds 1300 characters.
I am using the below code
        string apiKey = "My Key";
        string sourceLanguage = "en";
        string targetLanguage = "de";
        string googleUrl;
        string textToTranslate =
        while (textToTranslate.Length < 1300)
        {
            textToTranslate = textToTranslate + " hello world ";
        }
        googleUrl = "https://www.googleapis.com/language/translate/v2?key=" + apiKey + "&q=" + textToTranslate + "&source=" + sourceLanguage + "&target=" + targetLanguage;

        WebRequest request = WebRequest.Create(googleUrl);
        // Set the Method property of the request to POST^H^H^H^HGET.
        request.Method = "GET"; // <-- ** You're putting textToTranslate into the query string so there's no need to use POST. **

        //// Create POST data and convert it to a byte array.
        //string postData = textToTranslate;
        //byte[] byteArray = Encoding.UTF8.GetBytes(postData);

        // Set the ContentType property of the WebRequest.
        request.ContentType = "application/x-www-form-urlencoded";

        // ** Commenting out the bit that writes the post data to the request stream **

        //// Set the ContentLength property of the WebRequest.
        //request.ContentLength = byteArray.Length;
        //// Get the request stream.
        //Stream dataStream = request.GetRequestStream();
        //// Write the data to the request stream.
        //dataStream.Write(byteArray, 0, byteArray.Length);
        //// Close the Stream object.
        //dataStream.Close();

        // Get the response.
        WebResponse response = request.GetResponse();
        // Display the status.
        Console.WriteLine(((HttpWebResponse)response).StatusDescription);
        // Get the stream containing content returned by the server.
        Stream dataStream = response.GetResponseStream();
        // Open the stream using a StreamReader for easy access.
        StreamReader reader = new StreamReader(dataStream);
        // Read the content.
        string responseFromServer = reader.ReadToEnd();
        // Display the content.
        Console.WriteLine(responseFromServer);
        Console.WriteLine(i);
        // Clean up the streams.
        reader.Close();
        dataStream.Close();
        response.Close();

Can You please suggest me that what kind of changes i can do in my code, so that the input text limit can be increased unto 40k - 50k per request.

A: At some point someone has changed your code from making a POST request to making a GET.
GET puts all the data into the URL instead of putting it in the request body. URLs have a length limit. Go back to using POST and this problem will go away. Refer to the documentation for your HTTP client library to find out how to do this.


Q: Spring Boot throws exception when int field in mongodb model has null value in the database I have a situation when a user does not enter data for certain field I pass null as value for that int field to signify that no value was entered by the user like
{user: 'John',
 age: null}

but when I read such document in my Spring Boot application, when it encounters above document, throws
Caused by: java.lang.IllegalArgumentException: Parameter age must not be null!

Is null allowed value in mongodb or Spring Boot is doing something wrong?
I tried to:
@Data
@Document
public class User {
    final private String user;
    @org.springframework.lang.Nullable
    final private int age;
}

But it makes no difference. How to solve this problem other than not storing null ( because null is already populated in another node/mongoose application (which gladly stores and reads null values without any issue) using the same mongodb database?

A: Replace int with Integer since int is a primitive type which won't accept null values. Integer is a wrapper object that accepts null values.


Q: What is the best way to update all clients when Flask database changes without polling? Currently I have a Flask server that runs a small web frontend as well as a command line interface to that same server.  The basic idea looks like this:
<Top section: allows file upload>
   * list of files from database

<Second section: allows file manipulation/ upload>
  * list of files  from database

<Third section: Not files, but still allows for database changes>
  * list of things made from database

Now this works well from the front end, but currently if the CLI or another client makes a change to the database, it doesn't update other clients. I have it somewhat working with JS polling and rewriting the list of files every 10s, but that seems both inefficient and also would look very messy if I had to do it for every section.  I saw websockets mentioned in various forums, but I've never used them and am unsure if it would be a pain to add.  I'm not trying to rewrite the whole thing for a single feature.
Final takeaway: How to update all clients better than polling/ how to do polling efficiently?

A: Yes you are correct. You need sockets. There are bunch of articles over the internet but I would like to give a summary and try to explain why sockets will be the best fit to your requirements.
Sockets are way of achieving two way communication between client and server without the need of polling.
There is a package called Flask-SocketIO

Flask-SocketIO gives Flask applications access to low latency
  bi-directional communications between the clients and the server.

Then for the scenario where you would like to send changes to all the connected client when one client does some work to your database or something similar, you will need to use broadcasting. When a message is sent with the broadcast option enabled, all clients connected to the namespace receive it, including the sender. Here you can find details of the broadcasting using Flask-SocketIO.


Q: Is this C++11 regex error me or the compiler? OK, this isn't the original program I had this problem in, but I duplicated it in a much smaller one. Very simple problem.
main.cpp:
#include <iostream>
#include <regex>
using namespace std;

int main()
{
    regex r1("S");
    printf("S works.\n");
    regex r2(".");
    printf(". works.\n");
    regex r3(".+");
    printf(".+ works.\n");
    regex r4("[0-9]");
    printf("[0-9] works.\n");
    return 0;
}

Compiled successfully with this command, no error messages:
$ g++ -std=c++0x main.cpp

The last line of g++ -v, by the way, is:
gcc version 4.6.1 (Ubuntu/Linaro 4.6.1-9ubuntu3)

And the result when I try to run it:
$ ./a.out
S works.
. works.
.+ works.
terminate called after throwing an instance of 'std::regex_error'
  what():  regex_error
Aborted

It happens the same way if I change r4 to \\s, \\w, or [a-z]. Is this a problem with the compiler? I might be able to believe that C++11's regex engine has different ways of saying "whitespace" or "word character," but square brackets not working is a stretch. Is it something that's been fixed in 4.6.2?
EDIT:
Joachim Pileborg has supplied a partial solution, using an extra regex_constants parameter to enable a syntax that supports square brackets, but neither basic, extended, awk, nor ECMAScript seem to support backslash-escaped terms like \\s, \\w, or \\t.
EDIT 2:
Using raw strings (R"(\w)" instead of "\\w") doesn't seem to work either.

A: Regex support improved between gcc 4.8.2 and 4.9.2. For example, the regex =[A-Z]{3} was failing for me with:

Regex error

After upgrading to gcc 4.9.2, it works as expected.

A: Update: <regex> is now implemented and released in GCC 4.9.0

Old answer:
ECMAScript syntax accepts [0-9], \s, \w, etc, see ECMA-262 (15.10). Here's an example with boost::regex that also uses the ECMAScript syntax by default:
#include <boost/regex.hpp>

int main(int argc, char* argv[]) {
  using namespace boost;
  regex e("[0-9]");
  return argc > 1 ? !regex_match(argv[1], e) : 2;
}

It works:
$ g++ -std=c++0x *.cc -lboost_regex && ./a.out 1

According to the C++11 standard (28.8.2) basic_regex() uses regex_constants::ECMAScript flag by default so it must understand this syntax.

Is this C++11 regex error me or the compiler?

gcc-4.6.1 doesn't support c++11 regular expressions (28.13).

A: The error is because creating a regex by default uses ECMAScript syntax for the expression, which doesn't support brackets. You should declare the expression with the basic or extended flag:
std::regex r4("[0-9]", std::regex_constants::basic);

Edit Seems like libstdc++ (part of GCC, and the library that handles all C++ stuff) doesn't fully implement regular expressions yet. In their status document they say that Modified ECMAScript regular expression grammar is not implemented yet.


Q: Using Win32, GetModuleBaseName() and GetModuleFileNameEx() fail with GetLastError() = 6 when using valid handle First some simple code snippet:
m_hProcessHandle = ::OpenProcess((PROCESS_QUERY_INFORMATION | PROCESS_CREATE_THREAD | PROCESS_DUP_HANDLE | PROCESS_VM_READ | PROCESS_VM_WRITE | PROCESS_VM_OPERATION), FALSE, m_dwProcessIdentifier);
if (NULL != m_hProcessHandle)
{
    if (FALSE != ::OpenProcessToken(m_hProcessHandle, (TOKEN_QUERY | TOKEN_IMPERSONATE | TOKEN_DUPLICATE), &m_hImpersonizationToken))
    {
        wchar_t wszFullExecutableFileName[MAX_PATH];
        if (0 == ::GetModuleBaseName(m_hProcessHandle, NULL, wszFullExecutableFileName, (sizeof(wszFullExecutableFileName)/sizeof(wchar_t))))
        {
            __DebugMessage(L"GetModuleBaseName() failed with GetLastError() = %d", ::GetLastError());
        }
        else
        {
            if (0 == ::GetModuleFileNameEx(m_hProcessHandle, NULL, wszFullExecutableFileName, (sizeof(wszFullExecutableFileName)/sizeof(wchar_t))))
            {
                __DebugMessage(L"GetModuleFileNameEx() failed with GetLastError() = %d", ::GetLastError());
            }
            else
            {
                m_strFullFileName = wszFullExecutableFileName;
            }
        }
    }
}

The OpenProcess() returns a valid handle as does the OpenProcessToken(), but when I call the subsequent GetModuleBaseName() and GetModuleFileNameEx() functions, I get GetLastError() = 6 (The handle is invalid). I am running that code as admin on Windows 7. What gives?
cheers,
GumbyTheBorg

A: You must run this program as administrator in order for it to work correctly.  I just tested it working and GetLastError() = 0 after each line, which means there were no problems.


Q: HelloAndroid.java not created automatically - Hello World Android App in Eclipse I've finally installed the Android SDK/Eclipse and set everything up correctly (I thought), but when I create a new Android project it is not automatically creating the necessary files (HelloAndroid.java is missing).
I just wanted to do the simple HelloAndroid example to verify that everything was properly set up, and obviously I can add the file myself, but my settings are all defaults and I don't understand why this file would not be created for me when every tutorial assumes it is. In fact I cannot find any posts from others about this issue, either.  The HelloAndroidActivity.java file is created, however.
Any ideas why this file is not being created for me? Did I start a new project the wrong way?  I am using Eclipse on OSX 10.7.3.

A: It's HellowWorld.java or HelloWorldActivity.java depends on what you choose at this step. Whatever the name is, as long as the it extends Activity Class you should be OK.


Q: Django fixtures for model from imported application (like django-allauth) I know that is possible to create fixtures file like initial_data.json for my own model. I want to create similar file for tables which are created and used by imported django-allauth application.
I tried:
[
    {
        "model":"allauth.socialaccount.models.SocialApp",
        "pk":1,
        "fields":{
            "id":"1",
            "provider":"facebook",
            "name":"facebook",
            "client_id":"0011223344556677",
            "key":"",
            "secret":"012345678901234567890123456"
        }
    }
]

However it's ends up with error:
python manage.py syncdb
Creating tables ...
Installing custom SQL ...
Installing indexes ...
DeserializationError: Problem installing fixture 'initial_data.json':
  Invalid model identifier: 'allauth.socialaccount.models.SocialApp'

A: I found here that table from model django.contrib.sites.models.Site can be populate using
[
  {
    "model": "sites.site",
    "pk": 1,
    "fields": {
      "domain": "myproject.mydomain.com",
      "name": "My Project"
    }
  }
]

So model allauth.socialaccount.models.SocialApp probably can by populated by:
[
    {
        "model":"socialaccount.socialapp",
        "pk":1,
        "fields":{
            "id":"1",
            "provider":"facebook",
            "name":"facebook",
            "client_id":"0011223344556677",
            "key":"",
            "secret":"012345678901234567890123456"
        }
    }
]

A: Full fixture example, tested with django-allauth 0.19 and Django 1.8:
[
  {
    "model": "sites.site",
    "pk": 1,
    "fields": {
      "domain": "localhost",
      "name": "localhost"
    }
  },
  {
        "model":"socialaccount.socialapp",
        "pk":1,
        "fields":{
            "id":"1",
            "provider":"facebook",
            "name":"facebook",
            "client_id":"0011223344556677",
            "secret":"012345678901234567890123456",
            "key":""
        }
  },
  {
        "model":"socialaccount.socialapp_sites",
        "pk":1,
        "fields":{
            "id":1,
            "socialapp_id":1,
            "site_id":1
        }
  }
]


Q: HTML5 Input tag : what if max,min,step do not fit with each other Let's say you had a job to provide the user with a <input> as this:
<input type="number" min="1" max="11" step="3" value="1"></input>

the result would be increased as this sequence : 1,4,7,10,(13).
you can never see "13" in the box because this number exceeds the maximum value it allows("11"). The max value you can get in this box is 10.
But what if the maximum number you want to show to the user is 11, as specified in your code ?
the expected sequence is like this : 1,4,7,10,11
How to make it ?
Thanks.
EDIT :
Here's a demonstration for the question.

A: The step attribute respects the max, but also restricts the input. If you need more flexibility, try this:
<input list="numbers">

<datalist id="numbers">
  <option value="1">
  <option value="4">
  <option value="7">
  <option value="10">
  <option value="11">
</datalist>

On second thought, that's not great - I would just use the good old-fashioned select tag:
  <select>
    <option>1<option>
    <option>4<option>
    <option>7<option>
    <option>10<option>
    <option>11<option>
  </select>

to get closer to your example. If your data set is contrived to demonstrate a point, these alternatives can be generated programmatically jsut as easy as the one in your example.

A: This is simply not possible using straight HTML5.
There's no HTML5 number feature that increments by 3s and switch to 1s near the last number. HTML rarely deviates from its established rules, no matter what our needs are. And step has pretty strict rules with no similar HTML5 alternatives. You will have to use Javascript or a <select> dropdown.
Easy Imperfect Solution
You can use some Javascript to make this happen. This example uses jQuery in a ready event:
$('input').change(function(){
    var $input = $(this), val = $input.val();
    if (val == 13) {
        $input.attr("step","1");
        $input.val(11);
    } else if (val == 10) {
        $input.attr("step","3");
    } else if (val == 12) {
        $input.val(11);
    }
});

Demo: http://jsfiddle.net/fpm21ej2/1/
There is a flash of the incorrect number "13" right before it changes to "11". I don't know of an event that would intercept this faster though, making this solution imperfect.
Harder Better Solution
Create a custom text field to mimick this incrementing behavior, but using your special number sequence. That means take a number box, add in some up/down buttons (possibly with sprite images), use Javascript to bind them to events that increment this as expected, and validate against the user entering invalid numbers (use the HTML5 pattern attribute).
That will probably take some work, and it needs a bit more time than most of us can volunteer here at StackOverflow. But this should be possible.
Easy Better Solution
Use a <select> dropdown.


Q: Css loop animation I have a problem with the animation, where the words should iterate 'n' number of times
The above mentioned code has 9 different words which has a fade in and out animation one after the other, but this animation is only once . What i need is the loop iterates again and again with the same animation , as the last word ends the first should be loaded.
Here is the html/css code:

    h1.main,p.demos {
     -webkit-animation-delay: 18s;
     -moz-animation-delay: 18s;
     -ms-animation-delay: 18s;
     animation-delay: 18s;
    }
    .sp-container {
     position: relative;
     top: 0px;
     left: 0px;
     width: 100%;
     height: 100%;
     z-index: 0;
     background: -webkit-radial-gradient(rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.3) 35%, rgba(0, 0, 0, 0.7));
     background: -moz-radial-gradient(rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.3) 35%, rgba(0, 0, 0, 0.7));
     background: -ms-radial-gradient(rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.3) 35%, rgba(0, 0, 0, 0.7));
     background: radial-gradient(rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.3) 35%, rgba(0, 0, 0, 0.7));
    }
    .sp-content {
     position: absolute;
     width: 100%;
     height: 100%;
     left: 0px;
     top: 0px;
     z-index: 1000;
    }
    .sp-container h2 {
     position: absolute;
     top: 50%;
     line-height: 100px;
     height: 90px;
     margin-top: -50px;
     font-size: 90px;
     width: 100%;
     text-align: center;
     color: transparent;
     -webkit-animation: blurFadeInOut 3s ease-in backwards;
     -moz-animation: blurFadeInOut 3s ease-in backwards;
     -ms-animation: blurFadeInOut 3s ease-in backwards;
     animation: blurFadeInOut 3s ease-in backwards;
    }

    .sp-container h2.frame-6 {
     -webkit-animation-delay:0s;
     -moz-animation-delay: 0s;
     -ms-animation-delay: 0s;
     animation-delay: 0s;
    }

    .sp-container h2.frame-1 {
     -webkit-animation-delay: 3s;
     -moz-animation-delay: 3s;
     -ms-animation-delay: 3s;
     animation-delay: 3s;
    }
    .sp-container h2.frame-2 {
     -webkit-animation-delay: 6s;
     -moz-animation-delay: 6s;
     -ms-animation-delay: 6s;
     animation-delay: 6s;
    }
    .sp-container h2.frame-3 {
     -webkit-animation-delay: 9s;
     -moz-animation-delay: 9s;
     -ms-animation-delay: 9s;
     animation-delay: 9s;
    }
    .sp-container h2.frame-4 {
     font-size: 200px;
     -webkit-animation-delay: 12s;
     -moz-animation-delay: 12s;
     -ms-animation-delay: 12s;
     animation-delay: 12s;
    }

    .sp-container h2.frame-7 {
     font-size: 200px;
     -webkit-animation-delay: 15s;
     -moz-animation-delay: 15s;
     -ms-animation-delay: 15s;
     animation-delay: 15s;
    }

    .sp-container h2.frame-8 {
     font-size: 200px;
     -webkit-animation-delay: 18s;
     -moz-animation-delay: 18s;
     -ms-animation-delay: 18s;
     animation-delay: 18s;
    }

    .sp-container h2.frame-9 {
     font-size: 200px;
     -webkit-animation-delay: 21s;
     -moz-animation-delay: 21s;
     -ms-animation-delay: 21s;
     animation-delay: 21s;
    }

    .sp-container h2.frame-5 {
     font-size: 200px;
     -webkit-animation-delay: 24s;
     -moz-animation-delay: 24s;
     -ms-animation-delay: 24s;
     animation-delay: 24s;
    }

    /* .sp-container h2.frame-5 span {
     -webkit-animation: blurFadeIn 3s ease-in 12s backwards;
     -moz-animation: blurFadeIn 1s ease-in 12s backwards;
     -ms-animation: blurFadeIn 3s ease-in 12s backwards;
     animation: blurFadeIn 3s ease-in 12s backwards;
     color: transparent;
     text-shadow: 0px 0px 1px #fff;
    } */
    .sp-container h2.frame-5 span:nth-child(2) {
     -webkit-animation-delay: 13s;
     -moz-animation-delay: 13s;
     -ms-animation-delay: 13s;
     animation-delay: 13s;
    }
    .sp-container h2.frame-5 span:nth-child(3) {
     -webkit-animation-delay: 14s;
     -moz-animation-delay: 14s;
     -ms-animation-delay: 14s;
     animation-delay: 14s;
    }
    .sp-globe {
     position: absolute;
     width: 282px;
     height: 273px;
     left: 50%;
     top: 50%;
     margin: -137px 0 0 -141px;
     background: transparent url(http://web-sonick.zz.mu/images/sl/globe.png) no-repeat top left;
     -webkit-animation: fadeInBack 3.6s linear 14s backwards;
     -moz-animation: fadeInBack 3.6s linear 14s backwards;
     -ms-animation: fadeInBack 3.6s linear 14s backwards;
     animation: fadeInBack 3.6s linear 14s backwards;
     -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=30)";
     filter: alpha(opacity=30);
     opacity: 0.3;
     -webkit-transform: scale(5);
     -moz-transform: scale(5);
     -o-transform: scale(5);
     -ms-transform: scale(5);
     transform: scale(5);

    }
    .sp-circle-link {
     position: absolute;
     left: 50%;
     bottom: 100px;
     margin-left: -50px;
     text-align: center;
     line-height: 100px;
     width: 100px;
     height: 100px;
     background: #fff;
     color: #3f1616;
     font-size: 25px;
     -webkit-border-radius: 50%;
     -moz-border-radius: 50%;
     border-radius: 50%;
     -webkit-animation: fadeInRotate 1s linear 16s backwards;
     -moz-animation: fadeInRotate 1s linear 16s backwards;
     -ms-animation: fadeInRotate 1s linear 16s backwards;
     animation: fadeInRotate 1s linear 16s backwards;
     -webkit-transform: scale(1) rotate(0deg);
     -moz-transform: scale(1) rotate(0deg);
     -o-transform: scale(1) rotate(0deg);
     -ms-transform: scale(1) rotate(0deg);
     transform: scale(1) rotate(0deg);
    }
    .sp-circle-link:hover {
     background: #85373b;
     color: #fff;
    }
    /**/
    @-webkit-keyframes blurFadeInOut{
     0%{
      opacity: 0;
      text-shadow: 0px 0px 40px #fff;
      -webkit-transform: scale(1.3);
     }
     20%,75%{
      opacity: 1;
      text-shadow: 0px 0px 1px #fff;
      -webkit-transform: scale(1);
     }
     100%{
      opacity: 0;
      text-shadow: 0px 0px 50px #fff;
      -webkit-transform: scale(0);
     }
    }
    @-webkit-keyframes blurFadeIn{
     0%{
      opacity: 0;
      text-shadow: 0px 0px 40px #fff;
      -webkit-transform: scale(1.3);
     }
     50%{
      opacity: 0.5;
      text-shadow: 0px 0px 10px #fff;
      -webkit-transform: scale(1.1);
     }
     100%{
      opacity: 1;
      text-shadow: 0px 0px 1px #fff;
      -webkit-transform: scale(1);
     }
    }
    @-webkit-keyframes fadeInBack{
     0%{
      opacity: 0;
      -webkit-transform: scale(0);
     }
     50%{
      opacity: 0.4;
      -webkit-transform: scale(2);
     }
     100%{
      opacity: 0.2;
      -webkit-transform: scale(5);
     }
    }
    @-webkit-keyframes fadeInRotate{
     0%{
      opacity: 0;
      -webkit-transform: scale(0) rotate(360deg);
     }
     100%{
      opacity: 1;
      -webkit-transform: scale(1) rotate(0deg);
     }
    }
    /**/
    @-moz-keyframes blurFadeInOut{
     0%{
      opacity: 0;
      text-shadow: 0px 0px 40px #fff;
      -moz-transform: scale(1.3);
     }
     20%,75%{
      opacity: 1;
      text-shadow: 0px 0px 1px #fff;
      -moz-transform: scale(1);
     }
     100%{
      opacity: 0;
      text-shadow: 0px 0px 50px #fff;
      -moz-transform: scale(0);
     }
    }
    @-moz-keyframes blurFadeIn{
     0%{
      opacity: 0;
      text-shadow: 0px 0px 40px #fff;
      -moz-transform: scale(1.3);
     }
     100%{
      opacity: 1;
      text-shadow: 0px 0px 1px #fff;
      -moz-transform: scale(1);
     }
    }
    @-moz-keyframes fadeInBack{
     0%{
      opacity: 0;
      -moz-transform: scale(0);
     }
     50%{
      opacity: 0.4;
      -moz-transform: scale(2);
     }
     100%{
      opacity: 0.2;
      -moz-transform: scale(5);
     }
    }
    @-moz-keyframes fadeInRotate{
     0%{
      opacity: 0;
      -moz-transform: scale(0) rotate(360deg);
     }
     100%{
      opacity: 1;
      -moz-transform: scale(1) rotate(0deg);
     }
    }
    /**/
    @keyframes blurFadeInOut{
     0%{
      opacity: 0;
      text-shadow: 0px 0px 40px #fff;
      transform: scale(1.3);
     }
     20%,75%{
      opacity: 1;
      text-shadow: 0px 0px 1px #fff;
      transform: scale(1);
     }
     100%{
      opacity: 0;
      text-shadow: 0px 0px 50px #fff;
      transform: scale(0);
     }
    }
    @keyframes blurFadeIn{
     0%{
      opacity: 0;
      text-shadow: 0px 0px 40px #fff;
      transform: scale(1.3);
     }
     50%{
      opacity: 0.5;
      text-shadow: 0px 0px 10px #fff;
      transform: scale(1.1);
     }
     100%{
      opacity: 1;
      text-shadow: 0px 0px 1px #fff;
      transform: scale(1);
     }
    }
    @keyframes fadeInBack{
     0%{
      opacity: 0;
      transform: scale(0);
     }
     50%{
      opacity: 0.4;
      transform: scale(2);
     }
     100%{
      opacity: 0.2;
      transform: scale(5);
     }
    }
    @keyframes fadeInRotate{
     0%{
      opacity: 0;
      transform: scale(0) rotate(360deg);
     }
     100%{
      opacity: 1;
      transform: scale(1) rotate(0deg);
     }
    }

WE  STAND  FOR

INNOVATION

QUALITY

RELIABILITY

SAFETY

VALUES

HARMONY

UNITY

CUSTOMER

A: I don't really understand your code, but what you can do is to create an animation for each element and define the same duration for each element of the animation (the total animation time).
After that, you just have to handle "what is displayed when" using %
In my example, I will handle 4 elements, so 25% of the total time for each one (and +/-5% for fadeIn fadeOut)

.el-1, .el-2, .el-3, .el-4 {
  position: absolute;
  width: 100px;
  height: 100px;
  animation-duration: 10s; /* Total time */
  animation-iteration-count: infinite;
  animation-delay: 0; /* by default */
}
.el-1 {
  animation-name: example-1;
  background: red;
}
.el-2 {
  animation-name: example-2;
  background: green;
}
.el-3 {
  animation-name: example-3;
  background: blue;
}
.el-4 {
  animation-name: example-4;
  background: yellow;
}

@keyframes example-1 {
    0%   {opacity: 0;}
    5%   {opacity: 1;}
    20%  {opacity: 1;}
    30%  {opacity: 0;}
    100% {opacity: 0;}
}
@keyframes example-2 {
    0%   {opacity: 0;}
    20%  {opacity: 0;}
    30%  {opacity: 1;}
    40%  {opacity: 1;}
    60%  {opacity: 0;}
    100% {opacity: 0;}
}
@keyframes example-3 {
    0%   {opacity: 0;}
    40%  {opacity: 0;}
    60%  {opacity: 1;}
    70%  {opacity: 1;}
    80%  {opacity: 0;}
    100% {opacity: 0;}
}
@keyframes example-4 {
    0%   {opacity: 0;}
    70%  {opacity: 0;}
    80%  {opacity: 1;}
    95%  {opacity: 1;}
    100% {opacity: 0;}
}

1

2

3

4


Q: Neo4j Cypher query empty collect makes the entire result empty I have been facing wierd problem, I have tried to get data from the neo4j graph that I have built.Here is my query
MATCH (u1:User {user_id: 4})-[:FOLLOWS]->(u2:User)-[]->(r1:Rest{city_id: 1})
WITH COLLECT ({ REST: r1.res_id}) as rows
MATCH (u1:User {user_id: 4})-[rel]->(r2:Rest{city_id: 1})
WHERE NOT (u1:User {user_id: 4})-[rel : BEEN_THERE | ADD_REVIEW]->(r2:Rest{city_id: 1})
WITH rows + COLLECT ({ REST: r2.res_id}) AS allrows
UNWIND allrows as row
RETURN row.REST as RESTAURANT_ID, count(row.REST) as COUNT
ORDER BY COUNT desc
LIMIT 15;

However when the result of COLLECT ({ REST: r2.res_id}) are empty the entire result becomes empty. Also the query is unable to identify rows from 1st match and return undefined rows. Please let me know. Thanks!

A: If the pattern doesn't match any path, the result will be empty indeed.
You have to split the MATCH in 2 and make the second one OPTIONAL, or in your actual case, stop matching the same u1 node over and over again:
MATCH (u1:User {user_id: 4})
OPTIONAL MATCH (u1)-[:FOLLOWS]->(:User)-->(r1:Rest {city_id: 1})
WITH u1, collect({ REST: r1.res_id }) AS rows
OPTIONAL MATCH (u1)-->(r2:Rest {city_id: 1})
WHERE NOT (u1)-[:BEEN_THERE | ADD_REVIEW]->(r2)
WITH rows + collect({ REST: r2.res_id }) AS allrows
UNWIND allrows as row
RETURN row.REST AS RESTAURANT_ID, count(row.REST) AS COUNT
ORDER BY COUNT desc
LIMIT 15

I'm not sure about the first OPTIONAL MATCH in your case (you only mention the second collect as being a blocker), but if you want the aggregation of both patterns where each can be empty, here you go.


Q: FragmentTabPager not working at all I'm trying to implement FragmentTabPager Activity, but it doesn't run at all. Once I call the activity the app stops immediately. I've used tried multiple sources of code/tutorial including developers.android, but the same problem happens with all of them. And from what I understand, no one has faced the same problem(at least they haven't written about it). THis leads me to believe that I am making some stupid mistake. I've spent over 2 days on this. Heres the code for my fragmentTabPager activity:
package com.my.pack;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TabHost;
import android.widget.TabWidget;

import java.util.ArrayList;

public class FragmentTabsPager extends FragmentActivity {
    TabHost mTabHost;
    ViewPager mViewPager;
    TabsAdapter mTabsAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.tabs_viewpager_layout);
        mTabHost = (TabHost) findViewById(android.R.id.tabhost);
        mTabHost.setup();

        mViewPager = (ViewPager) findViewById(R.id.pager);

        // Create our tab adapter
        mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);

        // add our tabs to the adapter
        mTabsAdapter.addTab(mTabHost.newTabSpec("forex").setIndicator("Forex"),
                Forex.class, null);
        mTabsAdapter.addTab(mTabHost.newTabSpec("stocks")
                .setIndicator("Stocks"), Stocks.class, null);
        mTabsAdapter.addTab(
                mTabHost.newTabSpec("commodities").setIndicator("Commodities"),
                Commodities.class, null);
        /*
         * mTabsAdapter.addTab(mTabHost.newTabSpec("throttle").setIndicator(
         * "Throttle"), LoaderThrottleSupport.ThrottledLoaderListFragment.class,
         * null);
         */

        if (savedInstanceState != null) {
            // restore the last selected tab if we can
            mTabHost.setCurrentTabByTag(savedInstanceState.getString("tab"));
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("tab", mTabHost.getCurrentTabTag());
    }

    public static class TabsAdapter extends FragmentPagerAdapter implements
            TabHost.OnTabChangeListener, ViewPager.OnPageChangeListener {
        private final Context mContext;
        private final TabHost mTabHost;
        private final ViewPager mViewPager;
        private final ArrayList mTabs = new ArrayList();

        static final class TabInfo {
            private final String tag;
            private final Class clss;
            private final Bundle args;

            TabInfo(String _tag, Class _class, Bundle _args) {
                tag = _tag;
                clss = _class;
                args = _args;
            }
        }

        static class DummyTabFactory implements TabHost.TabContentFactory {
            private final Context mContext;

            public DummyTabFactory(Context context) {
                mContext = context;
            }

            public View createTabContent(String tag) {
                View v = new View(mContext);
                v.setMinimumWidth(0);
                v.setMinimumHeight(0);
                return v;
            }
        }

        public TabsAdapter(FragmentActivity activity, TabHost tabHost,
                ViewPager pager) {
            super(activity.getSupportFragmentManager());
            mContext = activity;
            mTabHost = tabHost;
            mViewPager = pager;
            mTabHost.setOnTabChangedListener(this);
            mViewPager.setAdapter(this);
            mViewPager.setOnPageChangeListener(this);
        }

        public void addTab(TabHost.TabSpec tabSpec, Class clss, Bundle args) {
            tabSpec.setContent(new DummyTabFactory(mContext));
            String tag = tabSpec.getTag();

            TabInfo info = new TabInfo(tag, clss, args);
            mTabs.add(info);
            mTabHost.addTab(tabSpec);
            notifyDataSetChanged();
        }

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

        @Override
        public Fragment getItem(int position) {
            TabInfo info = (TabInfo) mTabs.get(position);
            // Create a new fragment if necessary.
            return Fragment.instantiate(mContext, info.clss.getName(),
                    info.args);
        }

        public void onTabChanged(String tabId) {
            // called when the user clicks on a tab.
            int position = mTabHost.getCurrentTab();
            mViewPager.setCurrentItem(position);
        }

        public void onPageScrolled(int position, float positionOffset,
                int positionOffsetPixels) {
        }

        public void onPageSelected(int position) {

            TabWidget widget = mTabHost.getTabWidget();
            int oldFocusability = widget.getDescendantFocusability();
            widget.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
            mTabHost.setCurrentTab(position);
            widget.setDescendantFocusability(oldFocusability);
        }

        public void onPageScrollStateChanged(int state) {
        }
    }
}

And my manifest looks like:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.my.pack"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".Main"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".FragmentTabsPager"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.FRAGMENTTABSPAGER" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
        <activity
            android:name=".Stocks"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.STOCKS" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
        <activity
            android:name=".Commodities"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.COMMODITIES" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
        <activity
            android:name=".Forex"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.FOREX" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
    </application>

</manifest>

The xml of tabs_viewpager_layout file:
<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TabWidget
        android:id="@android:id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0"
        android:orientation="horizontal" />

    <FrameLayout
        android:id="@android:id/tabcontent"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_weight="0" />

    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />
</LinearLayout>

And my main from which I wish to call my fragmentTab activity:
package com.my.pack;

    import android.app.Activity;
    import android.content.Intent;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;

    public class Main extends Activity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        Button b1 = (Button) findViewById(R.id.button1);
        b1.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent myintent = new Intent(Main.this, FragmentTabsPager.class);
                startActivity(myintent);
            }
        });
    }

}

I know my 3 Forex, stock, etc. pager activites are running without a hitch. I checked by changing the intent in main to Forex.class and all 3 work fine. I also thought that the activity had to be a LAUNCHER activity and tried that only to fail. Thanks in advance. Any help would be GREATLY appreciated.
My logcat is..
04-08 19:05:24.839: D/AndroidRuntime(1332): Shutting down VM
04-08 19:05:24.839: W/dalvikvm(1332): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
04-08 19:05:24.869: E/AndroidRuntime(1332): FATAL EXCEPTION: main
04-08 19:05:24.869: E/AndroidRuntime(1332): java.lang.ClassCastException: com.my.pack.Forex
04-08 19:05:24.869: E/AndroidRuntime(1332):     at android.support.v4.app.Fragment.instantiate(Fragment.java:384)
04-08 19:05:24.869: E/AndroidRuntime(1332):     at com.my.pack.FragmentTabsPager$TabsAdapter.getItem(FragmentTabsPager.java:124)
04-08 19:05:24.869: E/AndroidRuntime(1332):     at android.support.v4.app.FragmentPagerAdapter.instantiateItem(FragmentPagerAdapter.java:95)
04-08 19:05:24.869: E/AndroidRuntime(1332):     at android.support.v4.view.ViewPager.addNewItem(ViewPager.java:649)
04-08 19:05:24.869: E/AndroidRuntime(1332):     at android.support.v4.view.ViewPager.populate(ViewPager.java:783)
04-08 19:05:24.869: E/AndroidRuntime(1332):     at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1016)
04-08 19:05:24.869: E/AndroidRuntime(1332):     at android.view.View.measure(View.java:8171)
04-08 19:05:24.869: E/AndroidRuntime(1332):     at android.widget.LinearLayout.measureVertical(LinearLayout.java:526)
04-08 19:05:24.869: E/AndroidRuntime(1332):     at android.widget.LinearLayout.onMeasure(LinearLayout.java:304)
04-08 19:05:24.869: E/AndroidRuntime(1332):     at android.view.View.measure(View.java:8171)
04-08 19:05:24.869: E/AndroidRuntime(1332):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3132)
04-08 19:05:24.869: E/AndroidRuntime(1332):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:245)
04-08 19:05:24.869: E/AndroidRuntime(1332):     at android.view.View.measure(View.java:8171)
04-08 19:05:24.869: E/AndroidRuntime(1332):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3132)
04-08 19:05:24.869: E/AndroidRuntime(1332):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:245)
04-08 19:05:24.869: E/AndroidRuntime(1332):     at android.view.View.measure(View.java:8171)
04-08 19:05:24.869: E/AndroidRuntime(1332):     at android.widget.LinearLayout.measureVertical(LinearLayout.java:526)
04-08 19:05:24.869: E/AndroidRuntime(1332):     at android.widget.LinearLayout.onMeasure(LinearLayout.java:304)
04-08 19:05:24.869: E/AndroidRuntime(1332):     at android.view.View.measure(View.java:8171)
04-08 19:05:24.869: E/AndroidRuntime(1332):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3132)
04-08 19:05:24.869: E/AndroidRuntime(1332):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:245)
04-08 19:05:24.869: E/AndroidRuntime(1332):     at android.view.View.measure(View.java:8171)
04-08 19:05:24.869: E/AndroidRuntime(1332):     at android.view.ViewRoot.performTraversals(ViewRoot.java:801)
04-08 19:05:24.869: E/AndroidRuntime(1332):     at android.view.ViewRoot.handleMessage(ViewRoot.java:1727)
04-08 19:05:24.869: E/AndroidRuntime(1332):     at android.os.Handler.dispatchMessage(Handler.java:99)
04-08 19:05:24.869: E/AndroidRuntime(1332):     at android.os.Looper.loop(Looper.java:123)
04-08 19:05:24.869: E/AndroidRuntime(1332):     at android.app.ActivityThread.main(ActivityThread.java:4627)
04-08 19:05:24.869: E/AndroidRuntime(1332):     at java.lang.reflect.Method.invokeNative(Native Method)
04-08 19:05:24.869: E/AndroidRuntime(1332):     at java.lang.reflect.Method.invoke(Method.java:521)
04-08 19:05:24.869: E/AndroidRuntime(1332):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
04-08 19:05:24.869: E/AndroidRuntime(1332):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
04-08 19:05:24.869: E/AndroidRuntime(1332):     at dalvik.system.NativeStart.main(Native Method)
04-08 19:05:27.898: I/Process(1332): Sending signal. PID: 1332 SIG: 9

A: Do you have duplicate android:id tags in any of those three activities?  I've read that such a situation could cause an issue.
Ah, here's the link to where I read that:  ClassCastException


Q: Inserting additional code into the onclick attribute of a submit button using jquery I'm having trouble trying to properly insert additional code into the onclick attribute of a submit button.  I don't want to overwrite anything within the onclick but just add additional code.   I have successfully inserted the code needed but when I look at the source code of the button it shows some additional functionality that shouldn't be there so i don't think I have it written out properly.
Here's the button:
<input id='TESTFrmSubmit' type='submit' value='Submit' name='submitButton' onclick='formSubmit(document.getElementById("TESTForm_1001")); return false;' />

The additional code I want to insert into the onclick attribute is:
'_gaq.push(['_trackEvent', 'Whitepaper Campaign', 'Submit Button','conceptshareexample.pdf'']);'

The jquery I have that inserts the additonal code into the onclick attribute is:
$(document).ready(function(){

   $("#TESTFrmSubmit").attr ("onclick", function() {

return this.onclick + "'_gaq.push(['_trackEvent', 'Whitepaper Campaign', 'Submit Button','TESTexample.pdf'']);'";

  });

  });

The problem I'm having is that when i view the source code of the button, it contains
function onclick(event) within the onclick displaying it like so:
onclick="function onclick(event){ formSubmit(document.getElementById("TESTForm_1010")); return false; }_gaq.push(['_trackEvent', 'Whitepaper Campaign', 'Submit Button','TESTexample.pdf'']);"

I need it to display it like this without the function onclick(event):
onclick="{formSubmit(document.getElementById("TESTForm_1010")); return false; }_gaq.push(['_trackEvent', 'Whitepaper Campaign', 'Submit Button','TESTexample.pdf'']);"

Please help!  this has been racking my brain...

A: Instead of setting .attr('onclick', you can bind into the event handler directly:
$('#mktFrmSubmit').click(function ()
{
    doSomething();
    alert('hi');
}
$('#mktFrmSubmit').click(function ()
{
    alert('We can also bind to .click multiple times, and it adds events');
    // Instead of just overwriting them
}

Now clicking #mktFrmSubmit will fire both those click handlers.

A: this.onclick

is returning the
function onclick(event) {...

To accomplish what you want, use this:
$(document).ready(function(){

$("#mktFrmSubmit").attr ("onclick", function() {

_gaq.push(['_trackEvent', 'Whitepaper Campaign', 'Submit Button','conceptshareexample.pdf']);
formSubmit(document.getElementById("TESTForm_1001")); return false;

});

});


Q: JavaScript Double Select I have a problem with 3 Select Box's I have. The second and third should populate after select the first and second select box.
After select a value from Select Box 1, it populates Select Box 2.
After select a value from Select Box 2, it populates Select Box 3.
I have two problems with my code:

*

*It populates automatically the second select box based on first value, but doesn't populate the third select box

*After change it populates the select box, but If I change the first select box, it updates the second select box but the third isn't updated based on the values of the second select box. It only populates after I change the value in the second select box.

My Code:
<script type="text/javascript">
jQuery(document).ready(function() {
    $("#category").change(function(){
        getSubCat();//get sub category after change event
    });
    $("#subcategory").change(function(){
        getSubSubCat(); //get sub category after change event
    });
    getSubCat();//get sub category after page load
    getSubSubCat();
    function getSubCat(){
        var selectedCategory = $("#category option:selected").val();
        $.ajax({
            type: "POST",
            url: "subcat.php",
            data: { category : selectedCategory }
        }).done(function(data){
            $("#subcategory").html(data);
        });
    }
    function getSubSubCat(){
        var selectedSubCategory = $("#subcategory option:selected").val();
        $.ajax({
            type: "POST",
            url: "subsubcat.php",
            data: { subcategory : selectedSubCategory }
        }).done(function(data){
            $("#subsubcategory").html(data);
        });
    }
});
</script>

Can you help me please?

A: The .done() function of getSubCat() should call getSubSubCat().
function getSubCat(){
    var selectedCategory = $("#category option:selected").val();
    $.ajax({
        type: "POST",
        url: "subcat.php",
        data: { category : selectedCategory }
    }).done(function(data){
        $("#subcategory").html(data);
        getSubSubCat();
    });
}

When you call getSubSubCat() during page load, getSubCat() hasn't finished yet (because AJAX is asynchronous), so none of its changes to the second menu have been made.


Q: Make the BODY DIV Fill the Available Area I'm working on a brand new website and I'm trying to just get the basic layout going. I am using the ASP.NET MVC 4 generated HTML and I would like to get the DIV named body to fill the available space after making room for the header and thus anchoring the footer to the bottom of the browser window. However, what I'm getting right now is three panels just stacked on top of each other.
I would like a solution that would work if the browser supported HTML5 and one if it didn't
Please note I've inlined comments in the CSS to try and explain what I've tried.
HTML
<!DOCTYPE html>

        <meta charset="utf-8" />
        <title>@ViewBag.Title - Title</title>
        <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
        <meta name="viewport" content="width=device-width" />
        @Styles.Render("~/Content/css")

@Html.ActionLink("Title", "Index", "Home")

            @RenderSection("featured", required: false)

                @RenderBody()

© @DateTime.Now.Year - ACME. All rights reserved.

Facebook

Twitter

        @RenderSection("scripts", required: false)

CSS
body {
    /* I'VE TRIED BOTH OF THE FOLLOWING TO SEE IF THE BODY ITSELF WOULD SPAN */
    /* WITH NO OTHER CSS APPLIED TO THE body ELEMENT */

    /*height: fill-available;*/
    /*height: 100%*/
}

/* general layout
----------------------------------------------------------*/
.float-left {
    float: left;
}

.float-right {
    float: right;
}

.clear-fix:after {
    content: ".";
    clear: both;
    display: block;
    height: 0;
    visibility: hidden;
}

/* main layout
----------------------------------------------------------*/
.content-wrapper {
    margin: 0 auto;
    max-width: 960px;
}

#body {
    background-color: #efeeef;
    clear: both;
    padding-bottom: 35px;

    /* I'VE TRIED BOTH OF THE FOLLOWING TO SEE IF I COULD GET THIS ELEMENT TO SPAN */
    /* WITHOUT ANY OTHER CSS APPLIED TO THE body TAG */

    /*height: fill-available;*/
    /*height: 100%*/
}

.main-content {
    /*background: url("../Images/accent.png") no-repeat;*/
    padding-left: 10px;
    padding-top: 30px;
}

.featured + .main-content {
    /*background: url("../Images/heroAccent.png") no-repeat;*/
}

footer {
    clear: both;
    background-color: #e2e2e2;
    font-size: .8em;
    height: 100px;
}

/* site title
----------------------------------------------------------*/
.site-title {
    color: #c8c8c8;
    font-family: Rockwell, Consolas, "Courier New", Courier, monospace;
    font-size: 2.3em;
    margin: 20px 0;
}

    .site-title a, .site-title a:hover, .site-title a:active {
        background: none;
        color: #c8c8c8;
        outline: none;
        text-decoration: none;
    }

/* social
----------------------------------------------------------*/
ul#social li {
    display: inline;
    list-style: none;
}

    ul#social li a {
        color: #999;
        text-decoration: none;
    }

a.facebook, a.twitter {
    display: block;
    float: left;
    height: 24px;
    padding-left: 17px;
    text-indent: -9999px;
    width: 16px;
}

a.facebook {
    background: url("../Images/facebook.png") no-repeat;
}

a.twitter {
    background: url("../Images/twitter.png") no-repeat;
}

A: Just snap the header and footer at the bottom of the page using fixed positioning.
header, footer{ position:fixed; left:0; right:0; z-index:1; }
header{ top:0; }
footer{ bottom:0; }

Then you can give your body the background your div#body had before. The div gets no background and will expand as much as needed.
div#body{ background:none; }
body{ background:#eee; }

This will look like the div would fill the remaining space of the page. Finally give your header and footer a background so that you can't see the background of the body under it.
header, footer{ background:#fff; }

By the way I would suggest removing body margins. body{ margin:0; }

A: I believe it's a bit impossible to do that with just CSS. You can make a webpage with 100% height like this:
html{
    height: 100%;
}

body{
    height: 100%;
}

#body{
    height: 100%;
}

And then for header, body and footer you can do like this:
header{
  height: 100px;
  left: 0;
  position: absolute;
  top: 0;
  width: 100%;
  background-color: #f00;
}

#body{
  bottom: 100px;
  left: 0;
  position: absolute;
  right: 0;
  top: 100px;
  background-color: #fff;
}

footer{
  bottom: 0;
  height: 100px;
  left: 0;
  position: absolute;
  width: 100%;
  background-color: #ff0;
}

It might work for a bit, but it'll break at some point. When you resize your browser, it'll be running out of room for your #body. If you want a better solution, you should use javascript. In your javascript, calculate how much space you have for your #body, then either adjust the height of header and footer. Or adjust the #body instead.


Q: Passing a pointer for a dynamic runtime function I'm trying to write a generic utility function for a class that applies a function to each element of a vector with the only input argument being the value of that element. The idea being that I can use that to support scalar addition/multiplication as well as user-specified functions without duplicating too much code. It works fine for the user-specified functions, but I'm struggling with how the best implement it for scalar addition/multiplication.
The code below is a simplified version of what I'm playing around with. It works fine, but what I want to be able to do is have the "5" in the lambda expression be a variable passed in separately, but not necessarily passed into "apply_f". So keep apply_f only taking a vector an a function pointer. I'm aware of the captures field for lambda expressions, but I was having trouble passing a lambda function with a capture into another function. I'm also aware of something like std::bind, but couldn't get that to work either.
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

void apply_f(vector<double>& vec, double (*f)(double)) {
    transform(vec.begin(), vec.end(), vec.begin(), f);
}

int main() {
    vector<double> x {1, 2, 3};

    auto f = [](double x){ return x + 5; };
    apply_f(x, f);

    cout << x[0] << endl;
    cout << x[1] << endl;
    cout << x[2] << endl;
}

A: Simply take a parameter with a unique type:
template <class F>
void apply_f(vector<double>& vec, F f) {
    transform(vec.begin(), vec.end(), vec.begin(), f);
}

Not only it will work, but you will get way better performance since the compiler knows the actual type being passed.

A: Unfortunately, lambdas are not just pointers to functions (because they can have state, for instance). You can change your code to use a std::function<double(double) instead of a double(*)(double), and this can capture a lambda (you may need to pass std::cref(f) instead of just f).


Q: Peewee ArrayField error When I create my table based on a model without an ArrayField, I get no errors.
When I add:
images = ArrayField(CharField)

I get:
  Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.6/site-packages/peewee.py", line 5037, in create_table
    db.create_table(cls)
  File "/usr/local/lib/python3.6/site-packages/peewee.py", line 3914, in create_table
    return self.execute_sql(*qc.create_table(model_class, safe))
  File "/usr/local/lib/python3.6/site-packages/peewee.py", line 3837, in execute_sql
    self.commit()
  File "/usr/local/lib/python3.6/site-packages/peewee.py", line 3656, in __exit__
    reraise(new_type, new_type(*exc_args), traceback)
  File "/usr/local/lib/python3.6/site-packages/peewee.py", line 135, in reraise
    raise value.with_traceback(tb)
  File "/usr/local/lib/python3.6/site-packages/peewee.py", line 3830, in execute_sql
    cursor.execute(sql, params or ())
peewee.OperationalError: near "[]": syntax error

Can anyone point out why and provide a solution?

A: What database driver are you using? ArrayField requires postgresql.


Q: (python) solving transcendental equation i need to solve following equation:
0 = -1 / x**0.5) - 2 * log((alpha * x**0.5) + beta)

alpha and beta are given, i just need to iterate x until a certain extent.
I'm not a great python programmer, but like to implement this one.
How might this be possible?
Best regards

A: The smartest to do would be to implement a solve function like Stanislav recommended. You can't just iterate over values of x until the equation reaches 0 due to Floating Point Arithmetic. You would have to .floor or .ceil your value to avoid an infinity loop. An example of this would be something like:
x = 0

while True:
    x += 0.1
    print(x)
    if x == 10:
        break

Here you'd think that x eventually reaches 10 when it adds 0.1 to 9.9, but this will continue forever. Now, I don't know if your values are integers or floats, but what I'm getting at is: Don't iterate. Use already built solve libraries.


Q: Why do null columns behave differently with the count aggragate function? In oracle, we have a task to count the number of rows that have a specific null collumn.
I have the query:
select count(MY_COL) from My_Table where MY_COL is null;

this returns zero results.
Why does this return zero results and the query
select count(*) from My_Table where MY_COL is null;

return the correct results?

A: Both results are correct.
select count(col_name) counts the records where col_name is not null while select count(*) counts all records, regardless of any null values.
This is documented on Tahiti:

If you specify expr, then COUNT returns the number of rows where expr is not null. You can count either all rows, or only distinct values of expr.
If you specify the asterisk (*), then this function returns all rows, including duplicates and nulls.
COUNT never returns null.


Q: Can't install python, pip related apps through Ansible I am using below ansible yml file to install python, pip, etc.
roles/python/main.yml:
---

- name: python
  apt:
    pkg: python

- name: python-pip
  apt:
    pkg: python-pip

- name: mongopy
  pip:
    pkg: mongopy

- name: mtools
  pip:
    pkg: mtools

when I run ansible-playbook on this script, I get below
PLAY [ec2] ***********************************************************************************************************************************************************************************************

TASK [Gathering Facts] ***********************************************************************************************************************************************************************************
ok: [xxxxx.ap-southeast-2.compute.amazonaws.com]

PLAY RECAP ***********************************************************************************************************************************************************************************************
xxxxxap-southeast-2.compute.amazonaws.com : ok=1    changed=0    unreachable=0    failed=0

there is no error on them but I checked these apps are not installed on the remote host. What wrong with my yml file? Is there any place I can check what the error is?
below is my playbook:
python.yml:
---

- hosts: ec2
  remote_user: ubuntu
  roles:
    - python

below is the command I run:
ansible-playbook -i hosts python.yml

A: There are no tasks in your python role. Please have a look at the role structure.

If roles/x/tasks/main.yml exists, tasks listed therein will be added to the play

Tasks file (main.yml) should be placed in the tasks subdirectory of the role, not in the main role's directory.

And this has nothing to do with how you described the problem (installing Python or Pip). Even if you replaced the tasks with a single debug task which displays Hello world by default, it would not run.


Q: SpringBoot project gradle build 'bootRepackage' task fails because it is unable to rename jar When running 'gradle clean build' on my spring boot project (version 1.3.6.RELEASE) on windows 10 (as administrator), the build fails on the 'bootRepackage' task on one of my modules with the following stacktrace
:myProjectModule:findMainClass
:myProjectModule:bootRepackage FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':myProjectModule:bootRepackage'.
> Unable to rename 'D:\dev\myProject\myProjectModule\build\libs\myProjectModule-0.0.8-SNAPSHOT.jar' to 'D:\dev\myProject\myProjectModule\build\libs\myProjectModule-0.0.8-SNAPSHOT.jar.original'

* Try:
Run with --info or --debug option to get more log output.

* Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':myProjectModule:bootRepackage'.
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:69)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:46)
        at org.gradle.api.internal.tasks.execution.PostExecutionAnalysisTaskExecuter.execute(PostExecutionAnalysisTaskExecuter.java:35)
        at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:66)
        at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
        at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:52)
        at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
        at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:53)
        at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:203)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:185)
        at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.processTask(AbstractTaskPlanExecutor.java:66)
        at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.run(AbstractTaskPlanExecutor.java:50)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor.process(DefaultTaskPlanExecutor.java:25)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:110)
        at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:37)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
        at org.gradle.execution.DefaultBuildExecuter.access$000(DefaultBuildExecuter.java:23)
        at org.gradle.execution.DefaultBuildExecuter$1.proceed(DefaultBuildExecuter.java:43)
        at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:32)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:30)
        at org.gradle.initialization.DefaultGradleLauncher$4.run(DefaultGradleLauncher.java:153)
        at org.gradle.internal.Factories$1.create(Factories.java:22)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:91)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:53)
        at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:150)
        at org.gradle.initialization.DefaultGradleLauncher.access$200(DefaultGradleLauncher.java:32)
        at org.gradle.initialization.DefaultGradleLauncher$1.create(DefaultGradleLauncher.java:98)
        at org.gradle.initialization.DefaultGradleLauncher$1.create(DefaultGradleLauncher.java:92)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:91)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:63)
        at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:92)
        at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:83)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter$DefaultBuildController.run(InProcessBuildActionExecuter.java:99)
        at org.gradle.tooling.internal.provider.ExecuteBuildActionRunner.run(ExecuteBuildActionRunner.java:28)
        at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:48)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:30)
        at org.gradle.launcher.exec.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:81)
        at org.gradle.launcher.exec.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:46)
        at org.gradle.launcher.exec.DaemonUsageSuggestingBuildActionExecuter.execute(DaemonUsageSuggestingBuildActionExecuter.java:51)
        at org.gradle.launcher.exec.DaemonUsageSuggestingBuildActionExecuter.execute(DaemonUsageSuggestingBuildActionExecuter.java:28)
        at org.gradle.launcher.cli.RunBuildAction.run(RunBuildAction.java:43)
        at org.gradle.internal.Actions$RunnableActionAdapter.execute(Actions.java:173)
        at org.gradle.launcher.cli.CommandLineActionFactory$ParseAndBuildAction.execute(CommandLineActionFactory.java:239)
        at org.gradle.launcher.cli.CommandLineActionFactory$ParseAndBuildAction.execute(CommandLineActionFactory.java:212)
        at org.gradle.launcher.cli.JavaRuntimeValidationAction.execute(JavaRuntimeValidationAction.java:35)
        at org.gradle.launcher.cli.JavaRuntimeValidationAction.execute(JavaRuntimeValidationAction.java:24)
        at org.gradle.launcher.cli.ExceptionReportingAction.execute(ExceptionReportingAction.java:33)
        at org.gradle.launcher.cli.ExceptionReportingAction.execute(ExceptionReportingAction.java:22)
        at org.gradle.launcher.cli.CommandLineActionFactory$WithLogging.execute(CommandLineActionFactory.java:205)
        at org.gradle.launcher.cli.CommandLineActionFactory$WithLogging.execute(CommandLineActionFactory.java:169)
        at org.gradle.launcher.Main.doAction(Main.java:33)
        at org.gradle.launcher.bootstrap.EntryPoint.run(EntryPoint.java:45)
        at org.gradle.launcher.bootstrap.ProcessBootstrap.runNoExit(ProcessBootstrap.java:55)
        at org.gradle.launcher.bootstrap.ProcessBootstrap.run(ProcessBootstrap.java:36)
        at org.gradle.launcher.GradleMain.main(GradleMain.java:23)
        at org.gradle.wrapper.BootstrapMainStarter.start(BootstrapMainStarter.java:30)
        at org.gradle.wrapper.WrapperExecutor.execute(WrapperExecutor.java:129)
        at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:61)
Caused by: java.lang.IllegalStateException: Unable to rename 'D:\dev\myProject\myProjectModule\build\libs\myProjectModule-0.0.8-SNAPSHOT.jar' to 'D:\dev\myProject\myProjectModule\build\libs\myProjectModule-0.0.8-SNAPSHOT.jar.original'
        at org.springframework.boot.loader.tools.Repackager.renameFile(Repackager.java:285)
        at org.springframework.boot.loader.tools.Repackager.repackage(Repackager.java:138)
        at org.springframework.boot.gradle.repackage.RepackageTask$RepackageAction.repackage(RepackageTask.java:226)
        at org.springframework.boot.gradle.repackage.RepackageTask$RepackageAction.execute(RepackageTask.java:190)
        at org.springframework.boot.gradle.repackage.RepackageTask$RepackageAction.execute(RepackageTask.java:165)
        at org.gradle.internal.Actions$FilteredAction.execute(Actions.java:205)
        at org.gradle.api.internal.DefaultDomainObjectCollection.all(DefaultDomainObjectCollection.java:110)
        at org.gradle.api.internal.tasks.RealizableTaskCollection.all(RealizableTaskCollection.java:182)
        at org.gradle.api.internal.DefaultDomainObjectCollection.withType(DefaultDomainObjectCollection.java:120)
        at org.springframework.boot.gradle.repackage.RepackageTask.repackage(RepackageTask.java:140)
        at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:75)
        at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.doExecute(AnnotationProcessingTaskFactory.java:228)
        at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.java:221)
        at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.java:210)
        at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:621)
        at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:604)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:80)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:61)
        ... 60 more

BUILD FAILED

Total time: 25.024 secs

Build works when executed on a linux os and mac, so it looks like a windows issue.

A: I faced the similar problem. The jar was locked because the server was running using that jar. Terminating the server worked.


Q: Why does setting focus in the OnNavigatedTo() event not set focus? I've got this code in a pages OnNavigatedTo() event:
if (string.IsNullOrWhiteSpace(textBoxGroupName.Text))
{
    textBoxGroupName.Focus(FocusState.Programmatic);
}

...but textBoxGroupName does not have focus when the page displays. Why not?

A: OnNavigatedTo happens to early in the page lifetime for setting the focus to work. You should call your code in the Loaded event:
private void MainPage_OnLoaded(object sender, RoutedEventArgs e)
{
    if (string.IsNullOrWhiteSpace(textBoxGroupName.Text))
    {
        textBoxGroupName.Focus(FocusState.Programmatic);
    }
}

Of course you need to setup the handler in your .xaml file (I've omitted the other attributes in the Page element:
<Page
    Loaded="MainPage_OnLoaded">

A: Only controls that are contained within the GroupBox control can be selected or receive focus. Seems like you are not using GroupBox correctly.
From MSDN

The complete GroupBox itself cannot be selected or receive focus. For more information about how this control responds to the Focus and Select methods, see the following Control members: CanFocus, CanSelect, Focused, ContainsFocus, Focus, Select.

Hint:
You maybe want to use the Controls property to access the child controls:
if (string.IsNullOrWhiteSpace(textBoxGroupName.Text))
{
    var child_TextBox = textBoxGroupName.Controls["myTextBox"]
    if(child_TextBox.CanFocus)
        child_TextBox.Focus(FocusState.Programmatic);
}


Q: How to handle very very large amount of data in Android? I have a database containing 2 500 000 row of 13-digits numbers (and on end a little bit more - 4 000 000)
The user has to find if a 13-digits number exists in this database, all this on his android phone, without any internet connexion. So what do you suggest to deal with this?
I thought about using SQLITE on Android.
What do you suggest?

A: SQLite will be the best storage option for large data sets on the device. Ensure that where possible you use the correct SQLite query to get the data you need rather then using a general query and doing processing in your own code.

A: This is a bit too much to add in the comments, so I'll add it here.
4,000,000 rows of integers is not that much. Assuming that the integers will use the maximum size of a signed int (8 bytes), your database will be:
4000000 * 8 / 1024 / 1024 = ~30.5mb
That is large, but not game breaking.
Now that also assumes you will need a full 8 bytes per number. We know that we want to store 13 digits per entry, so a 6 byte integer column would suffice:
4000000 * 6 / 1024 / 1024 = ~23mb

A: Hi d3cima may be too late answer but it's help other's. Myself Realm is the best option.
Realm
Realm’s developer-friendly platform makes it easy to build reactive apps, realtime collaborative features, and offline-first experiences.
Advantage's:

*

*faster than SQLite (up to 10x speed up over raw SQLite for normal
operations)

*easy to use

*object conversion handled for you

*convenient for creating and storing data on the fly
I used my project it's more than 10 x then Sqlite.


Q: Open an iOS app from a shared link on a Facebook post We need users to open our app from a "...shared a link" on Facebook, or re-direct to the iOS app download page.  Is there objective c code available to accomplish this?  Thanks.

A: Since you asked for objective-C code, I assume you want to open either the appstore or the app on a certain URL. However, objective-c code is the least of the efforts here since it's mostly configurations that are at work for this.
To open an app you need to provide it a custom URL scheme:
http://iosdevelopertips.com/cocoa/launching-your-own-application-via-a-custom-url-scheme.html
To detect if that app is installed, you can try that URL:
https://developer.apple.com/library/ios/documentation/uikit/reference/UIApplication_Class/index.html#//apple_ref/occ/instm/UIApplication/canOpenURL:
And if not, you can navigate to the appstore instead via a different URL:
How can I link to my app in the App Store (iTunes)?
After you have done all that, the only actual code you need takes something of the form:
NSString *customURL = @"yourscheme://";
NSString *storeURL = @"itms://url_to_your_app";

if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:customURL]])
{
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:customURL]];
}
else
{
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:storeURL]];
}

Opening the app via it's URL can be done from other apps and websites, but will be more difficult to choose whether or not to open the app or store from inside a browser.

A: Apple have documented the process for you. You can just implement it your way.
NSString *iTunesLink = @"https://itunes.apple.com/us/app/apple-store/id375380948?mt=8";

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:iTunesLink]]

You can refer to This document for more info


Q: Cannot update global state using Context.API Trying to use Context.API to create a global state and pass it to multiple components. The state will store a few properties including a TwilioToken, device type and a name. I have a component SignupForm that renders a button. When the button is clicked, this triggers a function handleSubmit that takes a username and passes the username as an argument to another function setupTwilio. This function sends the username to an end point that interacts with Twilio Programmable Voice API, sending back a TwilioToken and device type. I then want to update my global state with the Twilio Token and device type and then redirect the user to another page /rooms
Problem is I don't seem to be updating my global state at all, when I console.log(state.TwilioToken) in the component rendered after handleSubmit I get null
Here is my context provider:
const initialState = {
    nickname: '',
    selectedRoom: null,
    rooms: [],
    createdRoomTopic: '',
    twilioToken: '',
    device: null
};

const RoomContext = createContext(null);

export const RoomContextProvider = ({ children }) => {
    const[state, setState] = useState(initialState);
    return (
        <RoomContext.Provider value={[state, setState]}>{children}</RoomContext.Provider>
    )
};

export const useGlobalState = () => {
    const value = useContext(RoomContext)
    if(value === undefined) throw new Error('Please add RoomContextProvider');
    return value;
}

My signupform
import { useGlobalState } from '../../context/RoomContextProvider';
...
//without useState() I get the error Uncaught TypeError: object null is not iterable (cannot read property Symbol(Symbol.iterator))

const [state, setState] = useState(useGlobalState());
...
    const handleSubmit = e => {
        e.preventDefault();
        const nickname = user.username;
        setupTwilio(nickname);
        history.push('/rooms');
    }
    const setupTwilio = (nickname) => {
        console.log('inside setupTwilio function', nickname)
        fetch(`http://127.0.0.1:8000/voice_chat/token/${nickname}`)
        .then(response => response.json())
        .then(data => {
            const twilioToken = data.token;
            const device = new Device(twilioToken);
            device.updateOptions(twilioToken, {
                codecPreferences: ['opus', 'pcmu'],
                fakeLocalDTMF: true,
                maxAverageBitrate: 16000
            });
            device.on('error', (device) => {
                console.log("error: ", device)
            });
            setState((state) => {
                return {...state, device, twilioToken}
            });
        })
      ...
    };
    return (
       <button className="button button-primary button-wide-mobile button-sm"
               onClick={handleSubmit}> Start Coding
       </button>

    );

When I console.log my state in the component rendered I get null
import { useGlobalState } from '../../context/RoomContextProvider';
...
const [state, setState] = useState(useGlobalState());
console.log('global state token is', state.twilioToken)