问:
HTML5: Playing HTTP streaming on HTTPS domain
Can I play HTTP streaming on HTTPS domain without browser's security errors? The browser blocks that requests by default.

I use hls.js library for .m3u8 desktop playing support. When I play content natively without it (via mobile or Mac's Safari), the browser shows warning but doesn't blocks requests. But when I play it on same devices with hls.js enabled, or via desktop browsers, the requests are blocked.

答:
You can't.

Mixed content, when you have resources served over http on a https site, can be passive or active.

Passive:

Images

Videos

Audio

Active:

Javascript

CSS

iFrames

Objects (flash, etc.)

XHR (requests made with javascript)

The problem is that your video is fetched with hls.js, which is considered active content (see that last bullet), and therefore blocked.

However, if the browser fetches it through a <video> element, it is considered passive content and allowed.

Suggestions / workarounds

Switch your video servers to HTTPS. This is the preferred option. HTTPS is faster. You said that your server's administrator says that the HTTPS will "overload videoservers". I doubt that. Try it out and see.

If you stop reading now you only need to remember one thing: SSL/TLS is not computationally expensive any more. -- Adam Langley (Google)

Switch to a diffrent video format, like mp4 or ogg or load both. Your website will load faster because you don't need a library.

<s>Switch to http</s> DON'T DO THIS


来源: stackexchange

问:
Links (without /index in them) are not pointing to index of that subdirectory
I've looked for about two hours for a way of solving, this to no avail:

Just to make it easier I'm providing links: malumkose.com malumkose.com/hizmetler

In the main page (first link) there is a button link to the page "hizmetler."

When I was linking these pages to one another, I didn't add in the /index or /index.html extensions to the links, and thought it would work on the server as it did on localhost.

The thing is, my site is peppered with these links - they're all over the joint! I would go and manually change these to add the file extension, but that would only cause the link to direct me to "hizmetler/index" instead of just "hizmetler."

I have tried adding the first line here to my .htaccess file, but it still doesn't point links without index in them, to the indexes of these subdirectories.

```<code>`DirectoryIndex index.html
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.html [NC,L]`
</code>```

How could I possibly kill these two birds with one stone?

答:
I don't completely understand the structure for the files of your pages, but this should help for your .htaccess file:

```<code>Options +FollowSymLinks
RewriteEngine On
DirectoryIndex index.html

RewriteRule ^hizmetler$ ./hizmetler/index.html
RewriteRule ^something$ ./something/index.html
RewriteRule ^something-else$ ./something-else/index.html
</code>```

Then it will work as follow:

malumkose.com/ > /index.html

malumkose.com/hizmetler > /hizmetler/index.html

malumkose.com/something > /something/index.html

malumkose.com/something-esle > /something-else/index.html

If you want to force SSL/HTTPS, then add (between the enter of the above script):

```<code>RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I've looked for about two hours for a way of solving, this to no avail:

Just to make it easier I'm providing links: malumkose.com malumkose.com/hizmetler

In the main page (first link) there is a button link to the page "hizmetler."

When I was linking these pages to one another, I didn't add in the /index or /index.html extensions to the links, and thought it would work on the server as it did on localhost.

The thing is, my site is peppered with these links - they're all over the joint! I would go and manually change these to add the file extension, but that would only cause the link to direct me to "hizmetler/index" instead of just "hizmetler."

I have tried adding the first line here to my .htaccess file, but it still doesn't point links without index in them, to the indexes of these subdirectories.

`DirectoryIndex index.html
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.html [NC,L]`

How could I possibly kill these two birds with one stone?

Body:
I don't completely understand the structure for the files of your pages, but this should help for your .htaccess file:

Options +FollowSymLinks
RewriteEngine On
DirectoryIndex index.html

RewriteRule ^hizmetler$ ./hizmetler/index.html
RewriteRule ^something$ ./something/index.html
RewriteRule ^something-else$ ./something-else/index.html

Then it will work as follow:

malumkose.com/ > /index.html

malumkose.com/hizmetler > /hizmetler/index.html

malumkose.com/something > /something/index.html

malumkose.com/something-esle > /something-else/index.html

If you want to force SSL/HTTPS, then add (between the enter of the above script):

RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]


问:
Handling Local vs Remote Database TimeZone Differences in Tests
I have unit test in Java that writes a constant Timestamp to a row in my local test database, reads it back and compares it to what I expected. This works fine on my local laptop which is under the GMT timezone.

When I commit the code to our continuous integration server, the test fails with the different in time being -5 hours. This is no surprise since our integration server is hosted on AWS on the East Coast of US. However, it is causing a problem...

Short of changing my local MySQL server to have the same timezone as the remote server (and having all the developers in my team do so also), can anyone show me how to fix this issue in code without getting too hacky?

```<code>//Fetch actual table contents
IDataSet databaseDataSet = databaseTester.getConnection().createDataSet();
ITable actualTable = databaseDataSet.getTable("batch");

// Load expected data from an XML dataset
IDataSet expectedDataSet = new XmlDataSet(getClass().getResourceAsStream("/dbunit/expected_insert_batch.xml"));
ITable expectedTable = expectedDataSet.getTable("batch");

// Assert actual database table match expected table
Assertion.assertEquals(expectedTable, actualTable);
</code>```

Thanks,

答:
OK, this may not be the best option, but why not create another

```<code>"/dbunit/expected_insert_batch.xml"
</code>```

for your CI server. Then add a switch in your unit test for timezone.

ContentLicense: CC BY-SA 2.5

Body:
I have unit test in Java that writes a constant Timestamp to a row in my local test database, reads it back and compares it to what I expected. This works fine on my local laptop which is under the GMT timezone.

When I commit the code to our continuous integration server, the test fails with the different in time being -5 hours. This is no surprise since our integration server is hosted on AWS on the East Coast of US. However, it is causing a problem...

Short of changing my local MySQL server to have the same timezone as the remote server (and having all the developers in my team do so also), can anyone show me how to fix this issue in code without getting too hacky?

//Fetch actual table contents
IDataSet databaseDataSet = databaseTester.getConnection().createDataSet();
ITable actualTable = databaseDataSet.getTable("batch");

// Load expected data from an XML dataset
IDataSet expectedDataSet = new XmlDataSet(getClass().getResourceAsStream("/dbunit/expected_insert_batch.xml"));
ITable expectedTable = expectedDataSet.getTable("batch");

// Assert actual database table match expected table
Assertion.assertEquals(expectedTable, actualTable);

Thanks,

Body:
OK, this may not be the best option, but why not create another

"/dbunit/expected_insert_batch.xml"

for your CI server. Then add a switch in your unit test for timezone.


问:
UIPickerView Delegate Method return nil
I am using a UIPickerView instance to determine certain setting in my project.

In my viewDidLoad(), I initialise an array which includes all my data:

```<code>pickerData = ["5 Minutes", "6 Minutes","7 Minutes","8 Minutes","9 Minutes","10 Minutes","11 Minutes","12 Minutes","13 Minutes","14 Minutes","15 Minutes","16 Minutes","17 Minutes","18 Minutes","19 Minutes","20 Minutes","21 Minutes","22 Minutes","23 Minutes","24 Minutes","25 Minutes","26 Minutes","27 Minutes","28 Minutes","29 Minutes","30 Minutes","31 Minutes","32 Minutes","33 Minutes","34 Minutes","35 Minutes","36 Minutes","37 Minutes","38 Minutes","39 Minutes","40 Minutes","41 Minutes","42 Minutes","43 Minutes","44 Minutes","45 Minutes","46 Minutes","47 Minutes","48 Minutes","49 Minutes","50 Minutes","51 Minutes","52 Minutes","53 Minutes","54 Minutes","55 Minutes","56 Minutes","57 Minutes","58 Minutes","59 Minutes","60 Minutes",]
</code>```

In UIPickerView delegate method, I need to retrieve the one element at certain index then convert it into an Integer.

```<code>func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

        let minuteIndex = Int(pickerData[row])
        print(minuteIndex)
    }
</code>```

When I start to make my selection in the UIPickView,
Xcode console print every selection as nil.

I am quite confuse what's wrong? How to resolve this, thanks in advance.

答:
You're trying to cast* a String which is not a pure Int into an Int.
Try removing the "Minutes" part from your values and see if it works.

Edit: cast not convert.

Title: UIPickerView Delegate Method return nil

Body:
I am using a UIPickerView instance to determine certain setting in my project.

In my viewDidLoad(), I initialise an array which includes all my data:

pickerData = ["5 Minutes", "6 Minutes","7 Minutes","8 Minutes","9 Minutes","10 Minutes","11 Minutes","12 Minutes","13 Minutes","14 Minutes","15 Minutes","16 Minutes","17 Minutes","18 Minutes","19 Minutes","20 Minutes","21 Minutes","22 Minutes","23 Minutes","24 Minutes","25 Minutes","26 Minutes","27 Minutes","28 Minutes","29 Minutes","30 Minutes","31 Minutes","32 Minutes","33 Minutes","34 Minutes","35 Minutes","36 Minutes","37 Minutes","38 Minutes","39 Minutes","40 Minutes","41 Minutes","42 Minutes","43 Minutes","44 Minutes","45 Minutes","46 Minutes","47 Minutes","48 Minutes","49 Minutes","50 Minutes","51 Minutes","52 Minutes","53 Minutes","54 Minutes","55 Minutes","56 Minutes","57 Minutes","58 Minutes","59 Minutes","60 Minutes",]

In UIPickerView delegate method, I need to retrieve the one element at certain index then convert it into an Integer.

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

        let minuteIndex = Int(pickerData[row])
        print(minuteIndex)
    }

When I start to make my selection in the UIPickView,
Xcode console print every selection as nil.

I am quite confuse what's wrong? How to resolve this, thanks in advance.


问:
Scroll view scrolls the list view not the layout
I am developing a layout which contains two listviews. when the listviews expand beyond the layout size, I want to scroll the layout but its scrolls the listview.

How to scrolls the layout instead of the listviews.

My Code:

fragment_one.xml

```<code>        <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:fillViewport="true" >

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:padding="10dip" >

                <ListView
                    android:id="@+id/list_nation"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="10dip"
                    android:background="#B29090" >
                </ListView>

                <ListView
                    android:id="@+id/list_regional"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="10dip"
                    android:background="#4A9C67" >
                </ListView>
            </LinearLayout>

        </ScrollView>
