问:
PHP Simple HTML DOM and cURL Not Working
I can't get my scraper to return the specific content I'm looking for. If I return $output, I see digg as though it's being hosted on my server, so I know I'm accessing the site properly, I'm just not able to then access elements from the new DOM. What am I doing wrong?

```<code><?php

include('simple_html_dom.php');

function curl_download($url) {

$ch = curl_init();                                              //creates a new cURL resource handle
curl_setopt($ch, CURLOPT_URL, "http://digg.com");               // Set URL to download
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                 //  TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.
curl_setopt($ch, CURLOPT_USERAGENT, "MozillaXYZ/1.0");          // Set a referer
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );                // Should cURL return or print out the data? (true = return, false = print)
curl_setopt($ch, CURLOPT_HEADER, 0);                            // Include header in result? (0 = yes, 1 = no)
curl_setopt($ch, CURLOPT_TIMEOUT, 10);                          // Timeout in seconds

$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);

}

$html = new simple_html_dom();
$html->load($output, true, false );

    foreach($html->find('div.digg-story__kicker') as $article) {
        $article_title = $article->find('.digg-story__kicker')->innertext;
        return $article_title;
    }

    echo $article_title;

?>
</code>```

Edit: Okay, dumb mistake, I'm calling the function now:

```<code>$html = curl_download('http://digg.com')
</code>```

and if I echo $html I'm seeing the "mirrored site", but when I use str_get_html($html) which simple_html_dom.php says will //get html dom from stringI keep getting this error message:

Fatal error: Call to a member function str_get_html() on null in /home/andrew73124/public_html/scraper/scraper.php on line 31

答:
Your loop is weird, you are looping over the titles, so just access the innertext property:</p>

```<code>foreach($html->find('div.digg-story__kicker') as $article) {

    echo $article->innertext;

}
</code>```

Body:
I can't get my scraper to return the specific content I'm looking for. If I return $output, I see digg as though it's being hosted on my server, so I know I'm accessing the site properly, I'm just not able to then access elements from the new DOM. What am I doing wrong?

<?php

include('simple_html_dom.php');

function curl_download($url) {

$ch = curl_init();                                              //creates a new cURL resource handle
curl_setopt($ch, CURLOPT_URL, "http://digg.com");               // Set URL to download
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                 //  TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.
curl_setopt($ch, CURLOPT_USERAGENT, "MozillaXYZ/1.0");          // Set a referer
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );                // Should cURL return or print out the data? (true = return, false = print)
curl_setopt($ch, CURLOPT_HEADER, 0);                            // Include header in result? (0 = yes, 1 = no)
curl_setopt($ch, CURLOPT_TIMEOUT, 10);                          // Timeout in seconds

$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);

}

$html = new simple_html_dom();
$html->load($output, true, false );

    foreach($html->find('div.digg-story__kicker') as $article) {
        $article_title = $article->find('.digg-story__kicker')->innertext;
        return $article_title;
    }

    echo $article_title;

?>

Edit: Okay, dumb mistake, I'm calling the function now:

$html = curl_download('http://digg.com')

and if I echo $html I'm seeing the "mirrored site", but when I use str_get_html($html) which simple_html_dom.php says will //get html dom from stringI keep getting this error message:

Fatal error: Call to a member function str_get_html() on null in /home/andrew73124/public_html/scraper/scraper.php on line 31

Body:
Your loop is weird, you are looping over the titles, so just access the innertext property:

foreach($html->find('div.digg-story__kicker') as $article) {

    echo $article->innertext;

}


来源: stackexchange

问:
C switch case with function
can someone explain me this code?
I cant understand why printed value is 8 in this code

can someone explain it to me

```<code>#include <stdio.h>

int f(int i){
    switch (i){
        case 0 :
            return 0;
        case 1:

        case 2:
            return 1;
        default:

            return f(i-2)+f(i-1);
    }
}

void main(void) {

printf("%d", f(6));

}
</code>```

答: This is a recursive function which contains a switch case. Generally, in a Switch case, you need a statement breaker like break or return so that only that specific case executes correctly. Since in your code case 1 and case 2 return to same value ie 1 your code breaks down as a sum of 8 1s and final sum is 8.

ContentLicense: CC BY-SA 3.0

Title: C switch case with function

Body:
can someone explain me this code?
I cant understand why printed value is 8 in this code

can someone explain it to me

#include <stdio.h>

int f(int i){
    switch (i){
        case 0 :
            return 0;
        case 1:

        case 2:
            return 1;
        default:

            return f(i-2)+f(i-1);
    }
}

void main(void) {

printf("%d", f(6));

}


问:
How to make console program to disappear and work in background?
How can I make console program disappear and work in the background?
I mean, I don't want to see the program, but I want to see it running in the task manager.

Thanks.

答:
Assuming Windows and .NET:

You could set its output type to "Windows Application", and it will not open the console window....

Or you could create a Windows Service...

OwnerDisplayName: Tal

OwnerDisplayName: Arjan Einbu

ContentLicense: CC BY-SA 2.5


问:
Kohana 2.3.4 ORM sql injection protection
Kohana mentions they use mysql_real_escape_string to sanitize database inputs in their documentation. However, while tasting some basic queries through a form they were entered in the database exactly as I entered them. For instance:

```<code>SELECT * FROM users WHERE username='admin' AND password='' OR ''=''
</code>```

is entered into that mysql data exactly as it appears. I was expecting to see:

```<code>SELECT * FROM users WHERE username=\'admin\' AND password=\'\' OR \'\'=\'\'
</code>```

I'm using the ORM library instead of the database, but I know they work together. Also, I'm using the built in Input library ($this->input-post) to collect the data from forms. I haven't changed any controllers or libraries that relate to security.

I haven't combed the source code yet, but does Kohana escape the string and then remove the slashes before entering it into a db field? I'm somewhat convinced that this is the case, but I want to be certain.

Thanks

答: Kohana ORM protects you from SQL injection automatically.</p>

Body:
Kohana mentions they use mysql_real_escape_string to sanitize database inputs in their documentation. However, while tasting some basic queries through a form they were entered in the database exactly as I entered them. For instance:

SELECT * FROM users WHERE username='admin' AND password='' OR ''=''

is entered into that mysql data exactly as it appears. I was expecting to see:

SELECT * FROM users WHERE username=\'admin\' AND password=\'\' OR \'\'=\'\'

I'm using the ORM library instead of the database, but I know they work together. Also, I'm using the built in Input library ($this->input-post) to collect the data from forms. I haven't changed any controllers or libraries that relate to security.

I haven't combed the source code yet, but does Kohana escape the string and then remove the slashes before entering it into a db field? I'm somewhat convinced that this is the case, but I want to be certain.

Thanks


问:
JS code coverage with selenium tests
I’m new to the entire concept of capturing JS coverage.
The way I intend to use JS coverage tool is to check how many lines of my JS code is being hit by my tests running in a browser, thus using code coverage to improvise my test coverage.
Can somebody guide me to an example/tool of how to capture JS coverage for the test running using selenium webdriver.</p>

答:
A tool like nyc is what you need. Take your js file(s) and run something like

nyc instrument

on them and nyc will modify the js files to record coverage. Use these modified files in your website. Then run your selenium tests. At the end of the selenium test, you need to capture the data from the JS files and save it to a json file. I use this code for that.

IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
  string coverageData = (string)js.ExecuteScript("return JSON.stringify(window.cov_h0rgge4zy);");
            File.WriteAllText(@"C:\someDir\coverage\" + DateTime.Now.Ticks + ".json", "{\"someFile\":" + coverageData + "}");

then run something like

nyc report html someCoverage.json

and you'll get the coverage report, html format

Title: JS code coverage with selenium tests


问:
Why isn't the compiler warns about casting to enum?
I was quite shocked, when I realised that D allows the user to cast a compatible value to an enum and therefore make it possible to produce an invalid enum value, which I think is problematic in many levels.

So for example, if I create a library, where I expose an enum type and a function that is working on it:

module greek;

import std.stdio : writeln;

enum GreekLetters
{
    ALPHA,
    BETA,
}

void writeGreekLetter(GreekLetters letter)
{
    final switch(letter)
    {
        case GreekLetters.ALPHA:
            writeln("\u03B1");
            break;

        case GreekLetters.BETA:
            writeln("\u03B2");
            break;
    }
}
```

<p>... and then the user does the following:</p>

<pre class="lang-d prettyprint-override"><code>import greek : GreekLetters, writeGreekLetter;

void main()
{
    writeGreekLetter(cast(GreekLetters)2);
}
</code>```

... the compiler will not complain, but obviously the program will crash with a (not so nice) exception:

```<code>core.exception.SwitchError@greek(14): No appropriate switch clause found
</code>```

So my questions are:

Does this mean, that me, the library designer who tries to make things safe (that is, handled), should avoid using the final switch, and use other approaches (maybe a regular switch with a default case) and handle the invalid enum state there (returning an error, or throwing an exception)?

Why does a modern and safe language like D allows me to do such a thing? That is, what is the main reason casting to enum is allowed in the first place? (From the language design point of view.)

Note: I'm aware, that enum can have a basetype, which can be string and in that case writeGreekLetter doesn't really needed, however this is just a dummy example to demonstrate my main concern/problem.

答:
In D, casts are a blunt low-level operation: by using them, the programmer acknowledges that they are avoiding type system restrictions intentionally. (This is why the casting syntax uses the special cast keyword - aid code review by providing something greppable).

To "safely" convert an integer to an integral enum, you can use std.conv.to. For example:

```<code>writeGreekLetter(2.to!GreekLetters);
</code>```

This code will still compile, but will provide a better error message at runtime:

```<code>Value (2) does not match any member value of enum 'GreekLetters'
</code>```

To check the conversion of an integer literal at compile-time, you can use CTFE to assign it to a manifest constant first:

```<code>enum greekLetter2 = 2.to!GreekLetters;
writeGreekLetter(greekLetter2);
</code>```

This code will then correctly fail to compile:

```<code>Error: uncaught CTFE exception std.conv.ConvException("Value (2) does not match any member value of enum 'GreekLetters'"c)
</code>```

Body:
I was quite shocked, when I realised that D allows the user to cast a compatible value to an enum and therefore make it possible to produce an invalid enum value, which I think is problematic in many levels.

So for example, if I create a library, where I expose an enum type and a function that is working on it:

module greek;

import std.stdio : writeln;

enum GreekLetters
{
    ALPHA,
    BETA,
}

void writeGreekLetter(GreekLetters letter)
{
    final switch(letter)
    {
        case GreekLetters.ALPHA:
            writeln("\u03B1");
            break;

        case GreekLetters.BETA:
            writeln("\u03B2");
            break;
    }
}

... and then the user does the following:

import greek : GreekLetters, writeGreekLetter;

void main()
{
    writeGreekLetter(cast(GreekLetters)2);
}

... the compiler will not complain, but obviously the program will crash with a (not so nice) exception:

core.exception.SwitchError@greek(14): No appropriate switch clause found

So my questions are:

Does this mean, that me, the library designer who tries to make things safe (that is, handled), should avoid using the final switch, and use other approaches (maybe a regular switch with a default case) and handle the invalid enum state there (returning an error, or throwing an exception)?

Why does a modern and safe language like D allows me to do such a thing? That is, what is the main reason casting to enum is allowed in the first place? (From the language design point of view.)

Note: I'm aware, that enum can have a basetype, which can be string and in that case writeGreekLetter doesn't really needed, however this is just a dummy example to demonstrate my main concern/problem.

Body:
In D, casts are a blunt low-level operation: by using them, the programmer acknowledges that they are avoiding type system restrictions intentionally. (This is why the casting syntax uses the special cast keyword - aid code review by providing something greppable).

To "safely" convert an integer to an integral enum, you can use std.conv.to. For example:

writeGreekLetter(2.to!GreekLetters);

This code will still compile, but will provide a better error message at runtime:

Value (2) does not match any member value of enum 'GreekLetters'

To check the conversion of an integer literal at compile-time, you can use CTFE to assign it to a manifest constant first:

enum greekLetter2 = 2.to!GreekLetters;
writeGreekLetter(greekLetter2);

This code will then correctly fail to compile:

Error: uncaught CTFE exception std.conv.ConvException("Value (2) does not match any member value of enum 'GreekLetters'"c)


问:
Can't Edit/Update Certain Items In Database (Table)
I have database that I have multiple orders entered into. Everything seems to be working fine except for a few old entries which will not accept updates/changes to their Fields.

Note: The majority of the Fields are Strings with Possible Values entered via a DropDown Box.

So if I open Order A I can make adjustments just fine and those changes persist even after closing the page and coming back or refreshing.

But if I open Order B, I can make changes via the dropdowns and it looks like they have adjusted, however if I leave the page or refresh all the changes have reverted back.

One piece of info that may be helpful is that each of these orders has at least one Field that contains an entry that is no longer a Possible Value (the original entries were removed/changed per request of the client).

Maybe they are "locked" because of this? Is there a way to look at an error log for a Published app?

I can delete the "corrupt" entries and recreate them (since there are currently only a few), but I would prefer to find a better solution in case this happens again in the future.

Any help would be greatly appreciated.

答:
It's a bug. Such field level value updates should get through.

As workaround you can update prohibited(not possible anymore) values with allowed ones in OnSave Model's Event like:

switch (record.Field) {
  case "old_value_1":
    record.Field = "new_value_1";
    break;
  case "old_value_2":
    record.Field = "new_value_2";
    break;
  ...
}```

Sorry for the inconvenience.

Body:
It's a bug. Such field level value updates should get through.

As workaround you can update prohibited(not possible anymore) values with allowed ones in OnSave Model's Event like:

switch (record.Field) {
  case "old_value_1":
    record.Field = "new_value_1";
    break;
  case "old_value_2":
    record.Field = "new_value_2";
    break;
  ...
}

Sorry for the inconvenience.


问:
Hide elements within tabs dynamically in jQuery
Before I developed a functionality for when you have only one set of tabs. Now the aApp is growing and that tabs functionality is failing since there are more sets of tabs.

The first time the function was like this:

```<code>var iconTabs = function () {

    $('#icons-tabs a:not(:first)').addClass('inactive');
    $('.icons-container').hide();
    $('.icons-container:first').show();

    $('#icons-tabs a').click(function(){
        var t = $(this).attr('id');
        if($(this).hasClass('inactive')) {
            $('#icons-tabs a').addClass('inactive');
            $(this).removeClass('inactive');
            $('.icons-container').hide();
            $('#'+ t + 'C').fadeIn('slow');
        }
    });
};
</code>```

And the html:

```<code><div id="fragment-1" class="fragments text-center">
    <div class="icons-container" id="tab1C">
        {{!-- Content --}}
    </div>

    <div class="icons-container" id="tab2C">
        {{!-- Content --}}
    </div>

    <div class="fragments-parent">
        <div class="fragments-icons fragments-parent--child">
            <div class="items" id="icons-tabs">
                <a href="#" class="item" id="tab1"></a>
                <a href="#" class="item" id="tab2"></a>
                <a href="#" class="item" id="tab3"></a>
                <a href="#" class="item" id="tab4"></a>
            </div>
        </div>
    </div>
</div>
</code>```

Now the html has a second section and I still have to add 3 more, so now it is like this:

```<code><div id="fragment-1" class="fragments text-center">
    <div class="icons-container" id="tab1C">
        {{!-- Content --}}
    </div>

    <div class="icons-container" id="tab2C">
        {{!-- Content --}}
    </div>

    <div class="fragments-parent">
        <div class="fragments-icons fragments-parent--child">
            <div class="items" id="icons-tabs">
                <a href="#" class="item" id="tab1"></a>
                <a href="#" class="item" id="tab2"></a>
            </div>
        </div>
    </div>
</div>

<div id="fragment-2" class="fragments text-center">
    <div class="icons-container" id="tab5C">
        {{!-- Content --}}
    </div>

    <div class="icons-container" id="ta62C">
        {{!-- Content --}}
    </div>

    <div class="fragments-parent">
        <div class="fragments-icons fragments-parent--child">
            <div class="items" id="icons-tabs">
                <a href="#" class="item" id="tab5"></a>
                <a href="#" class="item" id="tab6"></a>
            </div>
        </div>
    </div>
</div>
</code>```

I have created a JSFiddle in case you want to play:

http://jsfiddle.net/ju3a9zx5/

My mission is to do it dynamic and that every set of tabs has separate behaviour. As you may see in the JSFiddle: the second set of tabs doesn't work, and I want them to have the same behaviour as the first one, but separate, one set of tabs don't have to interfere with the others.

答:
Ok played around with your fiddle. First remark: change id="tabs" to class="tabs", also change the selectors in your javascript and css. With that change it should get you up and running.

From a developer point of view I would create a jQuery plugin and throw the code in an each() function to make this even more flexible, better scalable and maintanable.

Body:
Before I developed a functionality for when you have only one set of tabs. Now the aApp is growing and that tabs functionality is failing since there are more sets of tabs.

The first time the function was like this:

var iconTabs = function () {

    $('#icons-tabs a:not(:first)').addClass('inactive');
    $('.icons-container').hide();
    $('.icons-container:first').show();

    $('#icons-tabs a').click(function(){
        var t = $(this).attr('id');
        if($(this).hasClass('inactive')) {
            $('#icons-tabs a').addClass('inactive');
            $(this).removeClass('inactive');
            $('.icons-container').hide();
            $('#'+ t + 'C').fadeIn('slow');
        }
    });
};

And the html:

        {{!-- Content --}}

        {{!-- Content --}}

Now the html has a second section and I still have to add 3 more, so now it is like this:

        {{!-- Content --}}

        {{!-- Content --}}

        {{!-- Content --}}

        {{!-- Content --}}

I have created a JSFiddle in case you want to play:

http://jsfiddle.net/ju3a9zx5/

My mission is to do it dynamic and that every set of tabs has separate behaviour. As you may see in the JSFiddle: the second set of tabs doesn't work, and I want them to have the same behaviour as the first one, but separate, one set of tabs don't have to interfere with the others.


问:
MySQL - Keep finding superiors of employees until the most superior employee is reached
I have an employees table in which all employees report to a superior except for one employee who reports to no one as he is the boss.

```<code>employeeNumber | reportsTo
---------------|-----------------
1002           | null
1056           | 1002
1143           | 1056
1165           | 1143
...
</code>```

I want to be able to show the employee numbers of all employees who are superiors of a particular employee. (i.e. the person he reportsTo, and the employee who that person reportsTo, ... all the way up)

For e.g. employeeNumber 1165 should yield

```<code>   | employeeNumber |
   |----------------|
   | null           |
   | 1002           |
   | 1056           |
   | 1143           |
</code>```

I have written a MySQL statement which carries out the query but I believe this is a bit too complex to read and understand:

```<code>select reportsTo as employeeNumber from employees where employeeNumber in
(select reportsTo from employees where employeeNumber in (select reportsTo from employees where
employeeNumber = 1165)) union select reportsTo from employees where employeeNumber in
(select reportsTo from employees where employeeNumber = 1165) union select reportsTo from employees
where employeeNumber = 1165;
</code>```

What simple MySQL statement can I use to get the same result?

答:
I just gave a presentation about recursive queries in MySQL at Percona Live  April 2017. The short answer is that there's no simple solution in MySQL before version 8.0 (which is still under development as I write this, and not expected to be GA for another year or so).

You can do joins to get the ancestor nodes, but you can only do a fixed number of joins, you can't predict how deep the hierarchy is.

```<code>SELECT
  e1.employeeNumber AS emp1,
  e2.employeeNumber AS emp2,
  e3.employeeNumber AS emp3,
  e4.employeeNumber AS emp4,
  e5.employeeNumber AS emp5,
  e6.employeeNumber AS emp6
FROM employees AS e1
LEFT JOIN employees AS e2 ON e1.reportsTo = e2.employeeNumber
LEFT JOIN employees AS e3 ON e2.reportsTo = e3.employeeNumber
LEFT JOIN employees AS e4 ON e3.reportsTo = e4.employeeNumber
LEFT JOIN employees AS e5 ON e4.reportsTo = e5.employeeNumber
LEFT JOIN employees AS e6 ON e5.reportsTo = e6.employeeNumber
WHERE e1.employeeNumber = 1165
</code>```

There are several other workarounds to query hierarchical data in MySQL, but they each require you to store the hierarchy data differently. You might like my presentation Recursive Query Throwdown or my past Stack Overflow answer to What is the most efficient/elegant way to parse a flat table into a tree?

I also wrote about methods of recursive queries in my book, SQL Antipatterns Volume 1: Avoiding the Pitfalls of Database Programming.

Body:
I have an employees table in which all employees report to a superior except for one employee who reports to no one as he is the boss.

employeeNumber | reportsTo
---------------|-----------------
1002           | null
1056           | 1002
1143           | 1056
1165           | 1143
...

I want to be able to show the employee numbers of all employees who are superiors of a particular employee. (i.e. the person he reportsTo, and the employee who that person reportsTo, ... all the way up)

For e.g. employeeNumber 1165 should yield

   | employeeNumber |
   |----------------|
   | null           |
   | 1002           |
   | 1056           |
   | 1143           |

I have written a MySQL statement which carries out the query but I believe this is a bit too complex to read and understand:

select reportsTo as employeeNumber from employees where employeeNumber in
(select reportsTo from employees where employeeNumber in (select reportsTo from employees where
employeeNumber = 1165)) union select reportsTo from employees where employeeNumber in
(select reportsTo from employees where employeeNumber = 1165) union select reportsTo from employees
where employeeNumber = 1165;

What simple MySQL statement can I use to get the same result?

Body:
I just gave a presentation about recursive queries in MySQL at Percona Live  April 2017. The short answer is that there's no simple solution in MySQL before version 8.0 (which is still under development as I write this, and not expected to be GA for another year or so).

You can do joins to get the ancestor nodes, but you can only do a fixed number of joins, you can't predict how deep the hierarchy is.

SELECT
  e1.employeeNumber AS emp1,
  e2.employeeNumber AS emp2,
  e3.employeeNumber AS emp3,
  e4.employeeNumber AS emp4,
  e5.employeeNumber AS emp5,
  e6.employeeNumber AS emp6
FROM employees AS e1
LEFT JOIN employees AS e2 ON e1.reportsTo = e2.employeeNumber
LEFT JOIN employees AS e3 ON e2.reportsTo = e3.employeeNumber
LEFT JOIN employees AS e4 ON e3.reportsTo = e4.employeeNumber
LEFT JOIN employees AS e5 ON e4.reportsTo = e5.employeeNumber
LEFT JOIN employees AS e6 ON e5.reportsTo = e6.employeeNumber
WHERE e1.employeeNumber = 1165

There are several other workarounds to query hierarchical data in MySQL, but they each require you to store the hierarchy data differently. You might like my presentation Recursive Query Throwdown or my past Stack Overflow answer to What is the most efficient/elegant way to parse a flat table into a tree?

I also wrote about methods of recursive queries in my book, SQL Antipatterns Volume 1: Avoiding the Pitfalls of Database Programming.

ContentLicense: CC BY-SA 4.0


问:
Rails 5 - Google Maps - Javascript error - initMap is not a function - fixing one js issue creates another
I have been trying for years to figure out how to use google maps in my Rails app. I am currently trying with Rails 5.

I have also been trying to figure out how to get my javascript to work in a production environment.

My most recent attempts at these challenges are outlined in this production issue post and this google maps post.

After a long codementor session, the production environment javascript problem seemed to have been solved by moving:

```<code><%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
</code>```

from out of the head tag to the end of the body tag.

However, in doing this, the google maps javascript now doesnt work. It gives an error that says:

```<code>initMap is not a function
</code>```

I have seen many others raise this problem, including here.

I have tried the solution outlined in this post, which is to replace this script:

```<code><script src="https://maps.googleapis.com/maps/api/js?key=<%= ENV["GOOGLE_MAPS_API_KEY"] %>&callback=initMap"
    async defer></script> -->
</code>```

with this script in my address view file:

```<code><script type="text/javascript" src="http://maps.google.com/maps/api/js?key=<%= ENV['GOOGLE_MAPS_API_KEY'] %>" async defer></script>
</code>```

The key difference is the removal of "&callback=initMap". This gives no errors in the console inspector. However, it doesn't display a map either.

I have created a new problem by fixing the production issues.

Can anyone see what I need to do in order to get the google maps rendering (without breaking the production environment js)?

答:
I have just run into this issue using jQuery in a Rails 5 app.  After trying to figure it for over an hour on my own I hit SO and tried a number of snippets that were confirmed working by others but I could no replicate.  However, embodying the power of a few million monkeys typing I managed to achieve a working solution.

1) The callback works on the window object, so I had to place initMap() in this context and not within $(document).ready...

2) The page that I am using the map on I included <%= javascript_include_tag "https://maps.googleapis.com/maps/api/js?key=YOUR_KEY_HERE&v=3&callback=initMap", async: true, defer: true %>

So my view looks like this:

```<code><div id="map_container">
  <div id="map">
  </div>

     <%= javascript_include_tag "https://maps.googleapis.com/maps/api/js?key=YOUR_KEY_HERE&v=3&callback=initMap", async: true, defer: true %>
   </div>
 </div>
</code>```

3) The biggest hassle for me was the view.  I couldn't get it to render without my height and width being in pixels.  After trial and error modifying other suggestions, I stumbled upon using vh.

```<code>#map_container {
  width: 100%;
  height: 100%;
}