</code>```

答:
try NestedScrollView like,</p>

```<code>  <android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:fillViewport="true" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:padding="10dip" >

            <ListView
                android:id="@+id/list_nation"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dip"
                android:background="#B29090" >
            </ListView>

            <ListView
                android:id="@+id/list_regional"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dip"
                android:background="#4A9C67" >
            </ListView>
        </LinearLayout>

     </android.support.v4.widget.NestedScrollView>
</code>```

Body:
I am developing a layout which contains two listviews. when the listviews expand beyond the layout size, I want to scroll the layout but its scrolls the listview.

How to scrolls the layout instead of the listviews.

My Code:

fragment_one.xml

        <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:fillViewport="true" >

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:padding="10dip" >

                <ListView
                    android:id="@+id/list_nation"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="10dip"
                    android:background="#B29090" >
                </ListView>

                <ListView
                    android:id="@+id/list_regional"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="10dip"
                    android:background="#4A9C67" >
                </ListView>
            </LinearLayout>

        </ScrollView>

Body:
try NestedScrollView like,

  <android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:fillViewport="true" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:padding="10dip" >

            <ListView
                android:id="@+id/list_nation"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dip"
                android:background="#B29090" >
            </ListView>

            <ListView
                android:id="@+id/list_regional"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dip"
                android:background="#4A9C67" >
            </ListView>
        </LinearLayout>

     </android.support.v4.widget.NestedScrollView>


问:
JQuery click() on anchor tag not firing from an injected script inside WebBrowser control
I am developing a web bot using WinForms WebBrowser control. Everything is working fine except for the second click() call in following code:

```<code>function SaveRecordClick() {
    try {
        var menuButton = $('#s_at_m_4');
        menuButton.click();             //<-- This is working
        var x = $('#s_at_m_4-menu li')[5];
        var saveLink = $(x).find('a')[0];
        if (saveLink != null){
            saveLink.click();           //<-- This is not working

            return "1";
        }
    }
    catch (err) {
        alert(err.message);
    }
    return "0";
}
</code>```

saveLink is not null. I know this because I placed an alert() call inside the condition.

Updated code with suggested solutions

```<code>function SaveRecordClick() {
    try {
        var menuButton = $('#s_at_m_4');
        menuButton.click();
        var x = $('#s_at_m_4-menu li').eq(5);
        var saveLink = x.find('a').eq(0);
        if (saveLink != null) {
            alert(saveLink.html());
            saveLink.click();

            return "1";
        }
    }
    catch (err) {
        alert(err.message);
    }
    return "0";
}
</code>```

But still the same problem. 'alert()' is working fine but html() is showing inner text instead of HTML of the anchor.

HTML Code

```<code><li data-caption="Save Record                [Ctrl+S]" class="sbui-appletmenu-item  ui-menu-item" role="presentation">
<a href="javascript:void(0)" aria-disabled="false" class="ui-corner-all" id="ui-id-254" tabindex="-1" role="menuitem">Save Record                [Ctrl+S]</a>
</li>
</code>```

ID of the anchor tag is dynamically generated.

Also, click() is triggering when the same code is executed from Google Chrome Console. So, could it be the issue with the WebBrowser control?

Update

I think guys its a problem with the webrowser control that inherits Internet Explorer. So now I am shifting to another browser control and testing the code on it. Will let you know if it works there.

答:
Thank you everyone for your answers and comments.

After spending a week in researching the third party website, today I finally found the solution to my problem. Actually the problem was not with JavaScript or HTML but the way the website validate the form I am trying to autofill using my bot.

I awarded bounty to the answer whose conversation in comments gave me some hints.

The click on saveLink was not firing because I was programmatically setting a value of a text box using .val() but for some reason the website was not saving values directly set using this function. But when I changed the value using a combo box that loads value for the textbox from the server (Although the value set from server or using val() function are exactly same.), then the click successfully fired after that.

I also used setTimeout() at various places because the code was executing too fast before the value can be set in some form fields.

So in future if someone faces a similar problem then make sure you study the behavior of the page or form you are trying to submit.

Body:
I am developing a web bot using WinForms WebBrowser control. Everything is working fine except for the second click() call in following code:

function SaveRecordClick() {
    try {
        var menuButton = $('#s_at_m_4');
        menuButton.click();             //<-- This is working
        var x = $('#s_at_m_4-menu li')[5];
        var saveLink = $(x).find('a')[0];
        if (saveLink != null){
            saveLink.click();           //<-- This is not working

            return "1";
        }
    }
    catch (err) {
        alert(err.message);
    }
    return "0";
}

saveLink is not null. I know this because I placed an alert() call inside the condition.

Updated code with suggested solutions

function SaveRecordClick() {
    try {
        var menuButton = $('#s_at_m_4');
        menuButton.click();
        var x = $('#s_at_m_4-menu li').eq(5);
        var saveLink = x.find('a').eq(0);
        if (saveLink != null) {
            alert(saveLink.html());
            saveLink.click();

            return "1";
        }
    }
    catch (err) {
        alert(err.message);
    }
    return "0";
}

But still the same problem. 'alert()' is working fine but html() is showing inner text instead of HTML of the anchor.

HTML Code

Save Record                [Ctrl+S]

ID of the anchor tag is dynamically generated.

Also, click() is triggering when the same code is executed from Google Chrome Console. So, could it be the issue with the WebBrowser control?

Update

I think guys its a problem with the webrowser control that inherits Internet Explorer. So now I am shifting to another browser control and testing the code on it. Will let you know if it works there.


问:
Laravel 5.4 null csrf_token() when posting to route
I'm sending an ajax post request, and with Laravel it seems that is done by creating a post route for it. I've set it up so a csrf token is put in the header automaticaly for every ajax request using ajaxSetup. I'm attempting to then catch that header on the backend and verify the tokens match.

In my web routes (which automatically use the web middleware), this returns as expected:

```<code>Route::get('/test', function() {
    return csrf_token();
});
</code>```

However, when I post to a route via AJAX, like either of the below ways:

Attempt 1:

```<code>Route::post('/test', 'AjaxController@test');
</code>```

In the AjaxController construct, followed by an alert in the view:

```<code>var_dump(csrf_token().',hi'); die;
</code>```

Response: ',hi' (csrf_token was null).

Attempt 2:

```<code>Route::post('/test', ['test' => csrf_token().',hi', 'uses' => 'AjaxController@test']);

$test = $request->route()->getAction()['test'];
var_dump($test); die;
</code>```

Response: ',hi' (csrf_token was null).

What I seem to be running into is, with get requests csrf_token() is populated, on my post request, it is not.

Any ideas?

答:
csrf protections are managed by Laravel Forms. It won't be available when dealing with APIs.

You should have a look at how middlewares are used in Laravel
https://laravel.com/docs/5.4/middleware

Think using API middleware for your APIs ;)

Body:
I'm sending an ajax post request, and with Laravel it seems that is done by creating a post route for it. I've set it up so a csrf token is put in the header automaticaly for every ajax request using ajaxSetup. I'm attempting to then catch that header on the backend and verify the tokens match.

In my web routes (which automatically use the web middleware), this returns as expected:

Route::get('/test', function() {
    return csrf_token();
});

However, when I post to a route via AJAX, like either of the below ways:

Attempt 1:

Route::post('/test', 'AjaxController@test');

In the AjaxController construct, followed by an alert in the view:

var_dump(csrf_token().',hi'); die;

Response: ',hi' (csrf_token was null).

Attempt 2:

Route::post('/test', ['test' => csrf_token().',hi', 'uses' => 'AjaxController@test']);

$test = $request->route()->getAction()['test'];
var_dump($test); die;

Response: ',hi' (csrf_token was null).

What I seem to be running into is, with get requests csrf_token() is populated, on my post request, it is not.

Any ideas?


问:
Java orm problem
There is a big table business_apply in our system. It's used to store business apply information, and contains hundreds of columns.

When business type differs, a column may mean different things.

What kind of orm framework can make our life easier? Hibernate, iBatis or something else?

答:
According to your description you are using "wrong" DB schema:

table may contain hundreds (!) of columns

"when business type diffs ,a column may means different things"

So, hibernate is not for you. This tool is good for "right" solutions. Hibernate cannot help you too much because it cannot map your data to java object. You need some kind of custom implementation of such mapping.

I think that you need plain JDBC or a very simple helper like DBUtils from jakarta. Once you connected to DB and managed to access your big table implement a custom mechanism (probably per business) that maps bulk of your data to your value objects.

Title: Java orm problem


问:
iOS Swift Textfield Inside Tableview
I'm having three textfields inside tableview. I need to set range for each textfield like:

TextField1 -> MobileNumber -> I not allow user to type more than 10 digit

Textfield2 -> PostalCode -> I not allow user to type more than 6 digit

Textfield3 -> UserName -> I not allow user to leave first character as empty

答:
Assuming that the 3 text fields are in the same cell:

Create 3 different UITextFields in the UI Builder and put them inside a cell in the table view.

Click on the first text field and from the attributes inspector set its tag property to 1. Set the tag property of the 2 other text fields to 2 and 3.

tag 1 for mobile number text field.

tag 2 for postal code text field.

tag 3 for user name text field.

Now, in your cellForRowAtIndex method and at the index of the cell that contains the 3 text fields:

```<code>if let mobileNumberTextField = cell.viewWithTag(1) as UITextField {
    // Customize mobileNumberTextField
}