#map {
  height: 100vh;
}
</code>```

Hopefully this helps others dealing with this.

EDIT:

After posting came across this codepen snippet: https://codepen.io/gabrieleromanato/pen/qEzKZY?editors=0110#0

I tested it successfully in a Rails 5 app by adding <%= javascript_include_tag "https://maps.googleapis.com/maps/api/js?key=YOUR_KEY_HERE&v=3" %>

Body:
I have been trying for years to figure out how to use google maps in my Rails app. I am currently trying with Rails 5.

I have also been trying to figure out how to get my javascript to work in a production environment.

My most recent attempts at these challenges are outlined in this production issue post and this google maps post.

After a long codementor session, the production environment javascript problem seemed to have been solved by moving:

<%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>

from out of the head tag to the end of the body tag.

However, in doing this, the google maps javascript now doesnt work. It gives an error that says:

initMap is not a function

I have seen many others raise this problem, including here.

I have tried the solution outlined in this post, which is to replace this script:

 -->

with this script in my address view file:

The key difference is the removal of "&callback=initMap". This gives no errors in the console inspector. However, it doesn't display a map either.

I have created a new problem by fixing the production issues.

Can anyone see what I need to do in order to get the google maps rendering (without breaking the production environment js)?

Body:
I have just run into this issue using jQuery in a Rails 5 app.  After trying to figure it for over an hour on my own I hit SO and tried a number of snippets that were confirmed working by others but I could no replicate.  However, embodying the power of a few million monkeys typing I managed to achieve a working solution.

1) The callback works on the window object, so I had to place initMap() in this context and not within $(document).ready...

2) The page that I am using the map on I included <%= javascript_include_tag "https://maps.googleapis.com/maps/api/js?key=YOUR_KEY_HERE&v=3&callback=initMap", async: true, defer: true %>

So my view looks like this:

<div id="map_container">
  <div id="map">
  </div>

     <%= javascript_include_tag "https://maps.googleapis.com/maps/api/js?key=YOUR_KEY_HERE&v=3&callback=initMap", async: true, defer: true %>
   </div>
 </div>

3) The biggest hassle for me was the view.  I couldn't get it to render without my height and width being in pixels.  After trial and error modifying other suggestions, I stumbled upon using vh.

#map_container {
  width: 100%;
  height: 100%;
}

#map {
  height: 100vh;
}

Hopefully this helps others dealing with this.

EDIT:

After posting came across this codepen snippet: https://codepen.io/gabrieleromanato/pen/qEzKZY?editors=0110#0

I tested it successfully in a Rails 5 app by adding <%= javascript_include_tag "https://maps.googleapis.com/maps/api/js?key=YOUR_KEY_HERE&v=3" %>


问:
How can I retrieve rows by with the latest date by using Google SpreadSheet API?
I have a big Google SpreadSheet document that stores some data and I need to use Google SpreadSheet REST API to retrieve particular rows from it.

Let's say we have the following test data:

```<code>ID | Name | Date
-----------------
1  | Erik | 07.06.2017
2  | Anna | 07.06.2017
3  | Kirk | 07.06.2017
4  | Erik | 06.06.2017
5  | Anna | 06.06.2017
6  | Kirk | 06.06.2017
....
</code>```

I need to retrieve rows with the latest date such as:

```<code>1  | Erik | 07.06.2017
2  | Anna | 07.06.2017
3  | Kirk | 07.06.2017
</code>```

How can I achieve this ?

EDIT:

From the official doc I've found that I can retrieve a range by the following request:

```<code>GET https://sheets.googleapis.com/v4/spreadsheets/spreadsheetId/values/Sheet1!A1:D5
</code>```

But this not suitable for me because I need filtering by max date :(

答:
you can use event object that tracks every change in sheet to track last modified and 'copy' it to some fixed possiion in sheet like I did in this short video..

you have to paste this in your Tools -> Script Editor

```<code>function onEdit(e) {
  var s = SpreadsheetApp.getActiveSheet();
  var rng = e.range;
  var ix = rng.getRow();
  var X = s.getRange( ix, 1, 1, 3 );
  s.getRange( 3, 5, 1, 3 ).copyTo( s.getRange( 4, 5 ) ); // SECOND LAST TO BUTTOM
  s.getRange( 2, 5, 1, 3 ).copyTo( s.getRange( 3, 5 ) ); // SECOND LAST TO BUTTOM
  X.copyTo( s.getRange( 2, 5 ) ); // LAST ON TOP!
}
</code>```

.. and then you can pull your data via REST like:

GET https://sheets.googleapis.com/v4/spreadsheets/spreadsheetId/values/Sheet1!E2:G4

hope that helps :)

Body:
I have a big Google SpreadSheet document that stores some data and I need to use Google SpreadSheet REST API to retrieve particular rows from it.

Let's say we have the following test data:

ID | Name | Date
-----------------
1  | Erik | 07.06.2017
2  | Anna | 07.06.2017
3  | Kirk | 07.06.2017
4  | Erik | 06.06.2017
5  | Anna | 06.06.2017
6  | Kirk | 06.06.2017
....

I need to retrieve rows with the latest date such as:

1  | Erik | 07.06.2017
2  | Anna | 07.06.2017
3  | Kirk | 07.06.2017

How can I achieve this ?

EDIT:

From the official doc I've found that I can retrieve a range by the following request:

GET https://sheets.googleapis.com/v4/spreadsheets/spreadsheetId/values/Sheet1!A1:D5

But this not suitable for me because I need filtering by max date :(

Body:
you can use event object that tracks every change in sheet to track last modified and 'copy' it to some fixed possiion in sheet like I did in this short video..

you have to paste this in your Tools -> Script Editor

function onEdit(e) {
  var s = SpreadsheetApp.getActiveSheet();
  var rng = e.range;
  var ix = rng.getRow();
  var X = s.getRange( ix, 1, 1, 3 );
  s.getRange( 3, 5, 1, 3 ).copyTo( s.getRange( 4, 5 ) ); // SECOND LAST TO BUTTOM
  s.getRange( 2, 5, 1, 3 ).copyTo( s.getRange( 3, 5 ) ); // SECOND LAST TO BUTTOM
  X.copyTo( s.getRange( 2, 5 ) ); // LAST ON TOP!
}

.. and then you can pull your data via REST like:

GET https://sheets.googleapis.com/v4/spreadsheets/spreadsheetId/values/Sheet1!E2:G4

hope that helps :)


问:
Push Sidebar Nav Menu
I am trying to get a sidebar push navigation that looks like    this. I do actually have content in between my center element div. My html looks like:

```<code><div id="mySidenav" class="sidenav">
<a href="javascript:void(0)" class="closebtn" onclick="closeNav()">×
</a>
<a href="#">Home</a>
<a href="#">About</a>
<a href="#">Projects</a>
<a href="#">Hire Me</a>
</div>

<div id = "main">

<span style="font-size:50px;cursor:pointer" onclick="openNav()" id="btnMenu">☰</span>

<div class = "centerElement">

</div>
</div>
</code>```

I believe its probably because my centerElement class that is not allowing its content to be pushed. If that is true my btnMenu will also have to be changed.

css code here:

```<code> .centerElement {
 position: absolute;
 top: 50%;
 left: 50%;
 width: 600px;
 height: 600px;
 margin: -300px 0 0 -300px;
}

#main {
transition: margin-right .5s;
padding: 16px;
}

#btnMenu {
position: absolute;
top: 72px;
right: 128px;
font-size: 18px;
}
</code>```

javascript is

```<code>function openNav() {
document.getElementById("mySidenav").style.width = "250px";
document.getElementById("main").style.marginRight = "250px";
}

function closeNav() {
document.getElementById("mySidenav").style.width = "0";
document.getElementById("main").style.marginRight= "0";
}
</code>```

I also tried my first fiddle but for some reason my navbar doesn't even open in it.  Didn't really care to put the effort to find out why but if this helps here it is.

答:
I got your fiddle working in a code pen, if I understand your question you want to push the content to the side when opening the side nav. I changed a few css properties to achieve this.

you have your centerElement which has position: absolute; this wont allow it to adjust to the side nav when it opens.

same with your btnMenu icon

I created a div around your btnMenu and added

```<code>.menuIcon {
  text-align: right;
}
</code>```

which places it on the right side like you had it.
also I removed your btnMenu styles

I also changed your .centerElement class to

```<code>.centerElement {
  width: 45%;
  margin: auto;
}
</code>```

this centers the content and adjusts when the nav opens.

You may have to play with some other margins and padding to get things to line up, but I think this is what your going for.

https://codepen.io/anon/pen/qjORpO

Title: Push Sidebar Nav Menu

Body:
I am trying to get a sidebar push navigation that looks like    this. I do actually have content in between my center element div. My html looks like:

×

Home
About
Projects
Hire Me

☰

I believe its probably because my centerElement class that is not allowing its content to be pushed. If that is true my btnMenu will also have to be changed.

css code here:

 .centerElement {
 position: absolute;
 top: 50%;
 left: 50%;
 width: 600px;
 height: 600px;
 margin: -300px 0 0 -300px;
}

#main {
transition: margin-right .5s;
padding: 16px;
}

#btnMenu {
position: absolute;
top: 72px;
right: 128px;
font-size: 18px;
}

javascript is

function openNav() {
document.getElementById("mySidenav").style.width = "250px";
document.getElementById("main").style.marginRight = "250px";
}

function closeNav() {
document.getElementById("mySidenav").style.width = "0";
document.getElementById("main").style.marginRight= "0";
}

I also tried my first fiddle but for some reason my navbar doesn't even open in it.  Didn't really care to put the effort to find out why but if this helps here it is.

Body:
I got your fiddle working in a code pen, if I understand your question you want to push the content to the side when opening the side nav. I changed a few css properties to achieve this.

you have your centerElement which has position: absolute; this wont allow it to adjust to the side nav when it opens.

same with your btnMenu icon

I created a div around your btnMenu and added

.menuIcon {
  text-align: right;
}

which places it on the right side like you had it.
also I removed your btnMenu styles

I also changed your .centerElement class to

.centerElement {
  width: 45%;
  margin: auto;
}

this centers the content and adjusts when the nav opens.

You may have to play with some other margins and padding to get things to line up, but I think this is what your going for.

https://codepen.io/anon/pen/qjORpO


问:
Netlogo: choosing ranked n-of turtles to add to a certain value to a variable
I'm constructing a model to research opinion dynamics given certain network structures. In the model, there is a hypothetical 'dictator' who can hand out resources (or 'bribes') to certain nodes in the network. What I want is that the dictator can choose the top X% of nodes in the model who have the most positive opinions. (later I also want to the dictator to choose the nodes with the most network connections)

What's the best way to do this? I'm not sure how to use the n-of command for a 'ranked' n-of. Or is it better to use another term I'm not aware of?

```<code>ask n-of ??? turtles [set bribes (bribes + height-of-bribe)]
</code>```

thanks!

edit:

currently, I have:

```<code>foreach sublist sort-on [(- total-motivation)] nodes 0 10 ask nodes [
set bribes (bribes + height-of-bribes)]
</code>```

but I'm still getting errors. Any thoughts?

Edit 2:

Nevermind. It works. Thanks!

答:
I think you probably want the max-n-of primitive. There is no need to sort and take the first (or last) of the list. You probably want something like

```<code>ask max-n-of 10 turtles [total-motivation] [set bribes (bribes + height-of-bribes)]
</code>```

When you later want the ones with the most links, just put [count my-links] instead of [total-motivation]

Body:
I'm constructing a model to research opinion dynamics given certain network structures. In the model, there is a hypothetical 'dictator' who can hand out resources (or 'bribes') to certain nodes in the network. What I want is that the dictator can choose the top X% of nodes in the model who have the most positive opinions. (later I also want to the dictator to choose the nodes with the most network connections)

What's the best way to do this? I'm not sure how to use the n-of command for a 'ranked' n-of. Or is it better to use another term I'm not aware of?

ask n-of ??? turtles [set bribes (bribes + height-of-bribe)]

thanks!

edit:

currently, I have:

foreach sublist sort-on [(- total-motivation)] nodes 0 10 ask nodes [
set bribes (bribes + height-of-bribes)]

but I'm still getting errors. Any thoughts?

Edit 2:

Nevermind. It works. Thanks!

Body:
I think you probably want the max-n-of primitive. There is no need to sort and take the first (or last) of the list. You probably want something like

ask max-n-of 10 turtles [total-motivation] [set bribes (bribes + height-of-bribes)]

When you later want the ones with the most links, just put [count my-links] instead of [total-motivation]


问:
XDocument : Difference between .Root.Value and .Root.ToString
Does anybody know what is the difference between those two below statements :

```<code>xdoc.Root.Value;
</code>```

and

```<code>xdoc.Root.ToString();
</code>```

From my own research, I can see that the first line removes the root node and replaces the '\r\n' to '\n' whereas the second one keeps the content as original. Am I correct ? any documentation to back that up ?
As I want to use the first line but keep the original Windows new lines, is there a way to do that ?

答:
The primary difference is:
ToString() includes the root element tags and the indentation/tabs.

For example:

<Root>
  <Child1>1</Child1>
</Root>

Whereas, value doesn't; nor does it maintain the tabs, it just shows the content inside the root tag - it will show you the tags for the children, but not for the root itself:
For example:

<Child1>1</Child1>

Body:
Does anybody know what is the difference between those two below statements :

xdoc.Root.Value;

and

xdoc.Root.ToString();

From my own research, I can see that the first line removes the root node and replaces the '\r\n' to '\n' whereas the second one keeps the content as original. Am I correct ? any documentation to back that up ?
As I want to use the first line but keep the original Windows new lines, is there a way to do that ?


问:
Iterative solving for unknowns in a fluids problem
I am a Mechanical engineer with a computer scientist question. This is an example of what the equations I'm working with are like:

x = √((y-z)×2/r)

  z = f×(L/D)×(x/2g)

  f = something crazy with x in it

  etc…(there are more equations with x in it)

The situation is this:

I need r to find x, but I need x to find z. I also need x to find f which is a part of finding z. So I guess a value for x, and then I use that value to find r and f. Then I go back and use the value I found for r and f to find x. I keep doing this until the guess and the calculated are the same.

My question is:

How do I get the computer to do this? I've been using mathcad, but an example in another language like C++ is fine.

答:
As the commenters have noted, the mathematical aspects of your question are beyond the scope of the help you can expect here, and are even beyond the help you could be offered based on the detail you posted.

However, I think that even if you understood the mathematics thoroughly there are computer science aspects to your question that should be addressed.

When you write your code, try to make organize it into functions that depend only upon the parameters you are passing in to a subroutine.  So write a subroutine that takes in values for y, z, and r and returns you x.  Make another that takes in f,L,D,G and returns z. Now you have testable routines that you can check to make sure they are computing correctly.  Check the input values to your routines in the routines - for instance in computing x you will get a divide by 0 error if you pass in a 0 for r. Think about how you want to handle this.

If you are going to solve this problem interatively you will need a method that will decide, based on the results of one iteration, what the values for the next iteration will be.  This also should be encapsulated within a subroutine.  Now if you are using a language that allows only one value to be returned from a subroutine (which is most common computation languages C, C++, Java, C#) you need to package up all your variables into some kind of data structure to return them.  You could use an array of reals or doubles, but it would be nicer to choose to make an object and then you can reference the variables by their name and not their position (less chance of error).

Another aspect of iteration is knowing when to stop.  Certainly you'll do so when you get a solution that converges.  Make this decision into another subroutine.  Now when you need to change the convergence criteria there is only one place in the code to go to.  But you need to consider other reasons for stopping - what do you do if your solution starts diverging instead of converging?  How many iterations will you allow the run to go before giving up?

Another aspect of iteration of a computer is round-off error.  Mathematically 10^40/10^38 is 100.  Mathematically 10^20 + 1 > 10^20.  These statements are not true in most computations.  Your calculations may need to take this into account or you will end up with numbers that are garbage.  This is an example of a cross-cutting concern that does not lend itself to encapsulation in a subroutine.

I would suggest that you go look at the Python language, and the pythonxy.com extensions.  There are people in the associated forums that would be a good resource for helping you learn how to do iterative solving of a system of equations.


问:
Flexbox different size childs
I learn flexbox and I have a first question how to make such a layout of columns as in the picture?  [MyCodeFiddle](http://jsfiddle.net/1s3bo913/)

layout project

答:
You can create a column for the 2 vertical .small-boxes and set flex: wrap on the parent. I adjusted the widths so it matches the parent element dimensions.

.flex-container {
  display: flex;
  width: 500px;
  height: 400px;
  flex-wrap: wrap;
}

.flex-container, .flex-col {
  display: flex;
}

.flex-col {
  flex-direction: column;
}

.large-box {
  width: 300px;
  height: 200px;
  background: blue;
}

.small-box {
  width: 200px;
  height: 100px;
  background: yellow;
}

.medium-box {
  width: 250px;
  height: 200px;
  background: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="flex-container">
  <div class="large-box">
  </div>
  <div class="flex-col">
    <div class="small-box">
    </div>
    <div class="small-box">
    </div>
  </div>
  <div class="medium-box">
  </div>
  <div class="medium-box">
  </div>
</div></code>```

Title: Flexbox different size childs

Body:
You can create a column for the 2 vertical .small-boxes and set flex: wrap on the parent. I adjusted the widths so it matches the parent element dimensions.

.flex-container {
  display: flex;
  width: 500px;
  height: 400px;
  flex-wrap: wrap;
}

.flex-container, .flex-col {
  display: flex;
}

.flex-col {
  flex-direction: column;
}

.large-box {
  width: 300px;
  height: 200px;
  background: blue;
}

.small-box {
  width: 200px;
  height: 100px;
  background: yellow;
}

.medium-box {
  width: 250px;
  height: 200px;
  background: red;
}

<div class="flex-container">
  <div class="large-box">
  </div>
  <div class="flex-col">
    <div class="small-box">
    </div>
    <div class="small-box">
    </div>
  </div>
  <div class="medium-box">
  </div>
  <div class="medium-box">
  </div>
</div>


问:
Disable input conditionally (Vue.js)
I have an input:

<input
  type="text"
  id="name"
  class="form-control"
  name="name"
  v-model="form.name"
  :disabled="validated ? '' : disabled"
/>
```
<p>and in my Vue.js component, I have:</p>
<pre class="lang-js prettyprint-override"><code>..
..
ready() {
  this.form.name = this.store.name;
  this.form.validated = this.store.validated;
},
..
</code>```

validated being a boolean, it can be either 0 or 1, but no matter what value is stored in the database, my input is always disabled.

I need the input to be disabled if false, otherwise it should be enabled and editable.

Update:

Doing this always enables the input (no matter I have 0 or 1 in the database):

<input
  type="text"
  id="name"
  class="form-control"
  name="name"
  v-model="form.name"
  :disabled="validated ? '' : disabled"
/>
```
<p>Doing this always <strong>disabled</strong> the input (no matter I have 0 or 1 in  the database):</p>
<pre class="lang-js prettyprint-override"><code><input
  type="text"
  id="name"
  class="form-control"
  name="name"
  v-model="form.name"
  :disabled="validated ? disabled : ''"
/>
</code>```

答:
you could have a computed property that returns a boolean dependent on whatever criteria you need.

<input type="text" :disabled=isDisabled>
```
<p>then put your logic in a computed property...</p>
<pre class="lang-js prettyprint-override"><code>computed: {
  isDisabled() {
    // evaluate whatever you need to determine disabled here...
    return this.form.validated;
  }
}
</code>```

Title: Disable input conditionally (Vue.js)

Body:
I have an input:

<input
  type="text"
  id="name"
  class="form-control"
  name="name"
  v-model="form.name"
  :disabled="validated ? '' : disabled"
/>

and in my Vue.js component, I have:

..
..
ready() {
  this.form.name = this.store.name;
  this.form.validated = this.store.validated;
},
..