if let postalCodeTextField = cell.viewWithTag(2) as UITextField {
    // Customize postalCodeTextField
}

if let userNameTextField = cell.viewWithTag(3) as UITextField {
    // Customize userNameTextField
}
</code>```

You can achieve the same result by subclassing UITableViewCell and making the 3 text fields properties in it.

Title: iOS Swift Textfield Inside Tableview

Body:
Assuming that the 3 text fields are in the same cell:

Create 3 different UITextFields in the UI Builder and put them inside a cell in the table view.

Click on the first text field and from the attributes inspector set its tag property to 1. Set the tag property of the 2 other text fields to 2 and 3.

tag 1 for mobile number text field.

tag 2 for postal code text field.

tag 3 for user name text field.

Now, in your cellForRowAtIndex method and at the index of the cell that contains the 3 text fields:

if let mobileNumberTextField = cell.viewWithTag(1) as UITextField {
    // Customize mobileNumberTextField
}

if let postalCodeTextField = cell.viewWithTag(2) as UITextField {
    // Customize postalCodeTextField
}

if let userNameTextField = cell.viewWithTag(3) as UITextField {
    // Customize userNameTextField
}

You can achieve the same result by subclassing UITableViewCell and making the 3 text fields properties in it.


问:
how to highlight max and min points on lineChart
I use dc.js lineChart and barChart. Now I need to mark the maximum and minimum values on my lineChart with 'renderArea(true)'.

I want something like in the picture below or maybe something else, but I don't know how to add this feature.

Update:

Gordon's answer is perfect. Unfortunately, my chart doesn't show the hint with 'mouseover' on marked points

One more update:

How can I redraw these points after zooming?

答:
This isn't something supported directly by dc.js, but you can annotate the chart with a renderlet. Gladly, dc.js makes it easy to escape out to d3 when you need custom annotations like this.

We'll use the fact that by default the line chart draws invisible dots at each data point (which only appear when they are hovered over). We'll grab the coordinates from those and use them to draw or update our own dots in another layer.

Usually we'd want to use a pretransition event handler, but those dots don't seem to have positions until after the transition, so we'll have to handle the renderlet event instead:

```<code>chart.on('renderlet', function(chart) { // 1
  // create a layer for the highlights, only once
  // insert it after the tooltip/dots layer
  var highlightLayer = chart.select('g.chart-body') // 2
    .selectAll('g.highlight-dots').data([0]);
  highlightLayer
    .enter().insert('g', 'g.dc-tooltip-list').attr('class', 'highlight-dots');
  chart.selectAll('g.dc-tooltip').each(function(_, stacki) { // 3
    var dots = d3.select(this).selectAll('circle.dot'); // 4
    var data = dots.data();
    var mini = 0, maxi = 0;
    data.forEach(function(d, i) { // 5
      if(i===0) return;
      if(d.y < data[mini].y)
        mini = i;
      if(d.y > data[maxi].y)
        maxi = i;
    });
    var highlightData = [mini, maxi].map(function(i) { // 6
      var dot = dots.filter(function(_, j) { return j === i; });
      return {
        x: dot.attr('cx'),
        y: dot.attr('cy'),
        color: dot.attr('fill')
      }
    });
    var highlights = highlightLayer.selectAll('circle.minmax-highlight._' + stacki).data(highlightData);
    highlights
      .enter().append('circle') // 7
      .attr({
      class: 'minmax-highlight _' + stacki,
      r: 10,
      'fill-opacity': 0.2,
      'stroke-opacity': 0.8
    });
    highlights.attr({ // 8
      cx: function(d) { return d.x; },
      cy: function(d) { return d.y; },
      stroke: function(d) { return d.color; },
      fill: function(d) { return d.color; }
    });
  });
});
</code>```

This is fairly complicated, so let's look at it step-by-step:

We're listening for the renderlet event, which fires after everything has transitioned

We'll create another layer. The .data([0]).enter().insert(stuff) trick is a degenerate case of the d3 general update pattern that just makes sure an item is added exactly once. We specify the selector for the existing tooltip/dots layer as the second parameter to .insert(), in order to put this layer before in DOM order, which means behind. Also, we'll hold onto the update selection because that is either the inserted node or the existing node.

We iterate through each of the stacks of tooltip-dots

In each stack, we'll select all the existing dots,

and iterate over all their data, finding the minimum and maximum indices mini and maxi.

Now we'll create a two-element data array for binding to the min/max highlight dots, pulling data from the existing dots

Now we're finally ready to draw stuff. We'll use the same degenerate update pattern to draw two dots with class minmax-highlight _1, _2, etc.

And use the color and positions that we remembered in step 6

Note that the min and max for each stack is not necessarily the same as the total min and max, so the highlighted points for a higher stack might not be the highest or lowest points.

Not so simple, but not too hard if you're willing to do some d3 hacking.

Example fiddle: http://jsfiddle.net/gordonwoodhull/7vptdou5/31/

Body:
This isn't something supported directly by dc.js, but you can annotate the chart with a renderlet. Gladly, dc.js makes it easy to escape out to d3 when you need custom annotations like this.

We'll use the fact that by default the line chart draws invisible dots at each data point (which only appear when they are hovered over). We'll grab the coordinates from those and use them to draw or update our own dots in another layer.

Usually we'd want to use a pretransition event handler, but those dots don't seem to have positions until after the transition, so we'll have to handle the renderlet event instead:

chart.on('renderlet', function(chart) { // 1
  // create a layer for the highlights, only once
  // insert it after the tooltip/dots layer
  var highlightLayer = chart.select('g.chart-body') // 2
    .selectAll('g.highlight-dots').data([0]);
  highlightLayer
    .enter().insert('g', 'g.dc-tooltip-list').attr('class', 'highlight-dots');
  chart.selectAll('g.dc-tooltip').each(function(_, stacki) { // 3
    var dots = d3.select(this).selectAll('circle.dot'); // 4
    var data = dots.data();
    var mini = 0, maxi = 0;
    data.forEach(function(d, i) { // 5
      if(i===0) return;
      if(d.y < data[mini].y)
        mini = i;
      if(d.y > data[maxi].y)
        maxi = i;
    });
    var highlightData = [mini, maxi].map(function(i) { // 6
      var dot = dots.filter(function(_, j) { return j === i; });
      return {
        x: dot.attr('cx'),
        y: dot.attr('cy'),
        color: dot.attr('fill')
      }
    });
    var highlights = highlightLayer.selectAll('circle.minmax-highlight._' + stacki).data(highlightData);
    highlights
      .enter().append('circle') // 7
      .attr({
      class: 'minmax-highlight _' + stacki,
      r: 10,
      'fill-opacity': 0.2,
      'stroke-opacity': 0.8
    });
    highlights.attr({ // 8
      cx: function(d) { return d.x; },
      cy: function(d) { return d.y; },
      stroke: function(d) { return d.color; },
      fill: function(d) { return d.color; }
    });
  });
});

This is fairly complicated, so let's look at it step-by-step:

We're listening for the renderlet event, which fires after everything has transitioned

We'll create another layer. The .data([0]).enter().insert(stuff) trick is a degenerate case of the d3 general update pattern that just makes sure an item is added exactly once. We specify the selector for the existing tooltip/dots layer as the second parameter to .insert(), in order to put this layer before in DOM order, which means behind. Also, we'll hold onto the update selection because that is either the inserted node or the existing node.

We iterate through each of the stacks of tooltip-dots

In each stack, we'll select all the existing dots,

and iterate over all their data, finding the minimum and maximum indices mini and maxi.

Now we'll create a two-element data array for binding to the min/max highlight dots, pulling data from the existing dots

Now we're finally ready to draw stuff. We'll use the same degenerate update pattern to draw two dots with class minmax-highlight _1, _2, etc.

And use the color and positions that we remembered in step 6

Note that the min and max for each stack is not necessarily the same as the total min and max, so the highlighted points for a higher stack might not be the highest or lowest points.

Not so simple, but not too hard if you're willing to do some d3 hacking.

Example fiddle: http://jsfiddle.net/gordonwoodhull/7vptdou5/31/


问:
Flatmap scala [String, String,List[String]]
I have this prbolem, I have an RDD[(String,String,  List[String]), and I would like to "flatmap" it to obtain a RDD[(String,String,  String)]:

e.g:

```<code>val x :RDD[(String,String,  List[String]) =
RDD[(a,b, list[ "ra", "re", "ri"])]
</code>```

I would like get:

```<code>val result: RDD[(String,String,String)] =
RDD[(a, b, ra),(a, b, re),(a, b, ri)])]
</code>```

答:
This is an alternative way of doing it using flatMap again

```<code>val rdd  =  sparkContext.parallelize(Seq(("a", "b", List("ra", "re", "ri"))))
rdd.flatMap(array => array._3.map(list => (array._1, array._2, list))).foreach(println)
</code>```

Body:
I have this prbolem, I have an RDD[(String,String,  List[String]), and I would like to "flatmap" it to obtain a RDD[(String,String,  String)]:

e.g:

val x :RDD[(String,String,  List[String]) =
RDD[(a,b, list[ "ra", "re", "ri"])]

I would like get:

val result: RDD[(String,String,String)] =
RDD[(a, b, ra),(a, b, re),(a, b, ri)])]

Body:
This is an alternative way of doing it using flatMap again

val rdd  =  sparkContext.parallelize(Seq(("a", "b", List("ra", "re", "ri"))))
rdd.flatMap(array => array._3.map(list => (array._1, array._2, list))).foreach(println)


答:
check your route group it must apply the web middleware as

```<code>Route::group(['middleware' => 'web'], function () {
    Route::get('/test', function() {
       return csrf_token();
       //or return $request->session()->token();
    });
});
</code>```

Title: Laravel 5.4 null csrf_token() when posting to route

Body:
check your route group it must apply the web middleware as

Route::group(['middleware' => 'web'], function () {
    Route::get('/test', function() {
       return csrf_token();
       //or return $request->session()->token();
    });
});


问:
How to extract a url from a webpage?
Twitter returns a webpage that these lines are among others:

```<code><link rel="dns-prefetch" href="//video.twimg.com" />
<link rel="preload" as="script" crossorigin="anonymous" href="https://ma-0.twimg.com/twitter-assets/responsive-web/web/ltr/vendor.69f9ac19fa493004.js" />
<link rel="preload" as="script" crossorigin="anonymous" href="https://ma-0.twimg.com/twitter-assets/responsive-web/web/ltr/i18n/en.312d3f56908013c9.js" />
<link rel="preload" as="script" crossorigin="anonymous" href="https://ma-0.twimg.com/twitter-assets/responsive-web/web/ltr/main.da8c0a0fbf03fdac.js" />
<meta property="fb:app_id" content="2231777543" />
</code>```

I need the url that contains the main.*.js file. How can I get it?

I tried this:

```<code>var mainIndex = content.IndexOf("main.");
var startIndex = content.LastIndexOf("href=\"", mainIndex) + 6;
var endIndex = content.IndexOf(".js", startIndex) + 3;
var url = content.Substring(startIndex, endIndex - startIndex);
</code>```

but it's a bad unsafe implementation. Thanks.

答:
You can do it with a dedicated HTML parser, such as Html Agility Pack

```<code>var text = "<link rel=\"dns-prefetch\" href=\"//vide.... />";
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(text);