validated being a boolean, it can be either 0 or 1, but no matter what value is stored in the database, my input is always disabled.

I need the input to be disabled if false, otherwise it should be enabled and editable.

Update:

Doing this always enables the input (no matter I have 0 or 1 in the database):

<input
  type="text"
  id="name"
  class="form-control"
  name="name"
  v-model="form.name"
  :disabled="validated ? '' : disabled"
/>

Doing this always disabled the input (no matter I have 0 or 1 in  the database):

<input
  type="text"
  id="name"
  class="form-control"
  name="name"
  v-model="form.name"
  :disabled="validated ? disabled : ''"
/>

Body:
you could have a computed property that returns a boolean dependent on whatever criteria you need.

<input type="text" :disabled=isDisabled>

then put your logic in a computed property...

computed: {
  isDisabled() {
    // evaluate whatever you need to determine disabled here...
    return this.form.validated;
  }
}


问:
App which displays List does not work
I try to make an App with button which after the push will display all elements from list in editText.
But I have a problem, currently after I push the button I see only "second" in editText

In my opinion I need a tips from you about how to do it.  Maybe I shouldn't use a loop ?

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

    private Button button;
    private EditText editText;
    private ArrayList<String> list = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button = (Button) findViewById(R.id.button);
        editText = (EditText) findViewById(R.id.editText);

        list.add(0, "first");
        list.add(1, "second");

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                for (String abc: list){

                    editText.setText(abc);

                }

            }
        });
    }

}
</code>```

____ edit

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

    private Button button;
    private EditText editText;
    private ArrayList<String> list = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button = (Button) findViewById(R.id.button);
        editText = (EditText) findViewById(R.id.editText);

        list.add(0, "first");
        list.add(1, "second");
        list.add(2, "3");
        list.add(3, "4");
        list.add(4, "5");

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String final_text = "";

                for (String abc: list){

                    final_text = final_text + "\n" + abc;

                }

                editText.setText(final_text);

            }
        });
    }

}
</code>```

enter image description here

答:
On this loop you will always get the last string of the list into the edittext

```<code>for (String abc: list){
    editText.setText(abc);
}
</code>```

You need to create multiple edittext to add multiple value from your list, or else you need to compile all value from list to one string like @Zakir has propose.

Title: App which displays List does not work

Body:
I try to make an App with button which after the push will display all elements from list in editText.
But I have a problem, currently after I push the button I see only "second" in editText

In my opinion I need a tips from you about how to do it.  Maybe I shouldn't use a loop ?

public class MainActivity extends AppCompatActivity {

    private Button button;
    private EditText editText;
    private ArrayList<String> list = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button = (Button) findViewById(R.id.button);
        editText = (EditText) findViewById(R.id.editText);

        list.add(0, "first");
        list.add(1, "second");

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                for (String abc: list){

                    editText.setText(abc);

                }

            }
        });
    }

}

____ edit

public class MainActivity extends AppCompatActivity {

    private Button button;
    private EditText editText;
    private ArrayList<String> list = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button = (Button) findViewById(R.id.button);
        editText = (EditText) findViewById(R.id.editText);

        list.add(0, "first");
        list.add(1, "second");
        list.add(2, "3");
        list.add(3, "4");
        list.add(4, "5");

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String final_text = "";

                for (String abc: list){

                    final_text = final_text + "\n" + abc;

                }

                editText.setText(final_text);

            }
        });
    }

}

enter image description here

Body:
On this loop you will always get the last string of the list into the edittext

for (String abc: list){
    editText.setText(abc);
}

You need to create multiple edittext to add multiple value from your list, or else you need to compile all value from list to one string like @Zakir has propose.


问:
Ruby on Rails has_secure_password validation gets errors on update
I have working on a Ruby on Rails application and have a problem. I've user model in my domain and it has a has_secure_password field like this:

```<code>class User < ApplicationRecord
    validates :name, presence: true

    has_secure_password
    validates :password, presence: true
    validates :password, length: { in: 6..20, message: 'Password shoul be minimum 6 characters'}
end
</code>```

And I save the user object with this function:

```<code>def self.create_with_params(email,name,password)
    user = User.new()
    user.provider= :mail
    user.name=name
    user.email=email
    user.password=password
    user.activate_status=false

    user.save(validate: true);

    return user;
end
</code>```

That's ok too.

But when I want to update a field in my user model. I get validation error for password field.

```<code>@user = User.find_by(email: params[:email]) # this record has a valid password_digest field in database.
@user.name = 'John'
@user.save

puts @user.errors.full_messages
</code>```

It prints:

"Password shoul be minimum 6 characters".

Note: I have password_digest field in my users table.

I think when I query users table password_digest field couldn't be filled in to password field on model.

Any suggestions?

答:
I think when I query Users table password_digest field couldn't be
  filled in to password field on model.

Correct, the password is not stored, so when you query User you don't get the password field, yet your model asks for it every time with:

```<code>validates :password, presence: true
</code>```

So, you will need to provide password before saving @user to make it work, but i guess that is not what you want, so just remove that validation from your model,

You won't need to validate password every time, just upon creating, and that validation is done with has_secure_password.

Also, for the same reason, you will need to update length validation to:

```<code>validates :password, length: { in: 6..20, message: 'Password shoul be minimum 6 characters'}, allow_nil: true
</code>```

Body:
I have working on a Ruby on Rails application and have a problem. I've user model in my domain and it has a has_secure_password field like this:

class User < ApplicationRecord
    validates :name, presence: true

    has_secure_password
    validates :password, presence: true
    validates :password, length: { in: 6..20, message: 'Password shoul be minimum 6 characters'}
end

And I save the user object with this function:

def self.create_with_params(email,name,password)
    user = User.new()
    user.provider= :mail
    user.name=name
    user.email=email
    user.password=password
    user.activate_status=false

    user.save(validate: true);

    return user;
end

That's ok too.

But when I want to update a field in my user model. I get validation error for password field.

@user = User.find_by(email: params[:email]) # this record has a valid password_digest field in database.
@user.name = 'John'
@user.save

puts @user.errors.full_messages

It prints:

"Password shoul be minimum 6 characters".

Note: I have password_digest field in my users table.

I think when I query users table password_digest field couldn't be filled in to password field on model.

Any suggestions?

Body:
I think when I query Users table password_digest field couldn't be
  filled in to password field on model.

Correct, the password is not stored, so when you query User you don't get the password field, yet your model asks for it every time with:

validates :password, presence: true

So, you will need to provide password before saving @user to make it work, but i guess that is not what you want, so just remove that validation from your model,

You won't need to validate password every time, just upon creating, and that validation is done with has_secure_password.

Also, for the same reason, you will need to update length validation to:

validates :password, length: { in: 6..20, message: 'Password shoul be minimum 6 characters'}, allow_nil: true


问:
Excel - count first adjacent non-zero and not-null values in a row
I'm trying to write a formula, which will count numbers (>0) in a row.

Only the first set of >0 numbers in a row should be counted.

When there is a 0 or an empty cell after the >0 number, the count should ignore next values.

Example:

答:
It was fun trying to figure out a non-VBA solution.

1) Enter formula in cell H3:

```<code>=ADDRESS(ROW(B3),COLUMN(B3)+MATCH(TRUE,INDEX(B3:E3>0,0),0)-1)
</code>```

It will generate a cell adress ("D3") which contains the first value > 0 in its row.

2) Enter formula in cell I3:

```<code>=MATCH(TRUE,INDEX(INDIRECT(H3):F3=0,0),0)-1
</code>```

It will give you the expected result:

Requirement: one cell immediately after the data (F3) must be empty.

[Edit]: How it works

Approach logic:

for each record, find the address of the first cell that contains value > 0

starting from this cell address, find position of the first cell that is zero or blank

Desired count is a position number found at step 2, less 1

For example, for the first record step one gives "D3" - cell of the first value. Step 2 calculates that the first cell without value after "D3" starts in position 3 (D3 has value, E3 has value, F3 is blank). Therefore, value count is 3 - 1 = 2 (values in D3 and E3).

How formulas work:
INDEX(B3:E3>0,0) compares every cell in range B3:E3 to 0 (blanks are treated as 0s), and returns results as a boolean array {FALSE, FALSE, TRUE, TRUE}. MATCH(TRUE, ...) then finds position of the first TRUE in this array (3). ADDRESS calculates cell adress by adding this position to cell B3 ("B+3, 3" = "D3") .

INDIRECT(H3):F3 takes cell address we calculated in the first formula ("D3") from cell H3, and generates range D3:F3. Then MATCH(INDEX()) goes over this range and finds a position of the first cell without value (3) after D3. So, we have value in first position (D3), second position (E3), and no value in 3rd position (F3). 3 - 1 = 2 positions with values.

Body:
It was fun trying to figure out a non-VBA solution.

1) Enter formula in cell H3:

=ADDRESS(ROW(B3),COLUMN(B3)+MATCH(TRUE,INDEX(B3:E3>0,0),0)-1)

It will generate a cell adress ("D3") which contains the first value > 0 in its row.

2) Enter formula in cell I3:

=MATCH(TRUE,INDEX(INDIRECT(H3):F3=0,0),0)-1

It will give you the expected result:

Requirement: one cell immediately after the data (F3) must be empty.

[Edit]: How it works

Approach logic:

for each record, find the address of the first cell that contains value > 0

starting from this cell address, find position of the first cell that is zero or blank

Desired count is a position number found at step 2, less 1

For example, for the first record step one gives "D3" - cell of the first value. Step 2 calculates that the first cell without value after "D3" starts in position 3 (D3 has value, E3 has value, F3 is blank). Therefore, value count is 3 - 1 = 2 (values in D3 and E3).

How formulas work:
INDEX(B3:E3>0,0) compares every cell in range B3:E3 to 0 (blanks are treated as 0s), and returns results as a boolean array {FALSE, FALSE, TRUE, TRUE}. MATCH(TRUE, ...) then finds position of the first TRUE in this array (3). ADDRESS calculates cell adress by adding this position to cell B3 ("B+3, 3" = "D3") .

INDIRECT(H3):F3 takes cell address we calculated in the first formula ("D3") from cell H3, and generates range D3:F3. Then MATCH(INDEX()) goes over this range and finds a position of the first cell without value (3) after D3. So, we have value in first position (D3), second position (E3), and no value in 3rd position (F3). 3 - 1 = 2 positions with values.


问:
Invite people liked on post to like fanpage effectiveness measurement
I am going to find out the Like source of Facebook Page I am managing.

My page is much less than 100K page likes. I would like to use the invite function for those users given reactions towards posts, but did not like my page. (Similar steps in impactiv8.com.au/invite-people-who-like-your-facebook-post-to-like-your-page/)

Main Question: Now I would like to find out how is this effectiveness.
Which parameter(s) provided by Facebook I should have a look?

Second  Question: Is it possible somebody likes my page after my invitation, but that like source counted as "Page profile" type?

I tried Facebook Insights export data and the Graph API, but I am confused.

1) Facebook Insights data Export

The Export xls file both "Daily Like Source" are selected.

The descriptions are:

"Daily: This is a breakdown of the number of Page likes from the most common places where people can like your Page. (Total Count)"

"Daily: The number of people who liked your Page, broken down by the most common places where people can like your Page. (Unique Users)"

The fields given are as the following:

ads

api

banhammer

comment_chaining

engagement_pyml

external_connect

feed_chaining

feed_pyml

feed_story

hovercard

launch_point_discover_pyml