var links = doc
    .DocumentNode
    .SelectNodes("//link")
    .Select(e=>e.Attributes["href"].Value);

links
    // here, you could parse and match the URL robustly
    .Where(href=>href.Contains("main"))
    // try it in LINQPad
    .Dump();
</code>```

result: https://ma-0.twimg.com/twitter-assets/responsive-web/web/ltr/main.da8c0a0fbf03fdac.js

Title: How to extract a url from a webpage?

Body:
Twitter returns a webpage that these lines are among others:

<link rel="dns-prefetch" href="//video.twimg.com" />
<link rel="preload" as="script" crossorigin="anonymous" href="https://ma-0.twimg.com/twitter-assets/responsive-web/web/ltr/vendor.69f9ac19fa493004.js" />
<link rel="preload" as="script" crossorigin="anonymous" href="https://ma-0.twimg.com/twitter-assets/responsive-web/web/ltr/i18n/en.312d3f56908013c9.js" />
<link rel="preload" as="script" crossorigin="anonymous" href="https://ma-0.twimg.com/twitter-assets/responsive-web/web/ltr/main.da8c0a0fbf03fdac.js" />
<meta property="fb:app_id" content="2231777543" />

I need the url that contains the main.*.js file. How can I get it?

I tried this:

var mainIndex = content.IndexOf("main.");
var startIndex = content.LastIndexOf("href=\"", mainIndex) + 6;
var endIndex = content.IndexOf(".js", startIndex) + 3;
var url = content.Substring(startIndex, endIndex - startIndex);

but it's a bad unsafe implementation. Thanks.

Body:
You can do it with a dedicated HTML parser, such as Html Agility Pack

var text = "<link rel=\"dns-prefetch\" href=\"//vide.... />";
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(text);

var links = doc
    .DocumentNode
    .SelectNodes("//link")
    .Select(e=>e.Attributes["href"].Value);

links
    // here, you could parse and match the URL robustly
    .Where(href=>href.Contains("main"))
    // try it in LINQPad
    .Dump();

result: https://ma-0.twimg.com/twitter-assets/responsive-web/web/ltr/main.da8c0a0fbf03fdac.js


问:
Install HDP 2.2 on CentOS 7
As I can see HDP 2.2 needs Centos 6.5 as an operation system, probably because Ambari needs Centos 6.5. My question is if anyone has installed it on Centos 7. Is there any hard dependencies that will not allow me to complete the installation successfully? </p>

答:
Just consult the official Installation Guide for a relevant Ambari version
https://cwiki.apache.org/confluence/display/AMBARI/Install+Ambari+2.2.0+from+Public+Repositories

It's an up-to-date source of OS compatibility information.
Here you can see that Centos 7 is officially supported.

Title: Install HDP 2.2 on CentOS 7


问:
Spark - Scala - Remove Columns from a dataframe based on condition
We have a specific need wherein I will have to drop columns from a dataframe which has only one unique value in that column. The following is what we are doing

```<code>val rawdata = spark.read.format("csv").option("header","true").option("inferSchema","true").load(filename)
</code>```

Subsequently to find unique values in all columns we are using the HyperLog++ algorithm supported in spark

```<code>val cd_cols  = rawdata.select(rawdata.columns.map(column => approxCountDistinct(col(column)).alias(column)): _*)
</code>```

The output is

```<code>scala> cd_cols.show
+----+----------+---------+---+---------+--------------+---------+----------+----------------+---------+--------------+-------------+
|  ID|First Name|Last Name|Age|Attrition|BusinessTravel|DailyRate|Department|DistanceFromHome|Education|EducationField|EmployeeCount|
+----+----------+---------+---+---------+--------------+---------+----------+----------------+---------+--------------+-------------+
|1491|       172|      154| 43|        2|             3|      913|         3|              30|        1|             6|            1|
+----+----------+---------+---+---------+--------------+---------+----------+----------------+---------+--------------+-------------+
</code>```

Notice that I have two columns which has a 1 as the unique value. I want to create another dataframe which has all columns except those two columns (Education and EmployeeCount)

I tried using a for loop, but was not very happy and also tried

```<code>cd_cols.columns.filter(colName => cd_cols.filter(colName) <= 1)
</code>```

that is also not working.

Is there a smarter way to do this please.

Thanks

Bala

答:
If you want to go on from what you were originally trying, the following should also work.  Also, note that with Spark 2.0 onwards you can pass a list into drop and remove the columns that way.  This may be more clear as to what you are doing.

Or worst case is another way of doing it.

This should work with most spark versions.

```<code>    val keptCols: Seq[Column] = df.columns
      .map(c => (c, df.select(c).first.getLong(0)))
      .filter{case (c, v) => v!=1}
      .map{case (c, v) => df(c)}
      .toSeq

    df.select(keptCols: _*).show
</code>```

For > Spark 2.0

```<code>    val droppedCols: Seq[String] = df.columns
      .map(c => (c, df.select(c).first.getLong(0)))
      .filter{case (c, v) => v==1}
      .map{case (c, v) => c}
      .toSeq

    df.drop(droppedCols: _*).show
</code>```

Both should use the same results.

Body:
We have a specific need wherein I will have to drop columns from a dataframe which has only one unique value in that column. The following is what we are doing

val rawdata = spark.read.format("csv").option("header","true").option("inferSchema","true").load(filename)

Subsequently to find unique values in all columns we are using the HyperLog++ algorithm supported in spark

val cd_cols  = rawdata.select(rawdata.columns.map(column => approxCountDistinct(col(column)).alias(column)): _*)

The output is

scala> cd_cols.show
+----+----------+---------+---+---------+--------------+---------+----------+----------------+---------+--------------+-------------+
|  ID|First Name|Last Name|Age|Attrition|BusinessTravel|DailyRate|Department|DistanceFromHome|Education|EducationField|EmployeeCount|
+----+----------+---------+---+---------+--------------+---------+----------+----------------+---------+--------------+-------------+
|1491|       172|      154| 43|        2|             3|      913|         3|              30|        1|             6|            1|
+----+----------+---------+---+---------+--------------+---------+----------+----------------+---------+--------------+-------------+

Notice that I have two columns which has a 1 as the unique value. I want to create another dataframe which has all columns except those two columns (Education and EmployeeCount)

I tried using a for loop, but was not very happy and also tried

cd_cols.columns.filter(colName => cd_cols.filter(colName) <= 1)

that is also not working.

Is there a smarter way to do this please.

Thanks

Bala

Body:
If you want to go on from what you were originally trying, the following should also work.  Also, note that with Spark 2.0 onwards you can pass a list into drop and remove the columns that way.  This may be more clear as to what you are doing.

Or worst case is another way of doing it.

This should work with most spark versions.

    val keptCols: Seq[Column] = df.columns
      .map(c => (c, df.select(c).first.getLong(0)))
      .filter{case (c, v) => v!=1}
      .map{case (c, v) => df(c)}
      .toSeq

    df.select(keptCols: _*).show

For > Spark 2.0

    val droppedCols: Seq[String] = df.columns
      .map(c => (c, df.select(c).first.getLong(0)))
      .filter{case (c, v) => v==1}
      .map{case (c, v) => c}
      .toSeq

    df.drop(droppedCols: _*).show

Both should use the same results.


问:
How can i use two web service methods in the same activity?
I have two methods which are from soap webservice. I am calling them in asyntask that is a superclass of info.java page and tring to get the results in onPost method of asyntask. The calling code of info.java/onCreate is below.

```<code>        try{
        PropertyInfo propertyInfo1 = new PropertyInfo();
        properties.clear();

        propertyInfo1 = new PropertyInfo();
        propertyInfo1.setName("Module_id");
        propertyInfo1.setType(String.class);
        propertyInfo1.setValue(Utils.selectedModule_id);
        properties.add(propertyInfo1);

        new Info.AsyncTaskService().execute(new ServiceParams("GetInfo", properties), new ServiceParams("GetInfo_Photo", properties));

    } catch (Exception e) {
        Toast.makeText(Info.this, "Please check your internet connection.", Toast.LENGTH_LONG);
    }
</code>```

Both of the service methods takes the same properties thats why i gave them same properties. My problem is i can't take the results because i know that it needs to call these two methods in different threads with an order but i don't know how to do it. Could you help me please? The codes of asynctask class is also below thank you.

```<code> public class AsyncTaskService extends AsyncTask<ServiceParams, Void, Void> {
    String resp = "";
    String resp2 = "";
    ProgressDialog progressDialog;

    @Override
    protected Void doInBackground(ServiceParams... params) {
        resp = WebService.invoke(params[0].properties, params[0].methodName);
        resp2 = WebService.invoke(params[1].properties, params[1].methodName);
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {

        Log.w("WEBSERVICE RESPONSE===", resp);

        Log.w("WEBSERVICE RESPONSE===", resp2);
        try {
            JSONArray ja = new JSONArray(resp);
            Utils.subMenuArrayList.clear();
            Info_Item info_item=new Info_Item(ja.getJSONObject(0));
            ((TextView)findViewById(R.id.txtInfo)).setText(info_item.getInfo());
            ((TextView)findViewById(R.id.txtModule)).setText(Utils.selectedMenuName);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (progressDialog != null)
            progressDialog.dismiss();
    }
    @Override
    protected void onPreExecute() {

        progressDialog = new ProgressDialog(Info.this);
        if (progressDialog != null) {
            progressDialog.setCancelable(false);
            progressDialog.setMessage("İşlem yapılıyor ...");
            progressDialog.show();
        }
    }

    protected void onProgressUpdate(Integer... progress) {
        if (progressDialog != null)
            progressDialog.setProgress(progress[0]);
    }

}
</code>```

答:
I have found how to do it! Wanted to share with you too.

First of all describe you async tasks as below. I have two methods which i want to use in one activity at the same time(paralel) so i described two async task classes.

```<code>public class FirstAsyncTask extends AsyncTask<ServiceParams, Void, Void> {
    String resp = "";
    ProgressDialog progressDialog;

    @Override
    protected Void doInBackground(ServiceParams... params) {
        resp = WebService.invoke(params[0].properties, params[0].methodName);
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {

        Log.w("WEBSERVICE RESPONSE===", resp);

        try {
            JSONArray ja = new JSONArray(resp);
            Utils.subMenuArrayList.clear();
            Info_Item info_item=new Info_Item(ja.getJSONObject(0));
            ((TextView)findViewById(R.id.txtInfo)).setText(info_item.getInfo());
            ((TextView)findViewById(R.id.txtModule)).setText(Utils.selectedMenuName);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (progressDialog != null)
            progressDialog.dismiss();
    }

    @Override
    protected void onPreExecute() {

        progressDialog = new ProgressDialog(Info.this);
        if (progressDialog != null) {
            progressDialog.setCancelable(false);
            progressDialog.setMessage("İşlem yapılıyor ...");
            progressDialog.show();
        }
    }

    protected void onProgressUpdate(Integer... progress) {
        if (progressDialog != null)
            progressDialog.setProgress(progress[0]);
    }

}
</code>```

Then you should call the tasks like this with executeOnExecuter in your activity's onCreate method. I used a property array here to hold the parameters i am going to send to web service method and describe a serviceparameter with properties and method name and send them in executeOnExecuter() method. I used same properties for my both web service methods but you can describe an other property array like this "private ArrayList properties = new ArrayList<>();" and add informations you need for parameters you will send to web service method.

```<code>try{
        PropertyInfo propertyInfo1 = new PropertyInfo();
        properties.clear();

        propertyInfo1 = new PropertyInfo();
        propertyInfo1.setName("Module_id");
        propertyInfo1.setType(String.class);
        propertyInfo1.setValue(Utils.selectedModule_id);
        properties.add(propertyInfo1);

        ServiceParams serviceparams=new ServiceParams("GetInfo", properties);
        ServiceParams serviceparams2=new ServiceParams("GetInfo_Photo", properties);

        FirstAsyncTask asyncTask = new FirstAsyncTask(); // First
        asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, serviceparams);
        SecondAsyncTask asyncTask2 = new SecondAsyncTask(); // Second
        asyncTask2.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, serviceparams2);

    } catch (Exception e) {
        Toast.makeText(Info.this, "Please check your internet connection.", Toast.LENGTH_LONG);
    }
</code>```

Body:
I have two methods which are from soap webservice. I am calling them in asyntask that is a superclass of info.java page and tring to get the results in onPost method of asyntask. The calling code of info.java/onCreate is below.

        try{
        PropertyInfo propertyInfo1 = new PropertyInfo();
        properties.clear();

        propertyInfo1 = new PropertyInfo();
        propertyInfo1.setName("Module_id");
        propertyInfo1.setType(String.class);
        propertyInfo1.setValue(Utils.selectedModule_id);
        properties.add(propertyInfo1);

        new Info.AsyncTaskService().execute(new ServiceParams("GetInfo", properties), new ServiceParams("GetInfo_Photo", properties));

    } catch (Exception e) {
        Toast.makeText(Info.this, "Please check your internet connection.", Toast.LENGTH_LONG);
    }

Both of the service methods takes the same properties thats why i gave them same properties. My problem is i can't take the results because i know that it needs to call these two methods in different threads with an order but i don't know how to do it. Could you help me please? The codes of asynctask class is also below thank you.

 public class AsyncTaskService extends AsyncTask<ServiceParams, Void, Void> {
    String resp = "";
    String resp2 = "";
    ProgressDialog progressDialog;

    @Override
    protected Void doInBackground(ServiceParams... params) {
        resp = WebService.invoke(params[0].properties, params[0].methodName);
        resp2 = WebService.invoke(params[1].properties, params[1].methodName);
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {

        Log.w("WEBSERVICE RESPONSE===", resp);

        Log.w("WEBSERVICE RESPONSE===", resp2);
        try {
            JSONArray ja = new JSONArray(resp);
            Utils.subMenuArrayList.clear();
            Info_Item info_item=new Info_Item(ja.getJSONObject(0));
            ((TextView)findViewById(R.id.txtInfo)).setText(info_item.getInfo());
            ((TextView)findViewById(R.id.txtModule)).setText(Utils.selectedMenuName);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (progressDialog != null)
            progressDialog.dismiss();
    }
    @Override
    protected void onPreExecute() {

        progressDialog = new ProgressDialog(Info.this);
        if (progressDialog != null) {
            progressDialog.setCancelable(false);
            progressDialog.setMessage("İşlem yapılıyor ...");
            progressDialog.show();
        }
    }

    protected void onProgressUpdate(Integer... progress) {
        if (progressDialog != null)
            progressDialog.setProgress(progress[0]);
    }

}

Body:
I have found how to do it! Wanted to share with you too.

First of all describe you async tasks as below. I have two methods which i want to use in one activity at the same time(paralel) so i described two async task classes.

public class FirstAsyncTask extends AsyncTask<ServiceParams, Void, Void> {
    String resp = "";
    ProgressDialog progressDialog;

    @Override
    protected Void doInBackground(ServiceParams... params) {
        resp = WebService.invoke(params[0].properties, params[0].methodName);
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {

        Log.w("WEBSERVICE RESPONSE===", resp);

        try {
            JSONArray ja = new JSONArray(resp);
            Utils.subMenuArrayList.clear();
            Info_Item info_item=new Info_Item(ja.getJSONObject(0));
            ((TextView)findViewById(R.id.txtInfo)).setText(info_item.getInfo());
            ((TextView)findViewById(R.id.txtModule)).setText(Utils.selectedMenuName);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (progressDialog != null)
            progressDialog.dismiss();
    }

    @Override
    protected void onPreExecute() {

        progressDialog = new ProgressDialog(Info.this);
        if (progressDialog != null) {
            progressDialog.setCancelable(false);
            progressDialog.setMessage("İşlem yapılıyor ...");
            progressDialog.show();
        }
    }

    protected void onProgressUpdate(Integer... progress) {
        if (progressDialog != null)
            progressDialog.setProgress(progress[0]);
    }

}

Then you should call the tasks like this with executeOnExecuter in your activity's onCreate method. I used a property array here to hold the parameters i am going to send to web service method and describe a serviceparameter with properties and method name and send them in executeOnExecuter() method. I used same properties for my both web service methods but you can describe an other property array like this "private ArrayList properties = new ArrayList<>();" and add informations you need for parameters you will send to web service method.

try{
        PropertyInfo propertyInfo1 = new PropertyInfo();
        properties.clear();

        propertyInfo1 = new PropertyInfo();
        propertyInfo1.setName("Module_id");
        propertyInfo1.setType(String.class);
        propertyInfo1.setValue(Utils.selectedModule_id);
        properties.add(propertyInfo1);

        ServiceParams serviceparams=new ServiceParams("GetInfo", properties);
        ServiceParams serviceparams2=new ServiceParams("GetInfo_Photo", properties);

        FirstAsyncTask asyncTask = new FirstAsyncTask(); // First
        asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, serviceparams);
        SecondAsyncTask asyncTask2 = new SecondAsyncTask(); // Second
        asyncTask2.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, serviceparams2);

    } catch (Exception e) {
        Toast.makeText(Info.this, "Please check your internet connection.", Toast.LENGTH_LONG);
    }


问:
How to find the longest consecutive chain of numbers in an array
For example we have [0, 1, 3, 5, 7, 8, 9, 10, 12, 13] .

The result must be 7, 8, 9, 10 because they are adjacent to each other, index wise and are consecutive integers, and also this chain is longer than 0, 1.

English is not my first language, excuse me if the writing is a bit obscure.

答:
Alternative solution using numpy module:

```<code>import numpy as np

nums = np.array([0, 1, 3, 5, 7, 8, 9, 10, 12, 13])
longest_seq = max(np.split(nums, np.where(np.diff(nums) != 1)[0]+1), key=len).tolist()
print(longest_seq)
</code>```

The output:

```<code>[7, 8, 9, 10]
</code>```

np.where(np.diff(nums) != 1)[0]+1 - gets the indices of elements on which the array should be split (if difference between 2 consequtive numbers is not equal to 1, e.g. 3 and 5)

np.split(...) - split the array into sub-arrays

https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.diff.html#numpy.diff
https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.split.html

Body:
Alternative solution using numpy module:

import numpy as np

nums = np.array([0, 1, 3, 5, 7, 8, 9, 10, 12, 13])
longest_seq = max(np.split(nums, np.where(np.diff(nums) != 1)[0]+1), key=len).tolist()
print(longest_seq)

The output:

[7, 8, 9, 10]

np.where(np.diff(nums) != 1)[0]+1 - gets the indices of elements on which the array should be split (if difference between 2 consequtive numbers is not equal to 1, e.g. 3 and 5)

np.split(...) - split the array into sub-arrays

https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.diff.html#numpy.diff
https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.split.html


问:
Group rows by minimum value
The problem is that I have some tables to build and some values are under an specific threshold. For example:

```<code>    S1  S2  S3
A   700 367 751
B   354 103 143
C   18  7   6
D   27  11  5
E   3   6   1
F   8   2   9
G   1   3   2
</code>```

What I desire is to keep the rows where the values contain at least one value is equal or greater than 10 and merge the rows where the values are less than 10 to create a row named "Other (<10)":

1 - Part of the table with rows with at least one cell containing one value greater than 10 (Row C; value 18):

```<code>    S1  S2  S3
A   700 367 751
B   354 103 143
C   18  7   6
</code>```

2 - Part of the table where any value is greater than 10.

```<code>E   3   6   1
F   8   2   9
G   1   3   2
</code>```

The final table would have the last row with the sum of the columns from E, F, and G, including the "Other(>10)" row name. Like this:

```<code>            S1  S2  S3
A           700 367 751
B           354 103 143
C           18  7   6
D           27  11  5
Other(<10)  12  11  12
</code>```

答:
You can try this in python:</p>

```<code>data = ["700 367 751", "354 103 143", "18  7   6", "27  11  5", "3   6   1", "8   2   9", "1   3   2"]

new_data = [map(int, i.split()) for i in data]

final_data = []

extra_data = [0, 0, 0]

for i in new_data:
   if any(b >= 10 for b in i):
        final_data.append(i)

   else:
       extra_data = [extra_data[c]+b for c, b in enumerate(i)]

final_data.append(extra_data)

print final_data
</code>```

Title: Group rows by minimum value

Body:
The problem is that I have some tables to build and some values are under an specific threshold. For example:

    S1  S2  S3
A   700 367 751
B   354 103 143
C   18  7   6
D   27  11  5
E   3   6   1
F   8   2   9
G   1   3   2

What I desire is to keep the rows where the values contain at least one value is equal or greater than 10 and merge the rows where the values are less than 10 to create a row named "Other (<10)":

1 - Part of the table with rows with at least one cell containing one value greater than 10 (Row C; value 18):

    S1  S2  S3
A   700 367 751
B   354 103 143
C   18  7   6

2 - Part of the table where any value is greater than 10.

E   3   6   1
F   8   2   9
G   1   3   2

The final table would have the last row with the sum of the columns from E, F, and G, including the "Other(>10)" row name. Like this:

            S1  S2  S3
A           700 367 751
B           354 103 143
C           18  7   6
D           27  11  5
Other(<10)  12  11  12

Body:
You can try this in python:

data = ["700 367 751", "354 103 143", "18  7   6", "27  11  5", "3   6   1", "8   2   9", "1   3   2"]

new_data = [map(int, i.split()) for i in data]

final_data = []

extra_data = [0, 0, 0]

for i in new_data:
   if any(b >= 10 for b in i):
        final_data.append(i)

   else:
       extra_data = [extra_data[c]+b for c, b in enumerate(i)]

final_data.append(extra_data)

print final_data


问:
deleting datas in the table in GUI
I have question that how can I delete all datas from my jTable in GUI when a user entered a key?
thanks</p>

答:
You can set a new empty data model:</p>

```<code>TableModel newModel = new DefaultTableModel();
jtable.setModel(newModel);
</code>```

Title: deleting datas in the table in GUI

Body:
You can set a new empty data model:

TableModel newModel = new DefaultTableModel();
jtable.setModel(newModel);


问:
Django conversations - get_or_create MultipleObjectsReturned
I want to create simple chat system, my models:

```<code>class Conversation(models.Model):
    users = models.ManyToManyField(User, related_name='users')
    date = models.DateTimeField(auto_now_add=True)

class Message(models.Model):
    user = models.ForeignKey(User)
    conversation = models.ForeignKey(Conversation, related_name='conversation')
    content = models.TextField()
    date = models.DateTimeField(auto_now_add=True)
</code>```

and my view:

```<code>def conversation(request, username):
    recipient = User.objects.get(username=username)
    conversation, created = Conversation.objects.get_or_create(
        users__in=[recipient, request.user]
    )

    if created:
        conversation.users.add([recipient, request.user])
</code>```

I want create users connection by create conversation with manytomany field.
When i go to /conversations/user_name get_or_create check if conversation exists and if not then create new conversation with current logged user and user from url.

My problem is:

```<code>MultipleObjectsReturned at /conversations/user_name
get() returned more than one Conversation -- it returned 2!
</code>```

How can i solve it? Probably its problem with this manytomany field.. How i can limit users__id lookup to 1?

答:
get_or_create isn't suitable for this.

This method is atomic assuming correct usage, correct database
  configuration, and correct behavior of the underlying database.
  However, if uniqueness is not enforced at the database level for the
  kwargs used in a get_or_create call (see unique or unique_together),
  this method is prone to a race-condition which can result in multiple
  rows with the same parameters being inserted simultaneously.

You don't have a unique key in your table. And the nature of your app is such that a unique key cannot be used. At the same time, a chat message very very occasionally getting repeated isn't a big deal. So just go ahead and create the object without bothering to check for existence.

Also note that checking for existing using a select and then doing the create would be futile. The race condition mentioned would kick in and you will still end up with duplicates.

Body:
I want to create simple chat system, my models:

class Conversation(models.Model):
    users = models.ManyToManyField(User, related_name='users')
    date = models.DateTimeField(auto_now_add=True)

class Message(models.Model):
    user = models.ForeignKey(User)
    conversation = models.ForeignKey(Conversation, related_name='conversation')
    content = models.TextField()
    date = models.DateTimeField(auto_now_add=True)

and my view:

def conversation(request, username):
    recipient = User.objects.get(username=username)
    conversation, created = Conversation.objects.get_or_create(
        users__in=[recipient, request.user]
    )

    if created:
        conversation.users.add([recipient, request.user])

I want create users connection by create conversation with manytomany field.
When i go to /conversations/user_name get_or_create check if conversation exists and if not then create new conversation with current logged user and user from url.

My problem is:

MultipleObjectsReturned at /conversations/user_name
get() returned more than one Conversation -- it returned 2!

How can i solve it? Probably its problem with this manytomany field.. How i can limit users__id lookup to 1?


问:
C++ : Why it dont work?
I was trying to solve

In which you have given a array of int and you have to return its sum.

```<code>#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <cstdlib>
using namespace std;

int main(){
int n;
cin >> n;
int k;
vector<int> arr(n);
for(int arr_i = 0;arr_i < n;arr_i++){
   cin >> arr[arr_i];
    k = k + arr[arr_i];
    //cout << "arr = " << arr[arr_i] << " k " << k << endl;     //  [0]
    if (arr_i == (n-1))
    {
        cout << k;
    }

}
return 0;
}
</code>```

This return a afkard no. instead of sum.

But when uncomment out [0] line. code starts working as it should.

P.S. i found out the solution by changing cout to cerr.
but wanted to know why it doesn't work.

答:
as the other answer, initialize k, move if outside of loop

```<code>vector<int> arr(n);
int k = 0;
for(int arr_i = 0;arr_i < n;arr_i++){
   cin >> arr[arr_i];
    k = k + arr[arr_i];
    //cout << "arr = " << arr[arr_i] << " k " << k << endl;     //  [0]
}
cout << k;
</code>```

as your question, there is no need std::vector anymore

```<code>int sum = 0, num;
for(int arr_i = 0;arr_i < n;arr_i++){
   cin >> num;
   sum = sum + num;
}
std::cout << sum << std::endl;
</code>```

Title: C++ : Why it dont work?

Body:
I was trying to solve

In which you have given a array of int and you have to return its sum.

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <cstdlib>
using namespace std;

int main(){
int n;
cin >> n;
int k;
vector<int> arr(n);
for(int arr_i = 0;arr_i < n;arr_i++){
   cin >> arr[arr_i];
    k = k + arr[arr_i];
    //cout << "arr = " << arr[arr_i] << " k " << k << endl;     //  [0]
    if (arr_i == (n-1))
    {
        cout << k;
    }

}
return 0;
}

This return a afkard no. instead of sum.

But when uncomment out [0] line. code starts working as it should.

P.S. i found out the solution by changing cout to cerr.
but wanted to know why it doesn't work.

Body:
as the other answer, initialize k, move if outside of loop

vector<int> arr(n);
int k = 0;
for(int arr_i = 0;arr_i < n;arr_i++){
   cin >> arr[arr_i];
    k = k + arr[arr_i];
    //cout << "arr = " << arr[arr_i] << " k " << k << endl;     //  [0]
}
cout << k;

as your question, there is no need std::vector anymore

int sum = 0, num;
for(int arr_i = 0;arr_i < n;arr_i++){
   cin >> num;
   sum = sum + num;
}
std::cout << sum << std::endl;


问:
Established methods for websites to serve database results
Are there established methods or frameworks for serving database rows to web clients?  So far I just have them submit a JSON object ex

```<code>{
  Query: "SELECT",
  Schema: "icecream",
  Table: "cones",
  Fields: ["price", "flavor"],
  Filters: [
    {
      "Comparison": "=",
      "Field": "flavor",
      "Value": "chocolate"
    }
  ]
}
</code>```

I verify that the fields mentioned are authorized/correct, then construct a prepared statement mysql string, but are there any frameworks, or standard methods of implementing this?

答:
Truth be told, what you are doing is very unusual.  You are effectively giving your web client full access to build queries for your database.  You mention that you are validating the information before building the query, which is good, because the risk of SQL injection is very high.  You are asking a very broad question, so I will respond with an equally broad answer:

No, there are no frameworks or standards to implementing this.  The reason is because (unless you have a very specific reason for doing this), very few web applications are setup to give the web client such extensive control over the queries being built.  Normally your backend APIs would intentionally be much more limited.  You are effectively implementing an API method that says:

Give me the details of your query and I will build and execute it for you and return the result.

Normally standard operating procedure otherwise is to have much more specific and limited API methods.  Rather than having a generic query builder you would have an API for each specific thing that has to happen:

Tell me how many records you want and a search value on this small handful of fields and I will return a list of matching users

Tell me how many records you want and which of these fields you want to sort by and I will return a list of matching books

That is not to say that there aren't perfectly valid reasons to do it the way you are trying to do it, but unless there is a reason why you specifically want to give users full control over the query building process, I think the first step is to refactor in a way that gives the web client less control, and your server-side application more.

Body:
Are there established methods or frameworks for serving database rows to web clients?  So far I just have them submit a JSON object ex

{
  Query: "SELECT",
  Schema: "icecream",
  Table: "cones",
  Fields: ["price", "flavor"],
  Filters: [
    {
      "Comparison": "=",
      "Field": "flavor",
      "Value": "chocolate"
    }
  ]
}

I verify that the fields mentioned are authorized/correct, then construct a prepared statement mysql string, but are there any frameworks, or standard methods of implementing this?


问:
How to connect to weather API using requests?
I am trying to learn Requests and practicing by connecting to the weather API.  But for some reason I can't get it to work?  It is clear the weather API is wanting the param in a certain way that I cannot seem to figure out how it translates to Requests.

Here is my code:

```<code>r = requests.get('http://api.openweathermap.org/data/2.5/weather', q={'Anderson'})
</code>```

Here is the link to the API page:
https://openweathermap.org/current

I see the weather pages wants the param in terms of q = city, but the error I get is:

```<code>TypeError: request() got an unexpected keyword argument 'q'
</code>```

Also here the the Requests page that I am referring to: http://docs.python-requests.org/en/master/

Thanks for the help!

答:
Please review the requests user manual, at least the quickstart guide.
The RESTful API you are about to use expects GET request with q="City Name" parameter. Moreover you must have the appid and add it for every request.

Register you application and choose a pricing plan https://openweathermap.org/price

Pass both q="City Name" and APPID=xxx parameters

Here is corresponding request:

```<code>api_url = 'http://api.openweathermap.org/data/2.5/weather'
appid = ...
r = requests.get(url=api_url, params=dict(q='Anderson', APPID=appid))
</code>```

Body:
I am trying to learn Requests and practicing by connecting to the weather API.  But for some reason I can't get it to work?  It is clear the weather API is wanting the param in a certain way that I cannot seem to figure out how it translates to Requests.

Here is my code:

r = requests.get('http://api.openweathermap.org/data/2.5/weather', q={'Anderson'})

Here is the link to the API page:
https://openweathermap.org/current

I see the weather pages wants the param in terms of q = city, but the error I get is:

TypeError: request() got an unexpected keyword argument 'q'

Also here the the Requests page that I am referring to: http://docs.python-requests.org/en/master/

Thanks for the help!

Body:
Please review the requests user manual, at least the quickstart guide.
The RESTful API you are about to use expects GET request with q="City Name" parameter. Moreover you must have the appid and add it for every request.

Register you application and choose a pricing plan https://openweathermap.org/price

Pass both q="City Name" and APPID=xxx parameters

Here is corresponding request:

api_url = 'http://api.openweathermap.org/data/2.5/weather'
appid = ...
r = requests.get(url=api_url, params=dict(q='Anderson', APPID=appid))


问:
How to run a function on an Observable between item emotion if there was a big delay?
I have a PublishSubject which receive emits from UI:

```<code>myPublishSubject
        .map {
            ...
        }
        .doOnNext {
            // using emitted item
        }
        .timeout (...) // wait for the gap!
        .doOnNext {
            // running a function after a specific gap between two item
        }
        .subscribe()
</code>```

I want to wait a specific amount of time after last emit (not onComplete, cause it continue emitting later) and run a function. It can be interpreted as a gap between item emotion.

I am looking for something like timeout but this method issue is it kills the Observable with error.

答:
You have to be a bit creative with publish and switchMap for example:

```<code>PublishSubject<Integer> ps = PublishSubject.create();

ps.publish(o ->
    o.mergeWith(
        o.switchMap(e ->
             Observable.just(1).delay(200, TimeUnit.MILLISECONDS)
            .ignoreElements()
            .doOnCompleted(() -> System.out.println("Timeout action: " + e))
        )
    )
).subscribe(System.out::println);

ps.onNext(1);
ps.onNext(2);

Thread.sleep(100);

ps.onNext(3);

Thread.sleep(250);

ps.onNext(4);

Thread.sleep(250);
</code>```

It works by sharing a source and routing into two ways, one is directly emitting while the other feeds a switchMap that when receives a new item, starts a delayed Observable and reacts to its completion (ignoring the original trigger element to avoid duplicate events due to mergeWith). When there is a new signal during the grace period, switchMap will cancel the previous delay and start with the newer delay.

Body:
I have a PublishSubject which receive emits from UI:

myPublishSubject
        .map {
            ...
        }
        .doOnNext {
            // using emitted item
        }
        .timeout (...) // wait for the gap!
        .doOnNext {
            // running a function after a specific gap between two item
        }
        .subscribe()

I want to wait a specific amount of time after last emit (not onComplete, cause it continue emitting later) and run a function. It can be interpreted as a gap between item emotion.

I am looking for something like timeout but this method issue is it kills the Observable with error.

Body:
You have to be a bit creative with publish and switchMap for example:

PublishSubject<Integer> ps = PublishSubject.create();

ps.publish(o ->
    o.mergeWith(
        o.switchMap(e ->
             Observable.just(1).delay(200, TimeUnit.MILLISECONDS)
            .ignoreElements()
            .doOnCompleted(() -> System.out.println("Timeout action: " + e))
        )
    )
).subscribe(System.out::println);

ps.onNext(1);
ps.onNext(2);

Thread.sleep(100);

ps.onNext(3);

Thread.sleep(250);

ps.onNext(4);

Thread.sleep(250);

It works by sharing a source and routing into two ways, one is directly emitting while the other feeds a switchMap that when receives a new item, starts a delayed Observable and reacts to its completion (ignoring the original trigger element to avoid duplicate events due to mergeWith). When there is a new signal during the grace period, switchMap will cancel the previous delay and start with the newer delay.


问:
Rapid Miner - IF statements
I'm having a slight problem with my IF function expression in a generate attribute operator.

Essential this is the functionality I would like the function to have.

```<code>If VarX contains ".0", then remove this .0, else leave VarX unchanged
</code>```

So far this is the syntax I have for the function expression in Rapid Miner.

```<code>if(contains(".0",VarX),replace(".0",VarX,""),VarX)
</code>```

However this syntax is not working correctly, as the ".0" in the data are not being replaced.

答:
The parameter ordering is incorrect.

Try the following

```<code>if(contains(VarX, ".0"), replace(VarX, ".0", ""),VarX)
</code>```

Title: Rapid Miner - IF statements

Body:
I'm having a slight problem with my IF function expression in a generate attribute operator.

Essential this is the functionality I would like the function to have.

If VarX contains ".0", then remove this .0, else leave VarX unchanged

So far this is the syntax I have for the function expression in Rapid Miner.

if(contains(".0",VarX),replace(".0",VarX,""),VarX)

However this syntax is not working correctly, as the ".0" in the data are not being replaced.

Body:
The parameter ordering is incorrect.

Try the following

if(contains(VarX, ".0"), replace(VarX, ".0", ""),VarX)


问:
With a `new Request` in Node/React, how to pass params with a GET request?
I have the following API call in my Reactjs app:

```<code>  static getAllSkills(title_id) {
    const request = new Request(`http://localhost:4300/api/v1/job_title_skills`, {
      method: 'GET',
      headers: new Headers({
        'Content-Type': 'application/json'
      }),
      body: JSON.stringify({title_id: title_id})
    });

    return fetch(request).then(response => {
      return response.json();
    }).catch(error => {
      return error;
    });
  }
</code>```

Which points to a Rails endpoint which expects the param title_id like so:

```<code>  def index
    @skills = Skill.where(id: params[:title_id])
    ....
  end
</code>```

The controller is expecting a GET request however with the above, I'm getting the following JS console error:

```<code>Uncaught TypeError: Failed to construct 'Request': Request with GET/HEAD method cannot have body.
</code>```

What is the right way to construct the Request and pass the param to the API?

答:
I think the url in your api is waiting for the title_id maybe like:

```<code>api/v1/job_title_skills/:title_id
</code>```

So you can append it in your url when you make the request:

```<code>static getAllSkills(title_id) {
  const request = new Request(`http://localhost:4300/api/v1/job_title_skills/${title_id}`, {
    headers: new Headers({
      'Content-Type': 'application/json'
    })
  });

  return fetch(request).then(response => {
    return response.json();
  }).catch(error => {
    return error;
  });
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have the following API call in my Reactjs app:

  static getAllSkills(title_id) {
    const request = new Request(`http://localhost:4300/api/v1/job_title_skills`, {
      method: 'GET',
      headers: new Headers({
        'Content-Type': 'application/json'
      }),
      body: JSON.stringify({title_id: title_id})
    });

    return fetch(request).then(response => {
      return response.json();
    }).catch(error => {
      return error;
    });
  }

Which points to a Rails endpoint which expects the param title_id like so:

  def index
    @skills = Skill.where(id: params[:title_id])
    ....
  end

The controller is expecting a GET request however with the above, I'm getting the following JS console error:

Uncaught TypeError: Failed to construct 'Request': Request with GET/HEAD method cannot have body.

What is the right way to construct the Request and pass the param to the API?

Body:
I think the url in your api is waiting for the title_id maybe like:

api/v1/job_title_skills/:title_id

So you can append it in your url when you make the request:

static getAllSkills(title_id) {
  const request = new Request(`http://localhost:4300/api/v1/job_title_skills/${title_id}`, {
    headers: new Headers({
      'Content-Type': 'application/json'
    })
  });

  return fetch(request).then(response => {
    return response.json();
  }).catch(error => {
    return error;
  });
}


问:
Swift return result of function calls
I'm completing some exercism exercises. One is a Binary tree (although the context is not relevant to the question as I have experienced this previously in Swift)

I would like to put the following function on one line as:

```<code>func allData () -> [Int] {
    return ( left?.allData() ?? [] ) + [data] + ( right?.allData() ?? [] )
}
</code>```

But the error is 'Int' is not convertible to '[Int]'

Ok, but splitting into separate lines is fine:

```<code>func allData () -> [Int] {
    let leftdata = left?.allData() ?? []
    let rightdata = right?.allData() ?? []
    return ( leftdata ) + [data] + ( rightdata )
}
</code>```

In fact it will compile with either the left data, right data and [data], but not both.

Within exercism I can see that people did not solve this in one line.

So why is

```<code>return ( left?.allData() ?? [] ) + [data] + ( right?.allData() ?? [] )
</code>```

invalid?

答:
I've seen this often with multiple entries added together.  The compiler's type processing sometimes gets confused when combining optionals and non optional types (3 or more) in a single statement.

There is a very similar question here:

http://stackoverflow.com/q/43595162/5237560

and another one here:

http://stackoverflow.com/q/42568446/5237560

In short, the compiler needs help in some cases which are not detected as "too complex" but actually result in the wrong data type being inferred.

Title: Swift return result of function calls

Body:
I'm completing some exercism exercises. One is a Binary tree (although the context is not relevant to the question as I have experienced this previously in Swift)

I would like to put the following function on one line as:

func allData () -> [Int] {
    return ( left?.allData() ?? [] ) + [data] + ( right?.allData() ?? [] )
}

But the error is 'Int' is not convertible to '[Int]'

Ok, but splitting into separate lines is fine:

func allData () -> [Int] {
    let leftdata = left?.allData() ?? []
    let rightdata = right?.allData() ?? []
    return ( leftdata ) + [data] + ( rightdata )
}

In fact it will compile with either the left data, right data and [data], but not both.

Within exercism I can see that people did not solve this in one line.

So why is

return ( left?.allData() ?? [] ) + [data] + ( right?.allData() ?? [] )

invalid?


问:
How to tune Java InputStream size
I am developing file upload functionality in CentOS7 and Jetty9 environment. Everything is working fine but I have noticed that data in my inputstream is very small. I have counted bytes after each read in while loop as bellow.

```<code>  while ((bytesCount = inStream.read(byteArray)) != -1) {
      ...
      logger.trace("bytecount: " + bytesCount);
      ...
   }
</code>```

Log:

```<code> ... bytecount: 3844
 ... bytecount: 4052
 ... bytecount: 44
 ... bytecount: 4052
   .....
   .....
</code>```

My TCP socket buffer size:

```<code> cat /proc/sys/net/ipv4/tcp_rmem
 4096   87380   6291456
</code>```

Is my Jetty9 server reducing the data, so inputstream receiving only around 4KB data each read call? or do I need tune my Linux TCP Socket?

Thanks.

答:
The size of byteArray will not determine the minimum read size. Java has underlying streams, so you will get bytes as they come up to a maximum of byteArray's size.

If you want to force it you could tune your Linux TCP socket.

On the other hand, if you do not want to play with you array size in java you can use ByteArrayOutputStream with the toByteArray() method, which will return an array of the proper size, or google guava's byte[] bytes = ByteStreams.toByteArray(inputStream);

Title: How to tune Java InputStream size

Body:
I am developing file upload functionality in CentOS7 and Jetty9 environment. Everything is working fine but I have noticed that data in my inputstream is very small. I have counted bytes after each read in while loop as bellow.

  while ((bytesCount = inStream.read(byteArray)) != -1) {
      ...
      logger.trace("bytecount: " + bytesCount);
      ...
   }

Log:

 ... bytecount: 3844
 ... bytecount: 4052
 ... bytecount: 44
 ... bytecount: 4052
   .....
   .....

My TCP socket buffer size:

 cat /proc/sys/net/ipv4/tcp_rmem
 4096   87380   6291456

Is my Jetty9 server reducing the data, so inputstream receiving only around 4KB data each read call? or do I need tune my Linux TCP Socket?

Thanks.


问:
Add row dynamically to AdvancedDataGrid
I would like to add new row on the fly (runtime) to my AdvancedDataGrid.
I can add it to the data model, but couldn’t find a way to make the table render and show the new row.

What i am seeking for is to create an effect of expandable item, where clicking on row will show "additional information" (like a drawer) and clicking on row expand button will reveal it's children.

I saw examples of this for dataGrid (http://livedocs.adobe.com/flex/3/html/help.html?content=advdatagrid_10.html), but not for AdavancedDataGrid.

Only way I found to do this is to add a new child and use openItem, but this cause the other children to be visible as well.

Any help is greatly appreciated

答:
you need to revalidate the whole datagrid after you added a new item, so that all the new elements can become visible.

```<code>yourDataGrid.validateNow();
</code>```

This should help:)

Title: Add row dynamically to AdvancedDataGrid

Body:
you need to revalidate the whole datagrid after you added a new item, so that all the new elements can become visible.

yourDataGrid.validateNow();

This should help:)


问:
New Activity from FloatingActionButton
i would launch an activity with a click in a floating action button, but when i click this,  I get "Unfortunately, ... has stopped.". please help me!

questo è il codice del bottone di default, and this works

```<code>FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });
</code>```

When change the code of a snackbar with the code of a new activity, this does not work

```<code>fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent launchactivity=new Intent (getApplicationContext(),add.class);
            startActivity(launchactivity);

        }
    });
</code>```

This is my logcat

09-24 21:22:29.009 6353-6353/com.example.fra31.tradebooks E/AndroidRuntime: FATAL EXCEPTION: main
                                                                              Process: com.example.fra31.tradebooks, PID: 6353
                                                                              java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.fra31.tradebooks/com.example.fra31.tradebooks.add}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2356)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2418)
                                                                                at android.app.ActivityThread.access$900(ActivityThread.java:154)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:135)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5289)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
                                                                                at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:115)
                                                                               Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
                                                                                at com.example.fra31.tradebooks.add.onCreate(add.java:47)
                                                                                at android.app.Activity.performCreate(Activity.java:5990)
                                                                                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2309)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2418)
                                                                                at android.app.ActivityThread.access$900(ActivityThread.java:154)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:135)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5289)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
                                                                                at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:115)