like_story

live_video

mobile

mobile_ads

mobile_page_browser

mobile_page_suggestions_on_liking

outbound_click_chaining

page_browser

page_browser_invite

page_contextual_recommendations

page_finch_related_pages

page_invite

page_invite_escape_hatch_finch

page_profile

page_timeline

pagelike_adder_for_reactivated_users

profile_edit

reminder_box_invite

search

sponsored_story

timeline_collection

timeline_like_chaining

unknown

vertex_page

wap

2) Graph API (v2.9)

I also tried Graph API described in
https://developers.facebook.com/docs/graph-api/reference/v2.9/insights
I suspect "page_suggestion" under "page_fans_by_like_source" described in the docs looks like what I want.

However, I cannot find it in the JSON output in the Graph API Explorer.

Also, this post(www.sotrender.com/blog/2017/04/page-like-sources-facebook/) introduced something like "PYML suggestion". I find PYML in the JSON, but none description in docs.

The fields given are as the following:

end_time(* only appear at Graph API, not Insights data Export)

ads

api

banhammer

comment_chaining

engagement_pyml

external_connect

feed_chaining

feed_pyml

feed_share_link (* only appear at Graph API, not Insights data Export)

feed_story

hovercard

launch_point_discover_pyml

like_story

live_video

mobile

mobile_ads

mobile_page_browser

mobile_page_suggestions_on_liking

outbound_click_chaining

page_browser

page_browser_invite

page_contextual_recommendations

page_finch_related_pages

page_invite

page_invite_escape_hatch_finch

page_profile

page_timeline

pagelike_adder_for_reactivated_users

photo_snowlift (* only appear at Graph API, not Insights data Export)

profile_edit

reminder_box_invite

search

sponsored_story

timeline_collection

timeline_like_chaining

unknown

vertex_page

wap

Thank you!

答: So, basically, you want things that this extension does: https://chrome.google.com/webstore/detail/facebook-fan-inviter-cust/nadkillaoaocaambipdgoookeaghjeik ? Why not use it?</p>


问:
Error while installing google plugin for Eclipse Mars.2
I am getting following error while installing google plugin on Eclipse</p>

```<code>An error occurred while collecting items to be installed
session context was:(profile=C__Users_adu_eclipse_jee-mars_eclipse, phase=org.eclipse.equinox.internal.p2.engine.phases.Collect, operand=, action=).
No repository found containing: osgi.bundle,org.apache.commons.io,2.4.0
No repository found containing: osgi.bundle,org.eclipse.m2e.archetype.common,1.6.3.20160209-1444
No repository found containing: osgi.bundle,org.eclipse.m2e.core,1.6.3.20160209-1446
No repository found containing: osgi.bundle,org.eclipse.m2e.core.ui,1.6.3.20160209-1446
No repository found containing: osgi.bundle,org.eclipse.m2e.discovery,1.6.3.20160209-1446
No repository found containing: osgi.bundle,org.eclipse.m2e.editor,1.6.3.20160209-1446
No repository found containing: osgi.bundle,org.eclipse.m2e.editor.xml,1.6.3.20160209-1446
No repository found containing: osgi.bundle,org.eclipse.m2e.jdt,1.6.3.20160209-1446
No repository found containing: osgi.bundle,org.eclipse.m2e.jdt.ui,1.6.3.20160209-1446
No repository found containing: osgi.bundle,org.eclipse.m2e.launching,1.6.3.20160209-1446
No repository found containing: osgi.bundle,org.eclipse.m2e.lifecyclemapping.defaults,1.6.3.20160209-1446
No repository found containing: osgi.bundle,org.eclipse.m2e.maven.indexer,1.6.3.20160209-1444
No repository found containing: osgi.bundle,org.eclipse.m2e.maven.runtime,1.6.3.20160209-1444
No repository found containing: osgi.bundle,org.eclipse.m2e.maven.runtime.slf4j.simple,1.6.3.20160209-1444
No repository found containing: osgi.bundle,org.eclipse.m2e.model.edit,1.6.3.20160209-1446
No repository found containing: osgi.bundle,org.eclipse.m2e.profiles.core,1.6.3.20160209-1446
No repository found containing: osgi.bundle,org.eclipse.m2e.profiles.ui,1.6.3.20160209-1446
No repository found containing: osgi.bundle,org.eclipse.m2e.refactoring,1.6.3.20160209-1446
No repository found containing: osgi.bundle,org.eclipse.m2e.scm,1.6.3.20160209-1446
No repository found containing: org.eclipse.update.feature,org.eclipse.m2e.feature,1.6.3.20160209-1446
</code>```

答:
I had the same problem and was able to resolve it by adding the following repo in the "Available Software Sites":

http://download.eclipse.org/technology/m2e/releases

This resolved all of the no repository errors for m2e that you are showing.

Body:
I am getting following error while installing google plugin on Eclipse

An error occurred while collecting items to be installed
session context was:(profile=C__Users_adu_eclipse_jee-mars_eclipse, phase=org.eclipse.equinox.internal.p2.engine.phases.Collect, operand=, action=).
No repository found containing: osgi.bundle,org.apache.commons.io,2.4.0
No repository found containing: osgi.bundle,org.eclipse.m2e.archetype.common,1.6.3.20160209-1444
No repository found containing: osgi.bundle,org.eclipse.m2e.core,1.6.3.20160209-1446
No repository found containing: osgi.bundle,org.eclipse.m2e.core.ui,1.6.3.20160209-1446
No repository found containing: osgi.bundle,org.eclipse.m2e.discovery,1.6.3.20160209-1446
No repository found containing: osgi.bundle,org.eclipse.m2e.editor,1.6.3.20160209-1446
No repository found containing: osgi.bundle,org.eclipse.m2e.editor.xml,1.6.3.20160209-1446
No repository found containing: osgi.bundle,org.eclipse.m2e.jdt,1.6.3.20160209-1446
No repository found containing: osgi.bundle,org.eclipse.m2e.jdt.ui,1.6.3.20160209-1446
No repository found containing: osgi.bundle,org.eclipse.m2e.launching,1.6.3.20160209-1446
No repository found containing: osgi.bundle,org.eclipse.m2e.lifecyclemapping.defaults,1.6.3.20160209-1446
No repository found containing: osgi.bundle,org.eclipse.m2e.maven.indexer,1.6.3.20160209-1444
No repository found containing: osgi.bundle,org.eclipse.m2e.maven.runtime,1.6.3.20160209-1444
No repository found containing: osgi.bundle,org.eclipse.m2e.maven.runtime.slf4j.simple,1.6.3.20160209-1444
No repository found containing: osgi.bundle,org.eclipse.m2e.model.edit,1.6.3.20160209-1446
No repository found containing: osgi.bundle,org.eclipse.m2e.profiles.core,1.6.3.20160209-1446
No repository found containing: osgi.bundle,org.eclipse.m2e.profiles.ui,1.6.3.20160209-1446
No repository found containing: osgi.bundle,org.eclipse.m2e.refactoring,1.6.3.20160209-1446
No repository found containing: osgi.bundle,org.eclipse.m2e.scm,1.6.3.20160209-1446
No repository found containing: org.eclipse.update.feature,org.eclipse.m2e.feature,1.6.3.20160209-1446


问:
python syntax error can figure out!! variable
I have this code in python, to ask people how many cigarettes do they smoke and return how many they smoke in a month and in a year. I have an error at line 4, I have searched this but I don't find any that work. I know it is a syntax problem but I can't figure it out.

Here is the code:

```<code>print ("Hola, Que Tal")
print ("Como te llamas?")
miNumbre=input()
print ("Mucho Gusto " + miNumbre )
print ("Cuantos Paquetes de Puchos Fumas Por Dia?")
puchos=input()
print ("Fumas " +str(int(puchos) * 30) + " Paquetes de Puchos Por Mes")
print ("En Un Año Fumas " +str(int(puchos) * 360) + " Paquetes de Puchos")
</code>```

答:
It's really important to run this with Python3

```<code>miNumbre=input()
print ("Mucho Gusto " + miNumbre )
</code>```

in Python2, input() evaluates the string, so miNumbre will be an int

If you mean to use Python2, the equivalent would be

```<code>miNumbre = raw_input()
print "Mucho Gusto " + miNumbre
</code>```

Body:
I have this code in python, to ask people how many cigarettes do they smoke and return how many they smoke in a month and in a year. I have an error at line 4, I have searched this but I don't find any that work. I know it is a syntax problem but I can't figure it out.

Here is the code:

print ("Hola, Que Tal")
print ("Como te llamas?")
miNumbre=input()
print ("Mucho Gusto " + miNumbre )
print ("Cuantos Paquetes de Puchos Fumas Por Dia?")
puchos=input()
print ("Fumas " +str(int(puchos) * 30) + " Paquetes de Puchos Por Mes")
print ("En Un Año Fumas " +str(int(puchos) * 360) + " Paquetes de Puchos")

Body:
It's really important to run this with Python3

miNumbre=input()
print ("Mucho Gusto " + miNumbre )

in Python2, input() evaluates the string, so miNumbre will be an int

If you mean to use Python2, the equivalent would be

miNumbre = raw_input()
print "Mucho Gusto " + miNumbre


问:
Large CSV with Apache Camel + Aggregator
Generate big files with Apache Camel with Aggregator with better performance as this post: Large Files with Apache Camel

My body has 33352 rows.. and using completionSize="1000" and completionTimeout="2500" the final file missed the last 352 rows

<camel:split streaming="true">
  <camel:simple>${body}</camel:simple>
  <camel:marshal>
    <camel:csv quote='"' quoteDisabled="false" headerDisabled="true" />
  </camel:marshal>
  <camel:aggregate strategyRef="setfepCsvStringBodyAggregator" completionSize="1000" completionTimeout="2500">
    <camel:correlationExpression>
      <constant>true</constant>
    </camel:correlationExpression>
    <to uri="file:{{setfep_dir_inprogress}}/?fileName={{setfep_filename_clientes}}.txt&fileExist=Append" />
  </camel:aggregate>