答:
```<code>Intent launchactivity=new Intent (MainActivity.this,add.class);
            startActivity(launchactivity);
</code>```

and you should go to androidmanifest.xml and define your activity as this :

```<code><activity android:name=".MainActivity">
       </activity>
</code>```

Title: New Activity from FloatingActionButton

Body:
i would launch an activity with a click in a floating action button, but when i click this,  I get "Unfortunately, ... has stopped.". please help me!

questo è il codice del bottone di default, and this works

FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

When change the code of a snackbar with the code of a new activity, this does not work

fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent launchactivity=new Intent (getApplicationContext(),add.class);
            startActivity(launchactivity);

        }
    });

This is my logcat

09-24 21:22:29.009 6353-6353/com.example.fra31.tradebooks E/AndroidRuntime: FATAL EXCEPTION: main
                                                                              Process: com.example.fra31.tradebooks, PID: 6353
                                                                              java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.fra31.tradebooks/com.example.fra31.tradebooks.add}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2356)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2418)
                                                                                at android.app.ActivityThread.access$900(ActivityThread.java:154)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:135)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5289)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
                                                                                at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:115)
                                                                               Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
                                                                                at com.example.fra31.tradebooks.add.onCreate(add.java:47)
                                                                                at android.app.Activity.performCreate(Activity.java:5990)
                                                                                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2309)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2418)
                                                                                at android.app.ActivityThread.access$900(ActivityThread.java:154)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:135)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5289)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
                                                                                at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:115)

Body:
Intent launchactivity=new Intent (MainActivity.this,add.class);
            startActivity(launchactivity);

and you should go to androidmanifest.xml and define your activity as this :

<activity android:name=".MainActivity">
       </activity>


答: Initialize k before you use, else it will contain junk value  int k = 0;

Title: C++ : Why it dont work?