</camel:split>
```

<p>Final file has 33000 rows missing 352.</p>

```[INFO ] org.apache.camel.util.CamelLogger.log - Complete by=size rows=1000
[INFO ] org.apache.camel.util.CamelLogger.log - Complete by=size rows=1000
[INFO ] org.apache.camel.util.CamelLogger.log - Complete by=size rows=1000
[INFO ] org.apache.camel.util.CamelLogger.log - Complete by=size rows=1000
[INFO ] org.apache.camel.util.CamelLogger.log - Complete by=size rows=1000
[INFO ] org.apache.camel.util.CamelLogger.log - Complete by=size rows=1000
[INFO ] org.apache.camel.util.CamelLogger.log - Complete by=size rows=1000
[INFO ] org.apache.camel.util.CamelLogger.log - Complete by=size rows=1000
[INFO ] org.apache.camel.util.CamelLogger.log - Complete by=size rows=1000
[INFO ] org.apache.camel.util.CamelLogger.log - Complete by=size rows=1000
[INFO ] org.apache.camel.util.CamelLogger.log - Complete by=size rows=1000
[INFO ] org.apache.camel.util.CamelLogger.log - Complete by=size rows=1000
[INFO ] org.apache.camel.util.CamelLogger.log - Complete by=size rows=1000
[INFO ] org.apache.camel.util.CamelLogger.log - Complete by=size rows=1000
[INFO ] org.apache.camel.util.CamelLogger.log - Complete by=size rows=1000
[INFO ] org.apache.camel.util.CamelLogger.log - Complete by=size rows=1000
[INFO ] org.apache.camel.util.CamelLogger.log - Complete by=size rows=1000
[INFO ] org.apache.camel.util.CamelLogger.log - Complete by=size rows=1000
[INFO ] org.apache.camel.util.CamelLogger.log - Complete by=size rows=1000
[INFO ] org.apache.camel.util.CamelLogger.log - Complete by=size rows=1000
[INFO ] org.apache.camel.util.CamelLogger.log - Complete by=size rows=1000
[INFO ] org.apache.camel.util.CamelLogger.log - Complete by=size rows=1000
[INFO ] org.apache.camel.util.CamelLogger.log - Complete by=size rows=1000
[INFO ] org.apache.camel.util.CamelLogger.log - Complete by=size rows=1000
[INFO ] org.apache.camel.util.CamelLogger.log - Complete by=size rows=1000
[INFO ] org.apache.camel.util.CamelLogger.log - Complete by=size rows=1000
[INFO ] org.apache.camel.util.CamelLogger.log - Complete by=size rows=1000
[INFO ] org.apache.camel.util.CamelLogger.log - Complete by=size rows=1000
[INFO ] org.apache.camel.util.CamelLogger.log - Complete by=size rows=1000
[INFO ] org.apache.camel.util.CamelLogger.log - Complete by=size rows=1000
[INFO ] org.apache.camel.util.CamelLogger.log - Complete by=size rows=1000
[INFO ] org.apache.camel.util.CamelLogger.log - Complete by=size rows=1000
[INFO ] org.apache.camel.util.CamelLogger.log - Complete by=size rows=1000
```

<p>if I use <code>completionSize="1000"</code> and <code>completionInterval="2500"</code> my final file has 33155 hows missing 197 rows.</p>

```[Camel thread #0 - AggregateTimeoutChecker] [INFO ]  CamelLogger.log - Complete by=interval rows=566
[main] [INFO ]  CamelLogger.log - Complete by=size rows=1000
[main] [INFO ]  CamelLogger.log - Complete by=size rows=1000
[main] [INFO ]  CamelLogger.log - Complete by=size rows=1000
[main] [INFO ]  CamelLogger.log - Complete by=size rows=1000
[main] [INFO ]  CamelLogger.log - Complete by=size rows=1000
[main] [INFO ]  CamelLogger.log - Complete by=size rows=1000
[Camel thread #0 - AggregateTimeoutChecker] [INFO ]  CamelLogger.log - Complete by=interval rows=43
[main] [INFO ]  CamelLogger.log - Complete by=size rows=1000
[main] [INFO ]  CamelLogger.log - Complete by=size rows=1000
[main] [INFO ]  CamelLogger.log - Complete by=size rows=1000
[main] [INFO ]  CamelLogger.log - Complete by=size rows=1000
[main] [INFO ]  CamelLogger.log - Complete by=size rows=1000
[main] [INFO ]  CamelLogger.log - Complete by=size rows=1000
[main] [INFO ]  CamelLogger.log - Complete by=size rows=1000
[Camel thread #0 - AggregateTimeoutChecker] [INFO ]  CamelLogger.log - Complete by=interval rows=401
[main] [INFO ]  CamelLogger.log - Complete by=size rows=1000
[main] [INFO ]  CamelLogger.log - Complete by=size rows=1000
[main] [INFO ]  CamelLogger.log - Complete by=size rows=1000
[main] [INFO ]  CamelLogger.log - Complete by=size rows=1000
[main] [INFO ]  CamelLogger.log - Complete by=size rows=1000
[main] [INFO ]  CamelLogger.log - Complete by=size rows=1000
[main] [INFO ]  CamelLogger.log - Complete by=size rows=1000
[Camel thread #0 - AggregateTimeoutChecker] [INFO ]  CamelLogger.log - Complete by=interval rows=768
[main] [INFO ]  CamelLogger.log - Complete by=size rows=1000
[main] [INFO ]  CamelLogger.log - Complete by=size rows=1000
[main] [INFO ]  CamelLogger.log - Complete by=size rows=1000
[main] [INFO ]  CamelLogger.log - Complete by=size rows=1000
[main] [INFO ]  CamelLogger.log - Complete by=size rows=1000
[main] [INFO ]  CamelLogger.log - Complete by=size rows=1000
[main] [INFO ]  CamelLogger.log - Complete by=size rows=1000
[Camel thread #0 - AggregateTimeoutChecker] [INFO ]  CamelLogger.log - Complete by=interval rows=377
[main] [INFO ]  CamelLogger.log - Complete by=size rows=1000
[main] [INFO ]  CamelLogger.log - Complete by=size rows=1000
[main] [INFO ]  CamelLogger.log - Complete by=size rows=1000
[main] [INFO ]  CamelLogger.log - Complete by=size rows=1000
```

How to fix this?

Apache Camel 2.19.0

答:
gotcha!

I running as unit test... the context ends before complete completionInterval or completionTimeout

when I put a delay in my route I could see the total 33352 rows wrote.

<camel:delay>
  <constant>5000</constant>
</camel:delay>
```

<p>But in production isn't necessary, the context continue alive or we can use the option <code>forceCompletionOnStop</code>:</p>

<pre class="lang-xml prettyprint-override"><code><camel:aggregate strategyRef="setfepCsvStringBodyAggregator" forceCompletionOnStop="true" completionSize="1000" completionInterval="4000">
</code>```

Body:
Generate big files with Apache Camel with Aggregator with better performance as this post: Large Files with Apache Camel

My body has 33352 rows.. and using completionSize="1000" and completionTimeout="2500" the final file missed the last 352 rows

<camel:split streaming="true">
  <camel:simple>${body}</camel:simple>
  <camel:marshal>
    <camel:csv quote='"' quoteDisabled="false" headerDisabled="true" />
  </camel:marshal>
  <camel:aggregate strategyRef="setfepCsvStringBodyAggregator" completionSize="1000" completionTimeout="2500">
    <camel:correlationExpression>
      <constant>true</constant>
    </camel:correlationExpression>
    <to uri="file:{{setfep_dir_inprogress}}/?fileName={{setfep_filename_clientes}}.txt&fileExist=Append" />
  </camel:aggregate>
</camel:split>

Final file has 33000 rows missing 352.

[INFO ] org.apache.camel.util.CamelLogger.log - Complete by=size rows=1000
[INFO ] org.apache.camel.util.CamelLogger.log - Complete by=size rows=1000
[INFO ] org.apache.camel.util.CamelLogger.log - Complete by=size rows=1000
[INFO ] org.apache.camel.util.CamelLogger.log - Complete by=size rows=1000
[INFO ] org.apache.camel.util.CamelLogger.log - Complete by=size rows=1000
[INFO ] org.apache.camel.util.CamelLogger.log - Complete by=size rows=1000
[INFO ] org.apache.camel.util.CamelLogger.log - Complete by=size rows=1000
[INFO ] org.apache.camel.util.CamelLogger.log - Complete by=size rows=1000
[INFO ] org.apache.camel.util.CamelLogger.log - Complete by=size rows=1000
[INFO ] org.apache.camel.util.CamelLogger.log - Complete by=size rows=1000
[INFO ] org.apache.camel.util.CamelLogger.log - Complete by=size rows=1000
[INFO ] org.apache.camel.util.CamelLogger.log - Complete by=size rows=1000
[INFO ] org.apache.camel.util.CamelLogger.log - Complete by=size rows=1000
[INFO ] org.apache.camel.util.CamelLogger.log - Complete by=size rows=1000
[INFO ] org.apache.camel.util.CamelLogger.log - Complete by=size rows=1000
[INFO ] org.apache.camel.util.CamelLogger.log - Complete by=size rows=1000
[INFO ] org.apache.camel.util.CamelLogger.log - Complete by=size rows=1000
[INFO ] org.apache.camel.util.CamelLogger.log - Complete by=size rows=1000
[INFO ] org.apache.camel.util.CamelLogger.log - Complete by=size rows=1000
[INFO ] org.apache.camel.util.CamelLogger.log - Complete by=size rows=1000
[INFO ] org.apache.camel.util.CamelLogger.log - Complete by=size rows=1000
[INFO ] org.apache.camel.util.CamelLogger.log - Complete by=size rows=1000
[INFO ] org.apache.camel.util.CamelLogger.log - Complete by=size rows=1000
[INFO ] org.apache.camel.util.CamelLogger.log - Complete by=size rows=1000
[INFO ] org.apache.camel.util.CamelLogger.log - Complete by=size rows=1000
[INFO ] org.apache.camel.util.CamelLogger.log - Complete by=size rows=1000
[INFO ] org.apache.camel.util.CamelLogger.log - Complete by=size rows=1000
[INFO ] org.apache.camel.util.CamelLogger.log - Complete by=size rows=1000
[INFO ] org.apache.camel.util.CamelLogger.log - Complete by=size rows=1000
[INFO ] org.apache.camel.util.CamelLogger.log - Complete by=size rows=1000
[INFO ] org.apache.camel.util.CamelLogger.log - Complete by=size rows=1000
[INFO ] org.apache.camel.util.CamelLogger.log - Complete by=size rows=1000
[INFO ] org.apache.camel.util.CamelLogger.log - Complete by=size rows=1000

if I use completionSize="1000" and completionInterval="2500" my final file has 33155 hows missing 197 rows.

[Camel thread #0 - AggregateTimeoutChecker] [INFO ]  CamelLogger.log - Complete by=interval rows=566
[main] [INFO ]  CamelLogger.log - Complete by=size rows=1000
[main] [INFO ]  CamelLogger.log - Complete by=size rows=1000
[main] [INFO ]  CamelLogger.log - Complete by=size rows=1000
[main] [INFO ]  CamelLogger.log - Complete by=size rows=1000
[main] [INFO ]  CamelLogger.log - Complete by=size rows=1000
[main] [INFO ]  CamelLogger.log - Complete by=size rows=1000
[Camel thread #0 - AggregateTimeoutChecker] [INFO ]  CamelLogger.log - Complete by=interval rows=43
[main] [INFO ]  CamelLogger.log - Complete by=size rows=1000
[main] [INFO ]  CamelLogger.log - Complete by=size rows=1000
[main] [INFO ]  CamelLogger.log - Complete by=size rows=1000
[main] [INFO ]  CamelLogger.log - Complete by=size rows=1000
[main] [INFO ]  CamelLogger.log - Complete by=size rows=1000
[main] [INFO ]  CamelLogger.log - Complete by=size rows=1000
[main] [INFO ]  CamelLogger.log - Complete by=size rows=1000
[Camel thread #0 - AggregateTimeoutChecker] [INFO ]  CamelLogger.log - Complete by=interval rows=401
[main] [INFO ]  CamelLogger.log - Complete by=size rows=1000
[main] [INFO ]  CamelLogger.log - Complete by=size rows=1000
[main] [INFO ]  CamelLogger.log - Complete by=size rows=1000
[main] [INFO ]  CamelLogger.log - Complete by=size rows=1000
[main] [INFO ]  CamelLogger.log - Complete by=size rows=1000
[main] [INFO ]  CamelLogger.log - Complete by=size rows=1000
[main] [INFO ]  CamelLogger.log - Complete by=size rows=1000
[Camel thread #0 - AggregateTimeoutChecker] [INFO ]  CamelLogger.log - Complete by=interval rows=768
[main] [INFO ]  CamelLogger.log - Complete by=size rows=1000
[main] [INFO ]  CamelLogger.log - Complete by=size rows=1000
[main] [INFO ]  CamelLogger.log - Complete by=size rows=1000
[main] [INFO ]  CamelLogger.log - Complete by=size rows=1000
[main] [INFO ]  CamelLogger.log - Complete by=size rows=1000
[main] [INFO ]  CamelLogger.log - Complete by=size rows=1000
[main] [INFO ]  CamelLogger.log - Complete by=size rows=1000
[Camel thread #0 - AggregateTimeoutChecker] [INFO ]  CamelLogger.log - Complete by=interval rows=377
[main] [INFO ]  CamelLogger.log - Complete by=size rows=1000
[main] [INFO ]  CamelLogger.log - Complete by=size rows=1000
[main] [INFO ]  CamelLogger.log - Complete by=size rows=1000
[main] [INFO ]  CamelLogger.log - Complete by=size rows=1000

How to fix this?

Apache Camel 2.19.0

Body:
gotcha!

I running as unit test... the context ends before complete completionInterval or completionTimeout

when I put a delay in my route I could see the total 33352 rows wrote.

<camel:delay>
  <constant>5000</constant>
</camel:delay>

But in production isn't necessary, the context continue alive or we can use the option forceCompletionOnStop:

<camel:aggregate strategyRef="setfepCsvStringBodyAggregator" forceCompletionOnStop="true" completionSize="1000" completionInterval="4000">


问:
Errorstream in HttpUrlConnection
I want to do a POST request to an HTTP Servlet I wrote myself. Good case (HTTP response Code 200) always works fine by using URL.openConnection() method. But when I receive a desired error response code (e.g. 400) then I thought I have to use HttpUrlConnection.getErrorStream(). But the ErrorStream object is null though I am sending data back from the servlet in error case (I want to evaluate this data to generate error messages).
This is what my code looks like:

```<code>HttpURLConnection con = null;
        try {
            //Generating request String
            String request = "request="+URLEncoder.encode(xmlGenerator.getStringFromDocument(xmlGenerator.generateConnectRequest(1234)),"UTF-8");
            //Receiving HttpUrlConnection (DoOutput = true; RequestMethod is set to "POST")
            con = openConnection();
            if (con != null){
                PrintWriter pw = new PrintWriter(con.getOutputStream());
                pw.println(request);
                pw.flush();
                pw.close();
                InputStream errorstream = con.getErrorStream();

                BufferedReader br = null;
                if (errorstream == null){
                    InputStream inputstream = con.getInputStream();
                    br = new BufferedReader(new InputStreamReader(inputstream));
                }else{
                    br = new BufferedReader(new InputStreamReader(errorstream));
                }
                String response = "";
                String nachricht;
                while ((nachricht = br.readLine()) != null){
                    response += nachricht;
                }
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
</code>```

So my question is, why returns getErrorStream() null though status code is 400 (I can see it in the IOException that is thrown when it calls con.getInputStream())

Thanks

答:
Put the statement conn.setAllowUserInteraction(true); before execute the request and the connection will not be closed, even receiving 401 status.

```<code>conn.setDoInput(true);
conn.setDoOutput(true);
conn.setAllowUserInteraction(true); //                <<<--- ### HERE
//do something
conn.connect();
boolean isError = (conn.getResponseCode() >= 400);
InputSteam is = isError ? con.getErrorStream() : con.getInputStream();
</code>```

Title: Errorstream in HttpUrlConnection

Body:
I want to do a POST request to an HTTP Servlet I wrote myself. Good case (HTTP response Code 200) always works fine by using URL.openConnection() method. But when I receive a desired error response code (e.g. 400) then I thought I have to use HttpUrlConnection.getErrorStream(). But the ErrorStream object is null though I am sending data back from the servlet in error case (I want to evaluate this data to generate error messages).
This is what my code looks like:

HttpURLConnection con = null;
        try {
            //Generating request String
            String request = "request="+URLEncoder.encode(xmlGenerator.getStringFromDocument(xmlGenerator.generateConnectRequest(1234)),"UTF-8");
            //Receiving HttpUrlConnection (DoOutput = true; RequestMethod is set to "POST")
            con = openConnection();
            if (con != null){
                PrintWriter pw = new PrintWriter(con.getOutputStream());
                pw.println(request);
                pw.flush();
                pw.close();
                InputStream errorstream = con.getErrorStream();

                BufferedReader br = null;
                if (errorstream == null){
                    InputStream inputstream = con.getInputStream();
                    br = new BufferedReader(new InputStreamReader(inputstream));
                }else{
                    br = new BufferedReader(new InputStreamReader(errorstream));
                }
                String response = "";
                String nachricht;
                while ((nachricht = br.readLine()) != null){
                    response += nachricht;
                }
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

So my question is, why returns getErrorStream() null though status code is 400 (I can see it in the IOException that is thrown when it calls con.getInputStream())

Thanks

Body:
Put the statement conn.setAllowUserInteraction(true); before execute the request and the connection will not be closed, even receiving 401 status.

conn.setDoInput(true);
conn.setDoOutput(true);
conn.setAllowUserInteraction(true); //                <<<--- ### HERE
//do something
conn.connect();
boolean isError = (conn.getResponseCode() >= 400);
InputSteam is = isError ? con.getErrorStream() : con.getInputStream();


问:
symfony 3 and FOSRest Bundle Routing
I am trying to setup the symfony3 codebase with FOS REST Bundle and I end up getting no route found error

AppBundle\Resources\config\api-routing.yml

check:
    type: rest
    resource: "@AppBundle/Controller/CheckController.php"
```
<p>app\config\routing.yml</p>
<pre class="lang-yaml prettyprint-override"><code>app:
    type: rest
    prefix: /
    resource: '@AppBundle/Resources/config/api-routing.yml'
</code>```

controller

```<code>namespace AppBundle\Controller;

use FOS\RestBundle\Controller\FOSRestController;
use FOS\RestBundle\Controller\Annotations\Version;
use FOS\RestBundle\Controller\Annotations\RouteResource;
use Symfony\Component\HttpFoundation\Request;

/**
 * @RouteResource("Check")
 * @Version("v1")
 */

class CheckController extends FOSRestController
{

    public function getAction(Request $request)
    {
        $data = "Ok";
        return new JsonResponse($data);
    }
}

http://127.0.0.1:8000/v1/app/check/ return no route
</code>```

I would like to integrate the versioning of rest api route. Can you share what cud be the error and how can I correct this ?

fos_rest:
    body_listener: true
    versioning:
        enabled: true
        resolvers:
            query:
                enabled: true
                parameter_name: version
    format_listener:
        rules:
            - { path: '^/', priorities: ['json'], fallback_format: json, prefer_extension: false }
    param_fetcher_listener: true
    view:
        view_response_listener: 'force'
        formats:
            json: true
```

答:
Here is working example.

app\config\routng.yml

```<code>app:
    type: rest
    resource: "@AppBundle/Resources/config/routing.yml"
    prefix: /api
</code>```

AppBundle\Resources\config\routing.yml

```<code>rest_my:
    type: rest
    prefix: /v1
    resource: "@AppBundle/Controller/MyRestController.php"
    name_prefix:  api_1_
</code>```

Active route will be:

```<code>http://127.0.0.1:8000/api/v1/<MyRestControllerAction>
</code>```

or for second controller

AppBundle\Resources\config\routing.yml

```<code>rest_user:
    type: rest
    prefix: /v1/user
    resource: "@AppBundle/Controller/UserRestController.php"
    name_prefix:  api_1_
</code>```

Active route will be:

```<code>http://127.0.0.1:8000/api/v1/user/<UserRestControllerAction>
</code>```

I hope I help you... Chears.

Update #1:
Here is my complete fos_rest configuration for json format into config.yml file:

```<code>fos_rest:
    routing_loader:
        default_format: json
        include_format: false
    body_converter:
        enabled: true
    body_listener:
        decoders:
            json: fos_rest.decoder.json
    format_listener:
        enabled: true
        rules:
            - { path: '^/api/v1/', priorities: ['json'], fallback_format: json, prefer_extension: true}
            - { path: '^/', priorities: ['json', 'html'], fallback_format: 'html' }
    serializer:
        serialize_null: true
    view:
        view_response_listener: 'force'
        templating_formats:
            html: false
    param_fetcher_listener: 'force'
</code>```

If you need more then that you have full documentation for fos_rest
http://symfony.com/doc/current/bundles/FOSRestBundle/configuration-reference.html

Title: symfony 3 and FOSRest Bundle Routing

Body:
I am trying to setup the symfony3 codebase with FOS REST Bundle and I end up getting no route found error

AppBundle\Resources\config\api-routing.yml

check:
    type: rest
    resource: "@AppBundle/Controller/CheckController.php"

app\config\routing.yml

app:
    type: rest
    prefix: /
    resource: '@AppBundle/Resources/config/api-routing.yml'

controller

namespace AppBundle\Controller;

use FOS\RestBundle\Controller\FOSRestController;
use FOS\RestBundle\Controller\Annotations\Version;
use FOS\RestBundle\Controller\Annotations\RouteResource;
use Symfony\Component\HttpFoundation\Request;

/**
 * @RouteResource("Check")
 * @Version("v1")
 */

class CheckController extends FOSRestController
{

    public function getAction(Request $request)
    {
        $data = "Ok";
        return new JsonResponse($data);
    }
}

http://127.0.0.1:8000/v1/app/check/ return no route

I would like to integrate the versioning of rest api route. Can you share what cud be the error and how can I correct this ?

fos_rest:
    body_listener: true
    versioning:
        enabled: true
        resolvers:
            query:
                enabled: true
                parameter_name: version
    format_listener:
        rules:
            - { path: '^/', priorities: ['json'], fallback_format: json, prefer_extension: false }
    param_fetcher_listener: true
    view:
        view_response_listener: 'force'
        formats:
            json: true

Body:
Here is working example.

app\config\routng.yml

app:
    type: rest
    resource: "@AppBundle/Resources/config/routing.yml"
    prefix: /api

AppBundle\Resources\config\routing.yml

rest_my:
    type: rest
    prefix: /v1
    resource: "@AppBundle/Controller/MyRestController.php"
    name_prefix:  api_1_

Active route will be:

http://127.0.0.1:8000/api/v1/<MyRestControllerAction>

or for second controller

AppBundle\Resources\config\routing.yml

rest_user:
    type: rest
    prefix: /v1/user
    resource: "@AppBundle/Controller/UserRestController.php"
    name_prefix:  api_1_

Active route will be:

http://127.0.0.1:8000/api/v1/user/<UserRestControllerAction>

I hope I help you... Chears.

Update #1:
Here is my complete fos_rest configuration for json format into config.yml file:

fos_rest:
    routing_loader:
        default_format: json
        include_format: false
    body_converter:
        enabled: true
    body_listener:
        decoders:
            json: fos_rest.decoder.json
    format_listener:
        enabled: true
        rules:
            - { path: '^/api/v1/', priorities: ['json'], fallback_format: json, prefer_extension: true}
            - { path: '^/', priorities: ['json', 'html'], fallback_format: 'html' }
    serializer:
        serialize_null: true
    view:
        view_response_listener: 'force'
        templating_formats:
            html: false
    param_fetcher_listener: 'force'

If you need more then that you have full documentation for fos_rest
http://symfony.com/doc/current/bundles/FOSRestBundle/configuration-reference.html