问:
Full height of content in listview with ItemsWrapGrid as panel template windows 10 app
I am trying to have the content of gridview cell to stretch the height so there is no scrolling within the cell.

Here's my code:

```<code><Grid Grid.Row="1" Padding="50 10 50 10">
    <ListView IsTapEnabled="False"
        Background="White"
        SizeChanged="categoryListView_SizeChanged"
        x:Name="categoryListView"
        Height="auto"
        HorizontalAlignment="Stretch"
        VerticalAlignment="Stretch"
        ItemsSource="{Binding Source={StaticResource stores}, Path=CollectionGroups}"
        ItemTemplate="{StaticResource CategoriesList}">
        <ListView.ItemsPanel>
            <ItemsPanelTemplate>
                <ItemsWrapGrid Orientation="Horizontal"/>
            </ItemsPanelTemplate>
        </ListView.ItemsPanel>
    </ListView>
</Grid>
</code>```

and here is my data template:

```<code><DataTemplate x:Key="CategoriesList">
    <Grid x:Name="AlphabetGrid" VerticalAlignment="Top" HorizontalAlignment="Left" Margin="0 0 20 0">
        <TextBlock x:Name="CategoryName" FontSize="24" Text='{Binding Group.Key}' Foreground="#412141" FontWeight="Bold"  HorizontalAlignment="Left" TextAlignment="Left"/>
        <Grid Margin="0 30 0 0">
            <ListView ItemsSource="{Binding Group.Items}" HorizontalAlignment="Stretch" VerticalAlignment="Top">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <Grid Margin="0">
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="*"></ColumnDefinition>
                                <ColumnDefinition Width="4*"></ColumnDefinition>
                            </Grid.ColumnDefinitions>
                            <TextBlock Grid.Column="0" x:Name="unit_number" FontSize="15"  Text='{Binding unit}' Foreground="red"  HorizontalAlignment="Left" TextAlignment="Left"/>
                            <TextBlock Grid.Column="1" x:Name="name" FontSize="15"  Text='{Binding name}' Foreground="red"  HorizontalAlignment="Left" TextAlignment="Left"/>
                        </Grid>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
        </Grid>
    </Grid>
</DataTemplate>
</code>```

How can I achieve this? Any recommendations?
This is how it looks right now.

答:
I can reproduce your issue: it seems that ItemsWrapGrid uses some strange logic when row heights are calculated automatically. You can set its ItemHeight property manually to avoid this problem, but this solution is far from being elegant.

Alternatively you can use the WrapPanel XAML Control from the UWP Community Toolkit as an ItemsPanelTemplate for your ListView to make the items stretch their height to fit the content

```<code><ListView>
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <controls:WrapPanel/>
        <ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
</ListView>
</code>```

however, your grid is going to have a lot of empty space then

If that's not what you want, you can eliminate most of the empty spaces by changing the orientation of the WrapPanel from horizontal to vertical

and even further by not grouping your items into separate controls by category

Body:
I am trying to have the content of gridview cell to stretch the height so there is no scrolling within the cell.

Here's my code:

<Grid Grid.Row="1" Padding="50 10 50 10">
    <ListView IsTapEnabled="False"
        Background="White"
        SizeChanged="categoryListView_SizeChanged"
        x:Name="categoryListView"
        Height="auto"
        HorizontalAlignment="Stretch"
        VerticalAlignment="Stretch"
        ItemsSource="{Binding Source={StaticResource stores}, Path=CollectionGroups}"
        ItemTemplate="{StaticResource CategoriesList}">
        <ListView.ItemsPanel>
            <ItemsPanelTemplate>
                <ItemsWrapGrid Orientation="Horizontal"/>
            </ItemsPanelTemplate>
        </ListView.ItemsPanel>
    </ListView>
</Grid>

and here is my data template:

<DataTemplate x:Key="CategoriesList">
    <Grid x:Name="AlphabetGrid" VerticalAlignment="Top" HorizontalAlignment="Left" Margin="0 0 20 0">
        <TextBlock x:Name="CategoryName" FontSize="24" Text='{Binding Group.Key}' Foreground="#412141" FontWeight="Bold"  HorizontalAlignment="Left" TextAlignment="Left"/>
        <Grid Margin="0 30 0 0">
            <ListView ItemsSource="{Binding Group.Items}" HorizontalAlignment="Stretch" VerticalAlignment="Top">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <Grid Margin="0">
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="*"></ColumnDefinition>
                                <ColumnDefinition Width="4*"></ColumnDefinition>
                            </Grid.ColumnDefinitions>
                            <TextBlock Grid.Column="0" x:Name="unit_number" FontSize="15"  Text='{Binding unit}' Foreground="red"  HorizontalAlignment="Left" TextAlignment="Left"/>
                            <TextBlock Grid.Column="1" x:Name="name" FontSize="15"  Text='{Binding name}' Foreground="red"  HorizontalAlignment="Left" TextAlignment="Left"/>
                        </Grid>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
        </Grid>
    </Grid>
</DataTemplate>

How can I achieve this? Any recommendations?
This is how it looks right now.

Body:
I can reproduce your issue: it seems that ItemsWrapGrid uses some strange logic when row heights are calculated automatically. You can set its ItemHeight property manually to avoid this problem, but this solution is far from being elegant.

Alternatively you can use the WrapPanel XAML Control from the UWP Community Toolkit as an ItemsPanelTemplate for your ListView to make the items stretch their height to fit the content

<ListView>
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <controls:WrapPanel/>
        <ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
</ListView>

however, your grid is going to have a lot of empty space then

If that's not what you want, you can eliminate most of the empty spaces by changing the orientation of the WrapPanel from horizontal to vertical

and even further by not grouping your items into separate controls by category


来源: stackexchange

问:
Exception occurs performing aggregate queries on x64 platform
When running a query using aggregates I receive the following exception:

```<code>Microsoft.Azure.Documents.BadRequestException:
{"Errors":["Cross partition query only supports 'VALUE <AggreateFunc>' for aggregates."]}
---> System.Runtime.InteropServices.COMException: Exception from HRESULT: 0x800A0B00
</code>```

My query code is:

```<code>var store = "1234";
var sumResults = client.CreateDocumentQuery(
UriFactory.CreateDocumentCollectionUri("my-data-db", "my-collection"),
$"SELECT SUM(t.totalAmount) FROM t where t.siteData.siteID = '{store}'");
</code>```

It took me a while to figure out this works fine when the build platform is set to x86 but fails when set to x64.

I'm using the latest version of the package 1.12.2

Any ideas on how to make the x64 version work?

答:
You need to put Value in your query, like this

SELECT VALUE COUNT(1)
FROM C

ContentLicense: CC BY-SA 3.0

Body:
When running a query using aggregates I receive the following exception:

Microsoft.Azure.Documents.BadRequestException:
{"Errors":["Cross partition query only supports 'VALUE <AggreateFunc>' for aggregates."]}
---> System.Runtime.InteropServices.COMException: Exception from HRESULT: 0x800A0B00

My query code is:

var store = "1234";
var sumResults = client.CreateDocumentQuery(
UriFactory.CreateDocumentCollectionUri("my-data-db", "my-collection"),
$"SELECT SUM(t.totalAmount) FROM t where t.siteData.siteID = '{store}'");

It took me a while to figure out this works fine when the build platform is set to x86 but fails when set to x64.

I'm using the latest version of the package 1.12.2

Any ideas on how to make the x64 version work?


问:
How to store file into inetpub\wwwroot instead of local machine folder on UWP application
I am currently developing a UWP application for my school project and one of the pages allows the user to take a picture of themselves. I created the feature by following this tutorial: CameraStarterKit

For now I am storing the pictures taken on my desktop's picture folder. But the requirement of my project is to store the pictures taken in a folder called "Photos" under inetpub\wwwroot.

I dont really understand what wwwroot or IIS is... hence, I have no idea how I should modify my codes and store them into the folder.

Here are my codes for storing on my local desktop:

```<code>private async Task TakePhotoAsync()
    {
        idleTimer.Stop();
        idleTimer.Start();

        var stream = new InMemoryRandomAccessStream();

        //MediaPlayer mediaPlayer = new MediaPlayer();
        //mediaPlayer.Source = MediaSource.CreateFromUri(new Uri("ms-appx:///Assets/camera-shutter-click-03.mp3"));
        //mediaPlayer.Play();

        Debug.WriteLine("Taking photo...");
        await _mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream);

        try
        {
            var file = await _captureFolder.CreateFileAsync("NYPVisitPhoto.jpg", CreationCollisionOption.GenerateUniqueName);
            Debug.WriteLine("Photo taken! Saving to " + file.Path);

            var photoOrientation = CameraRotationHelper.ConvertSimpleOrientationToPhotoOrientation(_rotationHelper.GetCameraCaptureOrientation());

            await ReencodeAndSavePhotoAsync(stream, file, photoOrientation);
            Debug.WriteLine("Photo saved!");

        }
        catch (Exception ex)
        {
            // File I/O errors are reported as exceptions
            Debug.WriteLine("Exception when taking a photo: " + ex.ToString());
        }

    }
</code>```

For the storing of the files:

```<code>private static async Task ReencodeAndSavePhotoAsync(IRandomAccessStream stream, StorageFile file, PhotoOrientation photoOrientation)
    {
        using (var inputStream = stream)
        {
            var decoder = await BitmapDecoder.CreateAsync(inputStream);

            using (var outputStream = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                var encoder = await BitmapEncoder.CreateForTranscodingAsync(outputStream, decoder);

                var properties = new BitmapPropertySet { { "System.Photo.Orientation", new BitmapTypedValue(photoOrientation, PropertyType.UInt16) } };

                await encoder.BitmapProperties.SetPropertiesAsync(properties);
                await encoder.FlushAsync();
            }
        }
    }
</code>```

答:
Kennyzx is right here that you cannot access inetpub folder through your UWP application due to permissions.

But if your application fulfills following criteria then you can use Brokered Windows Component(a component within your app) to copy your file to any location in the system.

Your application is a LOB application

You are only targetting desktop devices(I assume this will be true because of your requirement)

You are using side-loading for your app installation and distribution.

If all three are Yes then use Brokered Windows Component for UWP, it's not a small thing that can be showed here on SO using an example. So give worth a try reading and implementing it.

Body:
I am currently developing a UWP application for my school project and one of the pages allows the user to take a picture of themselves. I created the feature by following this tutorial: CameraStarterKit

For now I am storing the pictures taken on my desktop's picture folder. But the requirement of my project is to store the pictures taken in a folder called "Photos" under inetpub\wwwroot.

I dont really understand what wwwroot or IIS is... hence, I have no idea how I should modify my codes and store them into the folder.

Here are my codes for storing on my local desktop:

private async Task TakePhotoAsync()
    {
        idleTimer.Stop();
        idleTimer.Start();

        var stream = new InMemoryRandomAccessStream();

        //MediaPlayer mediaPlayer = new MediaPlayer();
        //mediaPlayer.Source = MediaSource.CreateFromUri(new Uri("ms-appx:///Assets/camera-shutter-click-03.mp3"));
        //mediaPlayer.Play();

        Debug.WriteLine("Taking photo...");
        await _mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream);

        try
        {
            var file = await _captureFolder.CreateFileAsync("NYPVisitPhoto.jpg", CreationCollisionOption.GenerateUniqueName);
            Debug.WriteLine("Photo taken! Saving to " + file.Path);

            var photoOrientation = CameraRotationHelper.ConvertSimpleOrientationToPhotoOrientation(_rotationHelper.GetCameraCaptureOrientation());

            await ReencodeAndSavePhotoAsync(stream, file, photoOrientation);
            Debug.WriteLine("Photo saved!");

        }
        catch (Exception ex)
        {
            // File I/O errors are reported as exceptions
            Debug.WriteLine("Exception when taking a photo: " + ex.ToString());
        }

    }

For the storing of the files:

private static async Task ReencodeAndSavePhotoAsync(IRandomAccessStream stream, StorageFile file, PhotoOrientation photoOrientation)
    {
        using (var inputStream = stream)
        {
            var decoder = await BitmapDecoder.CreateAsync(inputStream);

            using (var outputStream = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                var encoder = await BitmapEncoder.CreateForTranscodingAsync(outputStream, decoder);

                var properties = new BitmapPropertySet { { "System.Photo.Orientation", new BitmapTypedValue(photoOrientation, PropertyType.UInt16) } };

                await encoder.BitmapProperties.SetPropertiesAsync(properties);
                await encoder.FlushAsync();
            }
        }
    }


问:
Number of positive integers in [1,1e18] that cannot be divided by any integers in [2,10]
I am having difficulty trying to solve the following problem:

For Q queries, Q <= 1e6, where each query is a positive integer N, N <= 1e18, find the number of integers in [1,N] that cannot be
  divided by integers in [2,10] for each query.

I thought of using using a sieve method to filter out numbers in [1,1e18] for each query (similar to sieve of eratosthenes). However, the value of N  could be very large. Hence, there is no way I could use this method. The most useful observation that I could make is that numbers ending with 0,2,4,5,6,8 are invalid. But that does not help me with this problem.

I saw a solution for a similar problem that uses a smaller number of queries (Q <= 200). But it doesn't work for this problem (and I don't understand that solution).

Could someone please advise me on how to solve this problem?

答:
The only matter numbers in [2,10] are those primes which are 2, 3, 5, 7

So, Let say, the number cannot be divided by integers in [2,10] is the number cannot be divided by {2,3,5,7}

Which is also equalled to the total number between [1,n] minus all number that is divided by any combination of {2,3,5,7}.

So, this is the fun part: from [1,n] how many numbers that is divided by 2?
The answer is n/2 (why? simple, because every 2 number, there is one number divided by 2)

Similarly, how many numbers that is divided by 5? The answer is n/5
...

So, do we have our answer yet? No, as we found out that we have doubled count those numbers that divided by both {2, 5} or {2, 7} ..., so now, we need to minus them.

But wait, seems like we are double minus those that divided by {2,5,7} ... so we need to add it back

...

Keep doing this until all combinations are taken care of,
so there should be 2^4 combination, which is 16 in total, pretty small to deal with.

Take a look at Inclusion-Exclusion principle for some good understanding.

Good luck!


问:
CakePHP 3 Ajax script work in view but not in external script
I'm using CakePHP 3 and the following script to call a controller

```<code>$('.link_like').click(function(event) {

    event.preventDefault();

    var id = $(this).data('value');

    $.ajax({
        type: "GET",
        url: '/instatux/like-'+id +'',
        success: function(data){
            $('#compteur_like-' +id +'')
            .append(data);

        },
        error: function(data)
        {
            alert('fail');
        }
    });
});
</code>```

This script works perfectly when he is inside a view but i want to use it as an external script , a .js file in the js folder
but I get an error 500 without further details.

Did i miss something or any cakephp configuration ?

I have some others script in the js folder and he works good.

答:
According to your comment, I think you are facing the problem for not created add.ctp file. </p>

<p>If you don't want to create add.ctp file. In your controller you should use </p>

```<code>$this->autoRender = false;
</code>```

Body:
I'm using CakePHP 3 and the following script to call a controller

$('.link_like').click(function(event) {

    event.preventDefault();

    var id = $(this).data('value');

    $.ajax({
        type: "GET",
        url: '/instatux/like-'+id +'',
        success: function(data){
            $('#compteur_like-' +id +'')
            .append(data);

        },
        error: function(data)
        {
            alert('fail');
        }
    });
});

This script works perfectly when he is inside a view but i want to use it as an external script , a .js file in the js folder
but I get an error 500 without further details.

Did i miss something or any cakephp configuration ?

I have some others script in the js folder and he works good.

Body:
According to your comment, I think you are facing the problem for not created add.ctp file.

If you don't want to create add.ctp file. In your controller you should use

$this->autoRender = false;


问:
MySQL - Update old default datetime value to new default value
I am working on an database version of mysql where they use to have a date time column with default value set as 0000-00-00 00:00:00. Now that i been creating new table with the new default date time value of 1000-00-00 00:00:00. When i try to INSERT and JOIN the two table i this error:

```<code>#1292 - Incorrect datetime value: '0000-00-00 00:00:00' for column 'process_date' at row 1
</code>```

So to fix this i try to use this code

```<code>UPDATE tableA
SET process_date = '1000-01-01 00:00:00'
WHERE process_date = '0000-00-00 00:00:00';
</code>```

And is giving me the same error as above, i have many rows and i don't want to manually set them.. any suggestion?

Added
TableA (old table with old default date value)and TableB (new) have the same structure while TableA is the source. And i need data from TableA INSERT into TableB

答:
In this post on stackoverflow
MySQL Incorrect datetime value: '0000-00-00 00:00:00'

i used this code to fix my update problem

UPDATE TableA
SET process_date = '1000-01-01 00:00:00'
WHERE CAST(process_date AS CHAR(20)) = '0000-00-00 00:00:00';

Body:
I am working on an database version of mysql where they use to have a date time column with default value set as 0000-00-00 00:00:00. Now that i been creating new table with the new default date time value of 1000-00-00 00:00:00. When i try to INSERT and JOIN the two table i this error:

#1292 - Incorrect datetime value: '0000-00-00 00:00:00' for column 'process_date' at row 1

So to fix this i try to use this code

UPDATE tableA
SET process_date = '1000-01-01 00:00:00'
WHERE process_date = '0000-00-00 00:00:00';

And is giving me the same error as above, i have many rows and i don't want to manually set them.. any suggestion?

Added
TableA (old table with old default date value)and TableB (new) have the same structure while TableA is the source. And i need data from TableA INSERT into TableB


问:
Undefined variable: users (View: C:\xampp\htdocs\rentalmobil\resources\views\admin\user.blade.php)

SOLVED

i am confusing that i think i have already make a true code with laravel. i have seen on many references for me to know how to read database. yes i'm newbie and still learning. well here is my code

from model. admin.php is the name of folder:

```<code><?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Admin extends Model
{
    protected $table = "admin";
}
</code>```

here is my controller. my controller name is UserController.php

```<code><?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Admin;

class UserController extends Controller
{
    public function users(){
        $users = Admin::all();
        return view('admin.user', ['admin' => $users]);
    }

}
</code>```

and here is my view, it is located in view/admin/ named user.blade.php:

```<code>@extends('admin.header')

@section('content')
<div class="col-md-12">
    <div class="card">
        <div class="header">
            <h4 class="title">Striped Table</h4>
            <p class="category">Here is a subtitle for this table</p>
        </div>
        <div class="content table-responsive table-full-width">
            <table class="table table-striped">
                <thead>
                    <th>ID</th>
                    <th>Name</th>
                    <th>Salary</th>
                    <th>Country</th>
                    <th>City</th>
                </thead>
                <tbody>
                    <tr>
                        <td>1</td>
                        <td>{{ $users->email }}</td>
                        <td>$36,738</td>
                        <td>Niger</td>
                        <td>Oud-Turnhout</td>
                    </tr>
                </tbody>
            </table>

        </div>
    </div>
</div>
@endsection
</code>```

and here is my error

i call from my browser with this http://localhost:8000/users

sorry for bad English :(

答:
```<code>@foreach($admin as $users)
<tbody>
                    <tr>
                        <td>1</td>
                        <td>{{ $users->email }}</td>
                        <td>$36,738</td>
                        <td>Niger</td>
                        <td>Oud-Turnhout</td>
                    </tr>
                </tbody>
@endforeach
</code>```

if u not need for each

```<code>             <tbody>
                        <tr>
                            <td>1</td>
                            <td>{{ $admin[0]->email }}</td>
                            <td>$36,738</td>
                            <td>Niger</td>
                            <td>Oud-Turnhout</td>
                        </tr>
                    </tbody>
</code>```

Body:
SOLVED

i am confusing that i think i have already make a true code with laravel. i have seen on many references for me to know how to read database. yes i'm newbie and still learning. well here is my code

from model. admin.php is the name of folder:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Admin extends Model
{
    protected $table = "admin";
}

here is my controller. my controller name is UserController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Admin;

class UserController extends Controller
{
    public function users(){
        $users = Admin::all();
        return view('admin.user', ['admin' => $users]);
    }

}

and here is my view, it is located in view/admin/ named user.blade.php:

@extends('admin.header')

@section('content')

Striped Table

Here is a subtitle for this table

                    ID
                    Name
                    Salary
                    Country
                    City

                        1
                        {{ $users->email }}
                        $36,738
                        Niger
                        Oud-Turnhout

@endsection

and here is my error

i call from my browser with this http://localhost:8000/users

sorry for bad English :(

Body:
@foreach($admin as $users)
<tbody>
                    <tr>
                        <td>1</td>
                        <td>{{ $users->email }}</td>
                        <td>$36,738</td>
                        <td>Niger</td>
                        <td>Oud-Turnhout</td>
                    </tr>
                </tbody>
@endforeach

if u not need for each

             <tbody>
                        <tr>
                            <td>1</td>
                            <td>{{ $admin[0]->email }}</td>
                            <td>$36,738</td>
                            <td>Niger</td>
                            <td>Oud-Turnhout</td>
                        </tr>
                    </tbody>


问:
Unable to click or select the value which is displayed in dropdown
I am trying to implement some code using Selenium Webdriver using Java.

Basically, I have a website with a text box. Once user enter the first letter, based on that a value will be displayed(using AJAX). I need to select the particular value, which i mentioned in send keys .

```<code>WebElement fromCity = driver.findElement(By.id("pickUpLocation"));
fromCity.sendKeys("A Ma Temple / 媽閣");

Thread.sleep(2000);

WebElement ajaxContainer1 = driver.findElement(By.className("txt-box ng-touched ng-dirty ng-valid"));
WebElement ajaxHolder1 = ajaxContainer1.findElement(By.tagName("ul"));
List<WebElement> ajaxValues1 = ajaxHolder1.findElements(By.tagName("li"));

for (WebElement value1 : ajaxValues1) {
    if (value1.getText().equals("A Ma Temple ")) {
        ((WebElement)ajaxValues1).click();
        break;
    }
}
</code>```

答:
After you send keys.your Ajax value should be retrieved in a box related to you keyword search.You need to get the complete box.and fetch each one as you have done in for loop .get the text and compare it with your expected text and click where this condition is true.
What is that line for before thread.sleep()</p>

Body:
I am trying to implement some code using Selenium Webdriver using Java.

Basically, I have a website with a text box. Once user enter the first letter, based on that a value will be displayed(using AJAX). I need to select the particular value, which i mentioned in send keys .

WebElement fromCity = driver.findElement(By.id("pickUpLocation"));
fromCity.sendKeys("A Ma Temple / 媽閣");

Thread.sleep(2000);

WebElement ajaxContainer1 = driver.findElement(By.className("txt-box ng-touched ng-dirty ng-valid"));
WebElement ajaxHolder1 = ajaxContainer1.findElement(By.tagName("ul"));
List<WebElement> ajaxValues1 = ajaxHolder1.findElements(By.tagName("li"));

for (WebElement value1 : ajaxValues1) {
    if (value1.getText().equals("A Ma Temple ")) {
        ((WebElement)ajaxValues1).click();
        break;
    }
}


问:
How to divide screen to two parts in react-native?
I'm new in react-native, and I'm trying to divide screen to tow part, the first part is the header or the navigation bar wish have a specific height about 40px the second part is the body or the content of the app wish his height must be the available height on the phone screen, I tried to use flex box method but it's not working!
That's my code:

```<code><View style={styles.mainContainer}>
    <View style={styles.navBar}>
    </View>
    <View style={styles.body}>
    </View>
</View>
</code>```

Style:

```<code>mainContainer: {
  height: '100%',
  display: 'flex',
  flexDirection: 'column',
},
navBar: {
  display: 'flex',
  flexDirection: 'row-reverse',
  justifyContent: 'space-between',
  alignItems: 'center',
  backgroundColor: '#f1f1f1',
  height: 30,
},
body: {
  flex: 3,
  display: 'flex',
},
</code>```

答:
just use this way, i hope this will work.</p>

```<code> <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF'}}>
   <View style={{flex:1, backgroundColor:"green"}}>
    <Text>hello world 1.........</Text>
    <Text>hello world 1.........</Text>
    <Text>hello world 1.........</Text>
    <Text>hello world 1.........</Text>
    </View>
      <View style={{flex:1, backgroundColor:"yellow"}}>
    <Text>hello world 2.........</Text>
    <Text>hello world 2.........</Text>
    <Text>hello world 2.........</Text>
    <Text>hello world 2.........</Text>
    </View>
  </View>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm new in react-native, and I'm trying to divide screen to tow part, the first part is the header or the navigation bar wish have a specific height about 40px the second part is the body or the content of the app wish his height must be the available height on the phone screen, I tried to use flex box method but it's not working!
That's my code:

<View style={styles.mainContainer}>
    <View style={styles.navBar}>
    </View>
    <View style={styles.body}>
    </View>
</View>

Style:

mainContainer: {
  height: '100%',
  display: 'flex',
  flexDirection: 'column',
},
navBar: {
  display: 'flex',
  flexDirection: 'row-reverse',
  justifyContent: 'space-between',
  alignItems: 'center',
  backgroundColor: '#f1f1f1',
  height: 30,
},
body: {
  flex: 3,
  display: 'flex',
},

Body:
just use this way, i hope this will work.

 <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF'}}>
   <View style={{flex:1, backgroundColor:"green"}}>
    <Text>hello world 1.........</Text>
    <Text>hello world 1.........</Text>
    <Text>hello world 1.........</Text>
    <Text>hello world 1.........</Text>
    </View>
      <View style={{flex:1, backgroundColor:"yellow"}}>
    <Text>hello world 2.........</Text>
    <Text>hello world 2.........</Text>
    <Text>hello world 2.........</Text>
    <Text>hello world 2.........</Text>
    </View>
  </View>


问:
Is writing unions content to file safe
I am developing simple virtual machine in C, and it will use Threaded code, consider this structure:

```<code>struct opcode
{
  int somefields; //etc
  union z
  {
    char opcode;
    void *opaddress;
  }
}
</code>```

my question is, is't safe and portable to write such struct with char data (opcode) and load that file on another machine (and maybe different architecture) and fill the pointer (opaddress) on the fly?

答:
The data types will vary between different architecture, so you can't guarantee the same size.

```<code>typedef struct
{
  int somefields; //etc
  union
  {
    char opcode;
    void *opaddress;
  }z;
}opc;
</code>```

you can access something like this

```<code>opc.somefields = 10;
opc.z.opcode = 1;
</code>```

Title: Is writing unions content to file safe

Body:
I am developing simple virtual machine in C, and it will use Threaded code, consider this structure:

struct opcode
{
  int somefields; //etc
  union z
  {
    char opcode;
    void *opaddress;
  }
}

my question is, is't safe and portable to write such struct with char data (opcode) and load that file on another machine (and maybe different architecture) and fill the pointer (opaddress) on the fly?

Body:
The data types will vary between different architecture, so you can't guarantee the same size.

typedef struct
{
  int somefields; //etc
  union
  {
    char opcode;
    void *opaddress;
  }z;
}opc;

you can access something like this

opc.somefields = 10;
opc.z.opcode = 1;


问:
.htaccess and php includ on same server using subdomain
I have been searching all day for a solution to this and searched here.

I have a central file for including functions for all sites on the server, this looks up to the database and if valid includes the file as a .inc as the sites could be on any server so has to process over a url. So I set up a subdomain to test this and everything works fine, however if someone where to look up the link in the site they can go direct and browse the .inc file.

I've tried looking up on here how to deny someone from browsing the file if they are viewing through the browser. This works, however if the website requesting/including the functions.inc are hosted on the same server then the requesting HTTP_HOST/REFFERER becomes the subdomain and the functions.inc file is exluded.

So far I had this:-

RewriteEngine on
RewriteCond %{SERVER_NAME} !^http://(www.)?subdomainchecker.mysite.co.uk/.*$ [NC]
RewriteRule .(inc)$ - [F]

See the subdomain acts like a service. And the reason I want to do this is that I want all the php functions in one place for everyone. that way I'm only maintaining one file. One bug fix etc.

Now I thought there has to be a way to check that there is a difference when using a subdomain.

However if there is a better way???

If this doesn't work maybe I could get htaccess to include (a virtual folder) to my subdomain folder so that I don't have to go over a url... but that wont work if the site gets hosted on another server?

Or... could I do a look up straight to the DB, as the user credentials only has SELECT privileges only. Could the DB contain all the functions and output them from a text field? Or have functions listings in a DB and retrieve the function when I do a database call?

Or... could I do a php XML request and return the php functions within an XML node?

I'd rather keep the functions and classes in a file than on a DB, but I am not sure how the best way to go about it is. All I want to do is keep my php functions in one place.

If anyone has any ideas?

Thanks

Andi

答:
Ok So I answered my own question eventually like so.

Step 1) I password protected my .inc files using .htaccess in the directory that stores my include files on my webservice (subdomain). Protecting both .inc and .php

```<code>Options -Indexes

<FilesMatch "\.(inc|php|anyext)$">
AuthType Basic
AuthName "authenticate this puppy"
AuthUserFile /[servername]/[accountusernameOnServer]/.unseenfolder/public_html/[website_authentication_folder]/.htpasswd
Require valid-user

</FilesMatch>
</code>```

This folder is now password protected by the encrypted .htpassword file outside my web root.

Step 2) Back in my now protected webserivce folder contains three files (one .php / two .inc files containing my functions and application file (session variables for the site)

authenticate_some_websitesite_against_my_own_DB.php
This contains the account verification process (lookup to a database on my own server), note the host is always Localhost and I am using PHP PDO for convenience (just in case you have a Postgre database or MSSQL etc)

application_for_site.inc
This contains/sets all the site session variables (user ID etc)

a file without a name called .anyext containing my global functions for all sites

Now here is the cool thing. THE PROCESS or how I got it to work.

I put my new website in a subfolder and include a file called authentication.php in my local folder in the site. I call this in the head of index.php in the site.
This file contains my webkey, usernames and passwords to my clients table in my DB which is used to verify in the file I call from my subdomain... authenticate_some_websitesite_against_my_own_DB.php

I put all these variables in a url variable which also include my username and password to my protected subdomain.
So now it looks something like this: Of course I set the variables above

```<code>$link = "authenticate_anewsite.php";

// Create Website check link criteria.
$link .= "?website=" . $_SERVER['HTTP_HOST'];
$link .= "&website_folder=$website_folder";
$link .= "&webkey=$webkey";
$link .= "&username=$username";
$link .= "&password=$password";
$link .= "&base_url=$base_url";
$link .= "&DBLangtype=$DBLangtype";
$link .= "&localDBtype=$localDBtype";
$link .= "&content_folder=$content_folder";
$link .= "&google_api=$google_api";
$link .= "&menu_folder=$menu_folder";
$link .= "&news_folder=$news_folder";
$link .= "&events_folder=$events_folder";
$link .= "&documents_folder=$documents_folder";
$link .= "&uploaded_images_folder=$uploaded_images_folder";
$link .= "&gallery_folder=$gallery_folder";

//// Do not delete required to access the link below
$PHP_AUTH_USER = "website_user"; /// Do NOT AMEND THIS
$PHP_AUTH_PW = "passw0rd"; /// Do NOT AMEND THIS
$path = "http://$PHP_AUTH_USER:$PHP_AUTH_PW@www.websitecheck.mydomain.com/"; /// Do NOT AMEND THIS LINK
$authCHK = $path . $link;

/// going to check that we connect
$handle = curl_init($authCHK);
curl_setopt($handle,  CURLOPT_RETURNTRANSFER, TRUE);

/* Get the HTML or whatever is linked in $url. */
$response = curl_exec($handle);

/* Check for 404 (file not found). */
$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);

/// If server can't connect
if($httpCode == 401) {

    //set error handler
    set_error_handler("customError", E_ALL);

    /* Handle 404 here. */
    trigger_error("<strong style='color:red;'>Error: SERVER - $httpCode</strong> $website failed to connect to authenticate site.<br />Connection string..:\n $authCHK");

//  error_function(error_level,error_message,error_file,error_line,error_context)

} else {

    require_once($authCHK);

} // end if

curl_close($handle);
</code>```

Now the file successfully includes the .php file from the server because the username and password to it are parsed in the url.

in the authenticate_anewsite.php I just included (actually I did a require_once) this is the bit that authenticates my website against my clients table which runs these checks:

The MySQL database username and password are stored in this file. This account has only the priveliges of select.

checks clients for existence of a webkey which I give them

check the username against the clients table

checks the password

paid = true

active = true

So the SQL looks like this:

```<code>SELECT * FROM clients where paid=1 and active=1 and webkey = '$webkey' and username = '$username' and password = '$password'
</code>```

If the required checks are verified then the num of records is 1, if this is >0 then my authenticate_anewsite.php includes the other two .inc files like this (the folder username and password have already been verified in the call.

if ($count_check > 0) {

```<code>$appliation = $path . 'application_for_my_site.inc';
$appliation = file_get_contents($appliation);
echo $appliation;

$functions = $path . '.anyext';
$functions = file_get_contents($functions);
echo $functions;

} else {
// redirect to the holding page
//header('Location: $base_url/500.shtml');
</code>```

}

At this point its probably ok to set a session variable to not keep checking the database every time the index.php page is called from the actual site.

OK so this actually works although a little Archaic.

The advantages of all this:

Functions and application are served from one file in a central location (one bug fix can fix all sites)

Doesn't matter if the website is hosted on my server or on another

A user cannot browse the files directly, because htaccess has password protected them

Even if a user were to browse the subdomain/webservice in the browser by putting the link together with the folder username and password the browser, it doesn't server the PHP as is server sided script. It wont be able to see my username and database password, sql, or the name of the files I'm calling in by viewing source

I have my functions in a file with no file name and an extension that I have made up this is the purpose of the .anyext (htaccess treats this the same and protects it, but because its an extension that I made up it makes it harder to guess, and generally invisible)

indexes have been switched off so general browsing is not allowed on my webservice

OK so it took me two days to come up with this solution. I hope that my idea will help save someone a lot of time!

Bless You :o)

Andi Lee Davis

ContentLicense: CC BY-SA 2.5

Body:
Ok So I answered my own question eventually like so.

Step 1) I password protected my .inc files using .htaccess in the directory that stores my include files on my webservice (subdomain). Protecting both .inc and .php

Options -Indexes

<FilesMatch "\.(inc|php|anyext)$">
AuthType Basic
AuthName "authenticate this puppy"
AuthUserFile /[servername]/[accountusernameOnServer]/.unseenfolder/public_html/[website_authentication_folder]/.htpasswd
Require valid-user

</FilesMatch>

This folder is now password protected by the encrypted .htpassword file outside my web root.

Step 2) Back in my now protected webserivce folder contains three files (one .php / two .inc files containing my functions and application file (session variables for the site)

authenticate_some_websitesite_against_my_own_DB.php
This contains the account verification process (lookup to a database on my own server), note the host is always Localhost and I am using PHP PDO for convenience (just in case you have a Postgre database or MSSQL etc)

application_for_site.inc
This contains/sets all the site session variables (user ID etc)

a file without a name called .anyext containing my global functions for all sites

Now here is the cool thing. THE PROCESS or how I got it to work.

I put my new website in a subfolder and include a file called authentication.php in my local folder in the site. I call this in the head of index.php in the site.
This file contains my webkey, usernames and passwords to my clients table in my DB which is used to verify in the file I call from my subdomain... authenticate_some_websitesite_against_my_own_DB.php

I put all these variables in a url variable which also include my username and password to my protected subdomain.
So now it looks something like this: Of course I set the variables above

$link = "authenticate_anewsite.php";

// Create Website check link criteria.
$link .= "?website=" . $_SERVER['HTTP_HOST'];
$link .= "&website_folder=$website_folder";
$link .= "&webkey=$webkey";
$link .= "&username=$username";
$link .= "&password=$password";
$link .= "&base_url=$base_url";
$link .= "&DBLangtype=$DBLangtype";
$link .= "&localDBtype=$localDBtype";
$link .= "&content_folder=$content_folder";
$link .= "&google_api=$google_api";
$link .= "&menu_folder=$menu_folder";
$link .= "&news_folder=$news_folder";
$link .= "&events_folder=$events_folder";
$link .= "&documents_folder=$documents_folder";
$link .= "&uploaded_images_folder=$uploaded_images_folder";
$link .= "&gallery_folder=$gallery_folder";

//// Do not delete required to access the link below
$PHP_AUTH_USER = "website_user"; /// Do NOT AMEND THIS
$PHP_AUTH_PW = "passw0rd"; /// Do NOT AMEND THIS
$path = "http://$PHP_AUTH_USER:$PHP_AUTH_PW@www.websitecheck.mydomain.com/"; /// Do NOT AMEND THIS LINK
$authCHK = $path . $link;

/// going to check that we connect
$handle = curl_init($authCHK);
curl_setopt($handle,  CURLOPT_RETURNTRANSFER, TRUE);

/* Get the HTML or whatever is linked in $url. */
$response = curl_exec($handle);

/* Check for 404 (file not found). */
$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);

/// If server can't connect
if($httpCode == 401) {

    //set error handler
    set_error_handler("customError", E_ALL);

    /* Handle 404 here. */
    trigger_error("<strong style='color:red;'>Error: SERVER - $httpCode</strong> $website failed to connect to authenticate site.<br />Connection string..:\n $authCHK");

//  error_function(error_level,error_message,error_file,error_line,error_context)

} else {

    require_once($authCHK);

} // end if

curl_close($handle);

Now the file successfully includes the .php file from the server because the username and password to it are parsed in the url.

in the authenticate_anewsite.php I just included (actually I did a require_once) this is the bit that authenticates my website against my clients table which runs these checks:

The MySQL database username and password are stored in this file. This account has only the priveliges of select.

checks clients for existence of a webkey which I give them

check the username against the clients table

checks the password

paid = true

active = true

So the SQL looks like this:

SELECT * FROM clients where paid=1 and active=1 and webkey = '$webkey' and username = '$username' and password = '$password'

If the required checks are verified then the num of records is 1, if this is >0 then my authenticate_anewsite.php includes the other two .inc files like this (the folder username and password have already been verified in the call.

if ($count_check > 0) {

$appliation = $path . 'application_for_my_site.inc';
$appliation = file_get_contents($appliation);
echo $appliation;

$functions = $path . '.anyext';
$functions = file_get_contents($functions);
echo $functions;

} else {
// redirect to the holding page
//header('Location: $base_url/500.shtml');

}

At this point its probably ok to set a session variable to not keep checking the database every time the index.php page is called from the actual site.

OK so this actually works although a little Archaic.

The advantages of all this:

Functions and application are served from one file in a central location (one bug fix can fix all sites)

Doesn't matter if the website is hosted on my server or on another

A user cannot browse the files directly, because htaccess has password protected them

Even if a user were to browse the subdomain/webservice in the browser by putting the link together with the folder username and password the browser, it doesn't server the PHP as is server sided script. It wont be able to see my username and database password, sql, or the name of the files I'm calling in by viewing source

I have my functions in a file with no file name and an extension that I have made up this is the purpose of the .anyext (htaccess treats this the same and protects it, but because its an extension that I made up it makes it harder to guess, and generally invisible)

indexes have been switched off so general browsing is not allowed on my webservice

OK so it took me two days to come up with this solution. I hope that my idea will help save someone a lot of time!

Bless You :o)

Andi Lee Davis


问:
UITableView - Scroll to bottom before viewDidAppear
In case it's not obvious by the title, what I want should be simple, for the tableView to start scrolled all the way to the bottom when the users first sees it (before he sees it, and without animations).

So, I know that this has been answered a few times, but none of those solutions seem to work right now.
To give some context, I'm using Swift, autolayout and latest version of iOS as of today.

Constraints

There are some things I need to support:

load it before user sees it (without animations, obviously).

dynamic cell heights, i.e., their height is determined by a UILabel (like a messaging app - using autolayout in storyboard).

My UITableView is inside a UIScrollView (UIScrollView scrolls horizontally and UITableView scrolls vertically).

The UITableView is in a childViewController, i.e., I add it to the main UIViewController (which, for some reason, makes viewWillAppear not get called - viewDidAppear is still called).

I'll make a summary of what I tried:

As for implementations:

tableView.contentOffset = CGPoint(x: 0, y: CGFloat.max

tableView.scrollToRowAtIndexPath(indexPathForLastItem, atScrollPosition: .Bottom, animated: false)

```<code>
    var contentOffset = tableView.contentOffset
    contentOffset.y = tableView.contentSize.height - tableView.bounds.size.height
    tableView.setContentOffset(contentOffset, animated: false)

</code>```

```<code>
    dispatch_async(dispatch_get_main_queue(), {
        // tried option 1., 2. and 3. here
    })

</code>```

As for places I've tried to call those implementations:

viewDidLoad

viewWillAppear

viewDidLayoutSubviews (only the first time it's called, I use a property to track that)

viewDidAppear (even though this wouldn't give me what I want)

On my model's didSet

Before those I always called tableView.reloadData

What I DON'T want to do:

tableView.transform = CGAffineTransformMakeScale(1, -1)

+

cell.transform = CGAffineTransformMakeScale(1, -1)

(I'm assuming that if you think of suggesting this solution, it's because you know the hack I'm talking about. If you don't, then you won't be suggesting this, so you don't need to understand how it works)

One of the reasons why I don't want this one is because now I can't scroll to the top...

Problems I've noticed:

The tableView's contentSize (as a UIScrollView subclass) changes when you scroll for the first time after it appeared. Yes, I meant contentSize, not contentOffset, and it changes more than once while you scroll. After you've scrolled through the entire tableView once, it doesn't change anymore.

Some people are saying it works for fewer cells (and to be honest, it was working for me at some point), so try it with at least 20 items.

viewWillAppear doesn't get called, but viewDidAppear does.

Any solutions (except for the one I mentioned I don't want) would be very much appreciated. Even hacky ones, as long as they don't break other stuff.

Just as a side note, scrollToRowAtIndexPath... does not scale, i.e., it is too slow if you have, say, 2000 items. So Ideally I'd prefer a solution that scales.

EDITS AFTER ANSWERS:

After @bsmith11's answer I tried:

```<code>private var called = false
override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    if !called {
        dispatch_async(dispatch_get_main_queue(), {
            self.tableView.setContentOffset(CGPoint(x: 0, y: self.tableView.bounds.height), animated: false)
        })
        called = true
    }
}
</code>```

And it didn't work.

答: I think that calling [table setContentOffset:CGPointMake(0, CGFLOAT_MAX)] and table.estimatedRowHeight = 50(change your value); in ViewDidLoad is what you need.

Body:
In case it's not obvious by the title, what I want should be simple, for the tableView to start scrolled all the way to the bottom when the users first sees it (before he sees it, and without animations).

So, I know that this has been answered a few times, but none of those solutions seem to work right now.
To give some context, I'm using Swift, autolayout and latest version of iOS as of today.

Constraints

There are some things I need to support:

load it before user sees it (without animations, obviously).

dynamic cell heights, i.e., their height is determined by a UILabel (like a messaging app - using autolayout in storyboard).

My UITableView is inside a UIScrollView (UIScrollView scrolls horizontally and UITableView scrolls vertically).

The UITableView is in a childViewController, i.e., I add it to the main UIViewController (which, for some reason, makes viewWillAppear not get called - viewDidAppear is still called).

I'll make a summary of what I tried:

As for implementations:

tableView.contentOffset = CGPoint(x: 0, y: CGFloat.max

tableView.scrollToRowAtIndexPath(indexPathForLastItem, atScrollPosition: .Bottom, animated: false)

    var contentOffset = tableView.contentOffset
    contentOffset.y = tableView.contentSize.height - tableView.bounds.size.height
    tableView.setContentOffset(contentOffset, animated: false)

    dispatch_async(dispatch_get_main_queue(), {
        // tried option 1., 2. and 3. here
    })

As for places I've tried to call those implementations:

viewDidLoad

viewWillAppear

viewDidLayoutSubviews (only the first time it's called, I use a property to track that)

viewDidAppear (even though this wouldn't give me what I want)

On my model's didSet

Before those I always called tableView.reloadData

What I DON'T want to do:

tableView.transform = CGAffineTransformMakeScale(1, -1)

+

cell.transform = CGAffineTransformMakeScale(1, -1)

(I'm assuming that if you think of suggesting this solution, it's because you know the hack I'm talking about. If you don't, then you won't be suggesting this, so you don't need to understand how it works)

One of the reasons why I don't want this one is because now I can't scroll to the top...

Problems I've noticed:

The tableView's contentSize (as a UIScrollView subclass) changes when you scroll for the first time after it appeared. Yes, I meant contentSize, not contentOffset, and it changes more than once while you scroll. After you've scrolled through the entire tableView once, it doesn't change anymore.

Some people are saying it works for fewer cells (and to be honest, it was working for me at some point), so try it with at least 20 items.

viewWillAppear doesn't get called, but viewDidAppear does.

Any solutions (except for the one I mentioned I don't want) would be very much appreciated. Even hacky ones, as long as they don't break other stuff.

Just as a side note, scrollToRowAtIndexPath... does not scale, i.e., it is too slow if you have, say, 2000 items. So Ideally I'd prefer a solution that scales.

EDITS AFTER ANSWERS:

After @bsmith11's answer I tried:

private var called = false
override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    if !called {
        dispatch_async(dispatch_get_main_queue(), {
            self.tableView.setContentOffset(CGPoint(x: 0, y: self.tableView.bounds.height), animated: false)
        })
        called = true
    }
}

And it didn't work.


问:
How do you create a custom user role in Azure AD?
Found this article on how to setup roles but it uses the legacy azure portal to accomplish this.

How do you create user roles in the latest Azure portal?

How do you assign multiple roles to a user afterwards?

答:
According to article your referred, I assume that you want to assign users and groups to application roles.

You can achieve this from new portal. But Only Azure AD Premium or Enterprise mobility suite support assigning with roles. You can take following steps:

Go to Azure portal > Azure Active Directory > Enterprise applications > All applications > Select your application > Users and Groups

Now, you can assign roles through adding users(My Azure AD is not basic):


问:
BeautifulSoup - findAll() doesn't return all descendants
I'm trying to get all the posts from a forum thread. Everything works fine for most posts, but whenever a post is a reply and it contains the original message, I can't get the reply. I found out that the soup.findAll(...) doesn't return all the children from the html source (see pictures below). From the html in picture 2 I get

```<code><b>Citation :</b><br/>
</code>```

where I should also get what's below (in the 'p' tag: si-si je suis là...). Actually I only want the stuff that's in this 'p' tag.

```<code>import requests
from bs4 import BeautifulSoup as bsoup

site_source = requests.get("http://forum.doctissimo.fr/sante/audition/acouphene-mouvement-secouant-sujet_152572_1.htm").content
soup = bsoup(site_source, "html.parser")

# Get text from forum posts

post_boxes = soup.findAll("td", class_="messCase2", style="border-bottom:0")

for post_box in post_boxes:
    message = post_box.find("div", itemprop="text")
    for line in message:
       print(line)
</code>```

Picture: new post (the parsing works)

Picture: reply post

答:
Use .descendants to recursively access all the children in a Tag object.

There's a bigger problem, though.  The link you provided does not give the same HTML structure as the "reply post" screenshot.  In the actual link, the additional
 tag with the content you want is not part of the
 with id=77714.  Here's a screenshot from Chrome's Inspect tab for this page, for the content you're interested in:

That
 appears not to be closed properly, but it is nested within a
 tag, which is closed before the next
.  (This is one good reason not to rely on screenshots when posting a question.)

Your browser may have imputed the dangling
 as

, but BeautifulSoup is respecting the apparent tag closure - that's why you don't see your target content in the children set.

Here's what your
 actually contains:

```<code>import requests
from bs4 import BeautifulSoup as bsoup

site_source = requests.get("http://forum.doctissimo.fr/sante/audition/acouphene-mouvement-secouant-sujet_152572_1.htm").content
soup = bsoup(site_source, "html.parser")

div = soup.find_all("div", id="para77714")

for tag in div:
    for subtag in tag.descendants:
        print(subtag)
</code>```

Output:

```<code><div itemprop="text"><b>Citation :</b><br/></div>
<b>Citation :</b>
Citation :
<br/>
</code>```

The main problem is that the HTML on this page is a mess.  BeautifulSoup quite rightly can't make heads or tails of it.  For example, it looks like your target content is wrapped in a
 tag, but because things are all messed up with bad closures earlier on, there isn't actually a valid tag that wraps your content.

You can see this if you iterate down through the tag hierarchy a bit past the starting
:

```<code>ct = 0
for tag in div.find_all_next():
    ct+=1
    if (ct < 15) & (ct > 12):
        for subtag in tag:
            print(f"tag name: {subtag.name}")
            print(f"{subtag.string}\n")

tag name: None
Afficher moins

tag name: br
None

tag name: br
None

tag name: br
None

tag name: None
si-si je suis là   <--- this is what you want, but it is not in a valid <p> tag

tag name: img
None
# ...
</code>```

TL;DR - BeautifulSoup is working just fine, it's this web page that's busted.

Body:
I'm trying to get all the posts from a forum thread. Everything works fine for most posts, but whenever a post is a reply and it contains the original message, I can't get the reply. I found out that the soup.findAll(...) doesn't return all the children from the html source (see pictures below). From the html in picture 2 I get

Citation :

where I should also get what's below (in the 'p' tag: si-si je suis là...). Actually I only want the stuff that's in this 'p' tag.

import requests
from bs4 import BeautifulSoup as bsoup

site_source = requests.get("http://forum.doctissimo.fr/sante/audition/acouphene-mouvement-secouant-sujet_152572_1.htm").content
soup = bsoup(site_source, "html.parser")

# Get text from forum posts

post_boxes = soup.findAll("td", class_="messCase2", style="border-bottom:0")

for post_box in post_boxes:
    message = post_box.find("div", itemprop="text")
    for line in message:
       print(line)

Picture: new post (the parsing works)

Picture: reply post

Body:
Use .descendants to recursively access all the children in a Tag object.

There's a bigger problem, though.  The link you provided does not give the same HTML structure as the "reply post" screenshot.  In the actual link, the additional <p> tag with the content you want is not part of the <div> with id=77714.  Here's a screenshot from Chrome's Inspect tab for this page, for the content you're interested in:

That <div> appears not to be closed properly, but it is nested within a <p> tag, which is closed before the next <div class="container">.  (This is one good reason not to rely on screenshots when posting a question.)

Your browser may have imputed the dangling </p> as <p></p>, but BeautifulSoup is respecting the apparent tag closure - that's why you don't see your target content in the children set.

Here's what your <div> actually contains:

import requests
from bs4 import BeautifulSoup as bsoup

site_source = requests.get("http://forum.doctissimo.fr/sante/audition/acouphene-mouvement-secouant-sujet_152572_1.htm").content
soup = bsoup(site_source, "html.parser")

div = soup.find_all("div", id="para77714")

for tag in div:
    for subtag in tag.descendants:
        print(subtag)

Output:

<div itemprop="text"><b>Citation :</b><br/></div>
<b>Citation :</b>
Citation :
<br/>

The main problem is that the HTML on this page is a mess.  BeautifulSoup quite rightly can't make heads or tails of it.  For example, it looks like your target content is wrapped in a <p> tag, but because things are all messed up with bad closures earlier on, there isn't actually a valid tag that wraps your content.

You can see this if you iterate down through the tag hierarchy a bit past the starting <div>:

ct = 0
for tag in div.find_all_next():
    ct+=1
    if (ct < 15) & (ct > 12):
        for subtag in tag:
            print(f"tag name: {subtag.name}")
            print(f"{subtag.string}\n")

tag name: None
Afficher moins

tag name: br
None

tag name: br
None

tag name: br
None

tag name: None
si-si je suis là   <--- this is what you want, but it is not in a valid <p> tag

tag name: img
None
# ...

TL;DR - BeautifulSoup is working just fine, it's this web page that's busted.


问:
C++ loop stack allocation
While doing an assignment for a course and learning C++ while doing it, I was reading up on when to use stack allocation and dynamic allocation. I'm aware that in a lot of cases it is easier and better to use stack allocation. But there is a simple situation I'm puzzeled about.

Lets say you have a for loop:

```<code>for(int i = 0; i < 10; i++)
{
   MyObject obj(file);
   obj.doSomething();
}
</code>```

Now the problem is that if the Object contains state, it keeps it state (stays the same object) while iterating through the iterations from 1 til 10. Maybe coming from a Java/C# background gets me on the wrong path. But I only see two ways of solving this:

Using dynamic memory.

Not giving file to the constructor but instead to the method doSomething(file) but this isn't very nice if you have more than one method manipulating the file object e.g. doSomethingElse(file).

So what do you guys do in such a situation, or do you never get yourself in such a situation at all?

Update:
Turns out i misunderstood and it is working as expected. Check the awnsers below! Thanks everyone

答:
obj gets deallocated at the end of every iteration---its destructor is called ten times as well. As long as the class's destructor properly deletes anything created by the constructor, you'll be fine.

On an efficiency note, you might just want to declare obj once before entering the loop.

Title: C++ loop stack allocation

Body:
While doing an assignment for a course and learning C++ while doing it, I was reading up on when to use stack allocation and dynamic allocation. I'm aware that in a lot of cases it is easier and better to use stack allocation. But there is a simple situation I'm puzzeled about.

Lets say you have a for loop:

for(int i = 0; i < 10; i++)
{
   MyObject obj(file);
   obj.doSomething();
}

Now the problem is that if the Object contains state, it keeps it state (stays the same object) while iterating through the iterations from 1 til 10. Maybe coming from a Java/C# background gets me on the wrong path. But I only see two ways of solving this:

Using dynamic memory.

Not giving file to the constructor but instead to the method doSomething(file) but this isn't very nice if you have more than one method manipulating the file object e.g. doSomethingElse(file).

So what do you guys do in such a situation, or do you never get yourself in such a situation at all?

Update:
Turns out i misunderstood and it is working as expected. Check the awnsers below! Thanks everyone


问:
can we make JavaDoc tool to parse comments inside methods?
I tried googling this question a lot but could not find the answer to exact question. I also read this question: Does the javadoc tool recognize comments inside methods?

So my question is kind-of a follow-up to this. I know that default JavaDoc tool would simple ignore any javadoc comments inside methods, but can we somehow make it read those comments too and may be try handling them on our customer doclets/ taglets? I tried writing my own doclet and taglet as well but since JavaDoc would completely ignore the comments inside methods, I could not succeed.

For example, suppose I have the following code:

```<code>public void methodX() {
        /**
         * @MyTag This is a sample javadoc comment with custom tag
         */
    }
</code>```

Is there a way to make JavaDoc not ignore the comment inside methodX? I could handle the response in a custom doclet if javadoc could parse and provide the comment text.

Reason to try this:
I guess it would be helpful to know why I'm looking for such a requirement. Basically we have a lot of configuration driven coding where these configurations are stored in DB (So that we could simply change the configuration at runtime without having to go through the BRD process again). So we are planning to document those configurations at a central place. And instead of keeping the code and document separate, we also think it would be wise to keep the documentation closer to code itself so that any code updations could also possibly update the documentation. Publishing to central place can be taken care of via doclets/ taglets but only if JavaDoc could read those comments inside methods.

So is there a possibility of making JavaDoc tool read through comments inside methods as well? Or else we would have to try and write our own comments parser similar to JavaDoc for this.

答:
So I did a little digging around and seeing that no-one has answered the question, it seems people are (maybe) not sure about the possibility.

Based on what I found, it doesn't seem feasible to have the JavaDoc tool parse the comments inside methods. The reason being, JavaDoc doesn't even get those comment texts to parse. Now, what I mean here is, JavaDoc relies on the JDK compiler (the API of-course) to have the Java code converted into tokens and trees and then gets all the comments from there. So unless you are okay modifying the JDK compiler itself to make it "Do Not Ignore" the comments inside methods, you can't make JavaDoc to read comments inside method.

Oh! And for the part of solving our problem, we're, for now, restricting to define JavaDocs with custom Tags for the constants we used and have the comments processed via a Custom Taglet to handle the new Tags.

Body:
I tried googling this question a lot but could not find the answer to exact question. I also read this question: Does the javadoc tool recognize comments inside methods?

So my question is kind-of a follow-up to this. I know that default JavaDoc tool would simple ignore any javadoc comments inside methods, but can we somehow make it read those comments too and may be try handling them on our customer doclets/ taglets? I tried writing my own doclet and taglet as well but since JavaDoc would completely ignore the comments inside methods, I could not succeed.

For example, suppose I have the following code:

public void methodX() {
        /**
         * @MyTag This is a sample javadoc comment with custom tag
         */
    }

Is there a way to make JavaDoc not ignore the comment inside methodX? I could handle the response in a custom doclet if javadoc could parse and provide the comment text.

Reason to try this:
I guess it would be helpful to know why I'm looking for such a requirement. Basically we have a lot of configuration driven coding where these configurations are stored in DB (So that we could simply change the configuration at runtime without having to go through the BRD process again). So we are planning to document those configurations at a central place. And instead of keeping the code and document separate, we also think it would be wise to keep the documentation closer to code itself so that any code updations could also possibly update the documentation. Publishing to central place can be taken care of via doclets/ taglets but only if JavaDoc could read those comments inside methods.

So is there a possibility of making JavaDoc tool read through comments inside methods as well? Or else we would have to try and write our own comments parser similar to JavaDoc for this.


问:
Using interp1 in R
I am using interp1 from the 'pracma' package (v 2.0.7) in R version 3.3.3 on Windows 10 x64.

I want NA's returned when xi is outside the range of x. This is a basic question, but I've tried looking online and can't find exactly what I am looking for.

interp1 use to have this feature ('extrap')? Doc for version 0.7.

```<code>#library(pracma)
x  = c(2,4,5,6,8,9)
y  = c(0.3,0.5,0.4,0.7,0.3,0.2)
xi = c(1,2,4,6,8)
yi = interp1(x,y,xi,method = "linear")

# my error message:
Error in interp1(x, y, xi, method = "linear") :
  Points 'xi' outside of range of argument 'x'.
</code>```

Instead of an error, how can I retrieve yi so that it just says NA on the end where xi is outside the range of x?

For instance, when I do this same code in MatLab, with it's interp1 function. I get an extrapolation.

```<code>yi = interp1(x,y,xi,'linear','extrap')
yi = 0.2  0.3  0.5  0.7  0.3
</code>```

And when I remove the 'extrap' clause, I get an NaN:

```<code>yi = NaN  0.3  0.5  0.7  0.3
</code>```

Is there a way to achieve the equivalent in R without rewriting the interp1 function?

答:
As ?interp1 will tell you (emphasis mine):

xi: Numeric vector; points at which to compute the interpolation;
            all points must lie between ‘min(x)’ and ‘max(x)’.

So you will have to code something for yourself, if xi lies outside that range.

Here is an example, where I define a short new function interp2 that gives NA's for xi values outside of range(x).

```<code># Your sample data
x <- c(2,4,5,6,8,9);
y <- c(0.3,0.5,0.4,0.7,0.3,0.2);
xi <- c(1,2,4,6,8);

# New function interp2
interp2 <- function(x, y, xi = x, ...) {
    yi <- rep(NA, length(xi));
    sel <- which(xi >= range(x)[1] & xi <= range(x)[2]);
    yi[sel] <- interp1(x = x, y = y, xi = xi[sel], ...);
    return(yi);
}

yi <- interp2(x, y, xi, method = "linear");
#[1]  NA 0.3 0.5 0.7 0.3
</code>```

A more general comment

If you take a look at the sample data, any interpolation results are probably to be taken with a large grain of salt. More generally, a more robust approach would be to fit a linear model, which you can then use to get predictions for any new values x (including uncertainties)

```<code>ynew <- predict(lm(y ~ x), data.frame(x = xi));
#    1     2     3     4     5
#0.484 0.466 0.430 0.394 0.358
</code>```

For your sample data, the linear fit is obviously not very good.

Alternatively, you can also get predictions based on a local polynomial regression fit (LOESS). This will give you similar results to pracma::interp1 (ignoring the warnings which stem from too few data points).

```<code>ynew <- predict(loess(y ~ x), data.frame(x = xi));
#  1   2   3   4   5
# NA 0.3 0.5 0.7 0.3
</code>```

Title: Using interp1 in R

Body:
I am using interp1 from the 'pracma' package (v 2.0.7) in R version 3.3.3 on Windows 10 x64.

I want NA's returned when xi is outside the range of x. This is a basic question, but I've tried looking online and can't find exactly what I am looking for.

interp1 use to have this feature ('extrap')? Doc for version 0.7.

#library(pracma)
x  = c(2,4,5,6,8,9)
y  = c(0.3,0.5,0.4,0.7,0.3,0.2)
xi = c(1,2,4,6,8)
yi = interp1(x,y,xi,method = "linear")

# my error message:
Error in interp1(x, y, xi, method = "linear") :
  Points 'xi' outside of range of argument 'x'.

Instead of an error, how can I retrieve yi so that it just says NA on the end where xi is outside the range of x?

For instance, when I do this same code in MatLab, with it's interp1 function. I get an extrapolation.

yi = interp1(x,y,xi,'linear','extrap')
yi = 0.2  0.3  0.5  0.7  0.3

And when I remove the 'extrap' clause, I get an NaN:

yi = NaN  0.3  0.5  0.7  0.3

Is there a way to achieve the equivalent in R without rewriting the interp1 function?

Body:
As ?interp1 will tell you (emphasis mine):

xi: Numeric vector; points at which to compute the interpolation;
            all points must lie between ‘min(x)’ and ‘max(x)’.

So you will have to code something for yourself, if xi lies outside that range.

Here is an example, where I define a short new function interp2 that gives NA's for xi values outside of range(x).

# Your sample data
x <- c(2,4,5,6,8,9);
y <- c(0.3,0.5,0.4,0.7,0.3,0.2);
xi <- c(1,2,4,6,8);

# New function interp2
interp2 <- function(x, y, xi = x, ...) {
    yi <- rep(NA, length(xi));
    sel <- which(xi >= range(x)[1] & xi <= range(x)[2]);
    yi[sel] <- interp1(x = x, y = y, xi = xi[sel], ...);
    return(yi);
}

yi <- interp2(x, y, xi, method = "linear");
#[1]  NA 0.3 0.5 0.7 0.3

A more general comment

If you take a look at the sample data, any interpolation results are probably to be taken with a large grain of salt. More generally, a more robust approach would be to fit a linear model, which you can then use to get predictions for any new values x (including uncertainties)

ynew <- predict(lm(y ~ x), data.frame(x = xi));
#    1     2     3     4     5
#0.484 0.466 0.430 0.394 0.358

For your sample data, the linear fit is obviously not very good.

Alternatively, you can also get predictions based on a local polynomial regression fit (LOESS). This will give you similar results to pracma::interp1 (ignoring the warnings which stem from too few data points).

ynew <- predict(loess(y ~ x), data.frame(x = xi));
#  1   2   3   4   5
# NA 0.3 0.5 0.7 0.3


问:
Boundary assignment in openFOAM
I created the mesh shown in the image below using snappyHexMesh.
I have assigned boundaries in blockMesh, but they have been removed after running snappy. My question is how to create boundaries like inlet/outlet to the mesh shown in the image. Thank you.

答: you don't specify the boundary condition on the mesh. In meshing you only specify the name of the faces. For boundary conditions than go to folder 0 and you specify everything in there (U, p, T)</p>

Title: Boundary assignment in openFOAM


问:
is.object and the S3 class system
Using the class function allows us to determine the class of an object:

```<code>> x = 5
> class(x)
[1] "numeric"
</code>```

I also understand that we can use the is.object command to determine if an object has a class. However some object types are implicit, that is

```<code>> is.object(x)
[1] FALSE
</code>```

Would it be correct to state that all variables in R are objects and is.object is a test for non-implicit classes only?

Also, how do types fit into this. Naively, I thought that the following piece of code would produce an error:

```<code>> x = 5
> class(x) = "fake"
> x = X + 1
> x + 1
[1] 6
attr(,"class")
[1] "fake"
</code>```

But x still has type "double", still everything still works. Can types be thought of as a superclass that all other objects inherit from?

答:
typeof returns the type of internal C representation, and it is not used for method dispatch. So strictly speaking you can not think of types as "superclasses".

There are instead basic classes (numeric, character, list, function etc) which roughly correspond to the names
returned by typeof, but not always (for example type double is of class numeric, special and closure are of class
function, and class data.frame is of type list!).

With S3 and S4 systems you can build non trivial classes using basic classes (but not necessary extending one of those!! example: setClass("foo", list(a="numeric",b="character") does not extend any of the basic classes).

For objects from these basic classes is.object returns FALSE. As its documentation says, this function provides
a very fast way to check if the object is of user build S3 or S4 class (i.e. not one of basic classes).

After casting x as "fake" your object is formally not of "numeric" class:

```<code>is(x, "numeric")
#FALSE
</code>```

but it is interpretable as basic "numeric" object:

```<code>is.numeric(x)
#TRUE
</code>```

And this is why + works here. So, internally, as @Richie already said the default method interprets x as of
numeric basic class.

This conceptual mess is because of S3 informal treatment of classes. Use S4 instead.

correspondence between typeof(.) and basic class(.):

```<code>                              typeof(.)  class(.)
NULL                          "NULL"     "NULL"
1                             "double"   "numeric"
1:1                           "integer"  "integer"
1i                            "complex"  "complex"
list(1)                       "list"     "list"
data.frame(x=1)               "list"     "data.frame"
pairlist(pi)                  "pairlist" "pairlist"
c                             "special"  "function"
lm                            "closure"  "function"
formals(lm)[[1]]              "symbol"   "name"
formals(lm)[[2]]              "symbol"   "name"
y~x                           "language" "formula"
expression((1))[[1]]          "language" "("
(y~x)[[1]]                    "symbol"   "name"
expression(x <- pi)[[1]][[1]] "symbol"   "name"
</code>```

Title: is.object and the S3 class system

Body:
Using the class function allows us to determine the class of an object:

> x = 5
> class(x)
[1] "numeric"

I also understand that we can use the is.object command to determine if an object has a class. However some object types are implicit, that is

> is.object(x)
[1] FALSE

Would it be correct to state that all variables in R are objects and is.object is a test for non-implicit classes only?

Also, how do types fit into this. Naively, I thought that the following piece of code would produce an error:

> x = 5
> class(x) = "fake"
> x = X + 1
> x + 1
[1] 6
attr(,"class")
[1] "fake"

But x still has type "double", still everything still works. Can types be thought of as a superclass that all other objects inherit from?

Body:
typeof returns the type of internal C representation, and it is not used for method dispatch. So strictly speaking you can not think of types as "superclasses".

There are instead basic classes (numeric, character, list, function etc) which roughly correspond to the names
returned by typeof, but not always (for example type double is of class numeric, special and closure are of class
function, and class data.frame is of type list!).

With S3 and S4 systems you can build non trivial classes using basic classes (but not necessary extending one of those!! example: setClass("foo", list(a="numeric",b="character") does not extend any of the basic classes).

For objects from these basic classes is.object returns FALSE. As its documentation says, this function provides
a very fast way to check if the object is of user build S3 or S4 class (i.e. not one of basic classes).

After casting x as "fake" your object is formally not of "numeric" class:

is(x, "numeric")
#FALSE

but it is interpretable as basic "numeric" object:

is.numeric(x)
#TRUE

And this is why + works here. So, internally, as @Richie already said the default method interprets x as of
numeric basic class.

This conceptual mess is because of S3 informal treatment of classes. Use S4 instead.

correspondence between typeof(.) and basic class(.):

                              typeof(.)  class(.)
NULL                          "NULL"     "NULL"
1                             "double"   "numeric"
1:1                           "integer"  "integer"
1i                            "complex"  "complex"
list(1)                       "list"     "list"
data.frame(x=1)               "list"     "data.frame"
pairlist(pi)                  "pairlist" "pairlist"
c                             "special"  "function"
lm                            "closure"  "function"
formals(lm)[[1]]              "symbol"   "name"
formals(lm)[[2]]              "symbol"   "name"
y~x                           "language" "formula"
expression((1))[[1]]          "language" "("
(y~x)[[1]]                    "symbol"   "name"
expression(x <- pi)[[1]][[1]] "symbol"   "name"


问:
ng is not recognised as an internal or external command. Jenkins + Angular CLI
I am trying to setup Jenkins for an Angular CLI project. I have installed node and Angular Cli on the Jenkins server under a specific user account.
if I open a command prompt on the server an execute the following commands to verify they are installed properly, this is the result:

I have configured the project with Jenkins, and i created two build steps two execute two bat files.

One runs: npm install

and the second one runs: ng build --prod

Then I build Jenkins, it runs the npm install but it fails running ng build --prod because it says " 'ng' is not recognised as an internal or external command".

Am I doing something wrong? Is there another way to probably use the angular cli on the node_modules folder, So it does not need to use the angular cli installed on the server. It seems like Angular CLI is installed only for my user on the server but not for the user Jenkins use to build.

PS: I installed Angular CLI globally using:

npm i -g @angular/cli

答:
No need to install angular cli on server, just run

```<code>npm run ng -- build
</code>```

That will run the local version from your project devDependencies

This way you can pass any flag to your local cli npm run ng -- test, npm run ng -- lint, etc

You can pass additional flags to ng just like that

  run ng -- build --prod

More details at https://docs.npmjs.com/cli/run-script

Body:
No need to install angular cli on server, just run

npm run ng -- build

That will run the local version from your project devDependencies

This way you can pass any flag to your local cli npm run ng -- test, npm run ng -- lint, etc

You can pass additional flags to ng just like that

  run ng -- build --prod

More details at https://docs.npmjs.com/cli/run-script


问:
WKWebView inside UISplitViewController has unwanted horizontal rubber-band scroll behaviour
If I display an HTML document (that is not wider then the screen) in a WKWebView as full screen view on an iPad or iPhone, it scrolls as expected, vertically only, and not at all horizontally.

If the same WKWebView is presented inside the detail view of a UISplitViewController, it will have a strange rubber-band horizontal scrolling behaviour.  The document is displayed at the correct width, but you can pull the document out to the left and right. After you let go, it snaps back.

This is a usability problem for a web system I am trying to display inside a split view controller.

Does anybody know why this is the case, and is it possible to cause WKWebView to use the normal scrolling behaviour?

答:
This is because the parent UISplitViewController is reporting incorrect dimensions to the WebView - it is (probably) failing to subtract the 0.5 points for the divider line from the detail view's frame.

There doesn't appear to be a solution.

A workaround is to add an 0.5 point contentInset to the left side of the WKWebView's ScrollView.

Note this solution was developed for iOS11.  Future versions of iOS may fix this miscalculation.  Will probably file a bug with Apple.


问:
How to apply watershed on grayscale image with opencv and python?
Based on a solution that I read at How to define the markers for Watershed in OpenCV?, I am trying apply watershed to grayscale data (not very visible but not all black), extracted from netcdf (precipitation data).

Here is a black and white version of the data (threshold at 0) so that you can see more easily, and the markers I want to use to define the different basins (basically just another threshold where precipitation is more intense).

The code I'm running is as follows:

```<code>import os,sys,string
from netCDF4 import Dataset as nc
import cv2
import numpy as np
import matplotlib.pyplot as mpl
import scipy.ndimage as ndimage
import scipy.spatial as spatial
from skimage import filter
from skimage.morphology import watershed
from scipy import ndimage

filename=["Cmorph-1999_01_03.nc"]

nc_data=nc(filename[0])
data=nc_data.variables["CMORPH"][23,0:250,250:750]
new_data=np.flipud(data)
ma_data=np.ma.masked_where(new_data<=0,new_data)
ma_conv=np.ma.masked_where(new_data<=2,new_data)

## Borders
tmp_data=ma_data.filled(0)
tmp_data[np.where(tmp_data!=0)]=255
bw_data=tmp_data.astype(np.uint8)
border = cv2.dilate(bw_data, None, iterations=5)
border = border - cv2.erode(border, None)

## Markers
tmp_conv=ma_conv.filled(0)
tmp_conv[np.where(tmp_conv!=0)]=255
bw_conv=tmp_conv.astype(np.uint8)
lbl, ncc = ndimage.label(bw_conv)
lbl = lbl * (255/ncc)
lbl[border == 255] = 255
lbl = lbl.astype(np.int32)

## Apply watershed
cv2.watershed(ma_data, lbl)

lbl[lbl == -1] = 0
lbl = lbl.astype(np.uint8)
result = 255 - lbl
</code>```

I have the following error for the watershed in opencv-2.4.11/modules/imgproc/src/segmentation.cpp:

```<code>error: (-210) Only 8-bit, 3-channel input images are supported in function cvWatershed
</code>```

For what I saw on the internet, this is due to the fact that the grayscale data is a 2D image and watershed needs a 3D image (from RGB). Indeed, I tried the script with a jpg image and I worked perfectly.
This problem is mentionned here but the answer given was finally rejected. And I can't find any more recent link answering the question.

To try to solve this, I created a 3D array from the 2D new_data:

```<code>new_data = new_data[..., np.newaxis]
test=np.append(new_data, new_data, axis=2)
test=np.append(new_data, test, axis=2)
</code>```

But, as expected, it didn't solve the problem (same error message).

I also tried to save the plot from matplotlib to get RGB data:

```<code>fig = mpl.figure()
fig.add_subplot(111)
fig.tight_layout(pad=0)
mpl.contourf(ma_data,levels=np.arange(0,255.1,0.1))
fig.canvas.draw()
test_data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
test_data = test_data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
</code>```

But the size of the test_data created is different from ma_data (+ I can't get rid of the labels).

So, I am stuck here. Ideally, I want to apply the watershed on the 2D grayscale image directly and/or limit the number of operations as much as possible.

答:
As yapws87 mentioned, there was indeed a problem with the format I was presenting to the watershed function.
Doing try_data=ma_data.astype(np.uint8) removed the error message.

Here is a minimal example that works now:

```<code>import os,sys
from netCDF4 import Dataset as nc
import cv2
import numpy as np
import scipy.ndimage as ndimage
from skimage.morphology import watershed
from scipy import ndimage

basename="/home/dcop696/Data/CMORPH/precip/CMORPH_V1.0/CRT/8km-30min/1999/"
filename=["Cmorph-1999_01_03.nc"]
fileslm=["/home/dcop696/Data/LSM/Cmorph_slm_8km.nc"]

nc_data=nc(basename+filename[0])
data=nc_data.variables["CMORPH"][23,0:250,250:750]
new_data=np.flipud(data)
ma_data=np.ma.masked_where(new_data<=0,new_data)
try_data=ma_data.astype(np.uint8)

## Building threshold
tmp_data=ma_data.filled(0)
tmp_data[np.where(tmp_data!=0)]=255
bw_data=tmp_data.astype(np.uint8)

## Building markers
ma_conv=np.ma.masked_where(new_data<=2,new_data)
tmp_conv=ma_conv.filled(0)
tmp_conv[np.where(tmp_conv!=0)]=255
bw_conv=tmp_conv.astype(np.uint8)
markers = ndimage.label(bw_conv)[0]

## Watershed
labels = watershed(-try_data, markers, mask=bw_data)
</code>```

Body:
Based on a solution that I read at How to define the markers for Watershed in OpenCV?, I am trying apply watershed to grayscale data (not very visible but not all black), extracted from netcdf (precipitation data).

Here is a black and white version of the data (threshold at 0) so that you can see more easily, and the markers I want to use to define the different basins (basically just another threshold where precipitation is more intense).

The code I'm running is as follows:

import os,sys,string
from netCDF4 import Dataset as nc
import cv2
import numpy as np
import matplotlib.pyplot as mpl
import scipy.ndimage as ndimage
import scipy.spatial as spatial
from skimage import filter
from skimage.morphology import watershed
from scipy import ndimage

filename=["Cmorph-1999_01_03.nc"]

nc_data=nc(filename[0])
data=nc_data.variables["CMORPH"][23,0:250,250:750]
new_data=np.flipud(data)
ma_data=np.ma.masked_where(new_data<=0,new_data)
ma_conv=np.ma.masked_where(new_data<=2,new_data)

## Borders
tmp_data=ma_data.filled(0)
tmp_data[np.where(tmp_data!=0)]=255
bw_data=tmp_data.astype(np.uint8)
border = cv2.dilate(bw_data, None, iterations=5)
border = border - cv2.erode(border, None)

## Markers
tmp_conv=ma_conv.filled(0)
tmp_conv[np.where(tmp_conv!=0)]=255
bw_conv=tmp_conv.astype(np.uint8)
lbl, ncc = ndimage.label(bw_conv)
lbl = lbl * (255/ncc)
lbl[border == 255] = 255
lbl = lbl.astype(np.int32)

## Apply watershed
cv2.watershed(ma_data, lbl)

lbl[lbl == -1] = 0
lbl = lbl.astype(np.uint8)
result = 255 - lbl

I have the following error for the watershed in opencv-2.4.11/modules/imgproc/src/segmentation.cpp:

error: (-210) Only 8-bit, 3-channel input images are supported in function cvWatershed

For what I saw on the internet, this is due to the fact that the grayscale data is a 2D image and watershed needs a 3D image (from RGB). Indeed, I tried the script with a jpg image and I worked perfectly.
This problem is mentionned here but the answer given was finally rejected. And I can't find any more recent link answering the question.

To try to solve this, I created a 3D array from the 2D new_data:

new_data = new_data[..., np.newaxis]
test=np.append(new_data, new_data, axis=2)
test=np.append(new_data, test, axis=2)

But, as expected, it didn't solve the problem (same error message).

I also tried to save the plot from matplotlib to get RGB data:

fig = mpl.figure()
fig.add_subplot(111)
fig.tight_layout(pad=0)
mpl.contourf(ma_data,levels=np.arange(0,255.1,0.1))
fig.canvas.draw()
test_data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
test_data = test_data.reshape(fig.canvas.get_width_height()[::-1] + (3,))

But the size of the test_data created is different from ma_data (+ I can't get rid of the labels).

So, I am stuck here. Ideally, I want to apply the watershed on the 2D grayscale image directly and/or limit the number of operations as much as possible.

Body:
As yapws87 mentioned, there was indeed a problem with the format I was presenting to the watershed function.
Doing try_data=ma_data.astype(np.uint8) removed the error message.

Here is a minimal example that works now:

import os,sys
from netCDF4 import Dataset as nc
import cv2
import numpy as np
import scipy.ndimage as ndimage
from skimage.morphology import watershed
from scipy import ndimage

basename="/home/dcop696/Data/CMORPH/precip/CMORPH_V1.0/CRT/8km-30min/1999/"
filename=["Cmorph-1999_01_03.nc"]
fileslm=["/home/dcop696/Data/LSM/Cmorph_slm_8km.nc"]

nc_data=nc(basename+filename[0])
data=nc_data.variables["CMORPH"][23,0:250,250:750]
new_data=np.flipud(data)
ma_data=np.ma.masked_where(new_data<=0,new_data)
try_data=ma_data.astype(np.uint8)

## Building threshold
tmp_data=ma_data.filled(0)
tmp_data[np.where(tmp_data!=0)]=255
bw_data=tmp_data.astype(np.uint8)

## Building markers
ma_conv=np.ma.masked_where(new_data<=2,new_data)
tmp_conv=ma_conv.filled(0)
tmp_conv[np.where(tmp_conv!=0)]=255
bw_conv=tmp_conv.astype(np.uint8)
markers = ndimage.label(bw_conv)[0]

## Watershed
labels = watershed(-try_data, markers, mask=bw_data)


问:
Spring security application of antMatcher() vs. antMatchers()
Just want to see whether I'm interpreting the answer to this question the right way.

If we only need to secure one path like this:

```<code>http.antMatcher("/api/**").authorizeRequests()....
</code>```

Then use antMatcher().

If we need to secure multiple URL paths like this:

```<code>http
.authorizeRequests()
    .antMatchers("/high_level_url_A/sub_level_1").hasRole('USER')
    .antMatchers("/high_level_url_A/sub_level_2").hasRole('USER2')
    ...
</code>```

Then use antMatchers().

There are two answers in this question, but the example provided in each of them contradicts example given in the other.  The first answer says that the author does not need antMatcher() and the second says to always start with `antMatcher() IIUC.

答:
HttpSecurity.antMatcher() changes the default request matcher for the HttpSecurity instance to an AntPathRequestMatcher from AnyRequestMatcher. ExpressionUrlAuthorizationConfigurer.ExpressionInterceptUrlRegistry.antMatchers() is used for applying authorization rules to a subset of endpoints associated with the current HttpSecurity instance.

Example code:

```<code>http
    .antMatcher("/api/**")
    .httpBasic()
        .disable()
    .authorizeRequests()
        .antMatchers("/api/user/**", "/api/ticket/**", "/index")
            .hasRole("USER");
</code>```

In the example above, basic authorization is disabled for all endpoints matching /api/**. Additionally, endpoints matching /api/user/** or /api/ticket/** will require the request's Authentication to contain ROLE_USER. However, when a user attempts to access /index, they will be met with a basic auth prompt. Upon entering credentials, the user will be granted access to the endpoint regardless of whether or not the request's Authentication contains ROLE_USER. This is because .antMatcher("/api/**") is limiting the scope of the entire HttpSecurity instance to that specific AntMatcher.

The example below would ensure that the HttpSecurity's scope includes the three previous AntMatchers and nothing else:

```<code>http
    .requestMatchers()
        .antMatchers("/api/user/**", "/api/ticket/**", "/index")
        .and()
    .httpBasic()
        .disable()
    .authorizeRequests()
        .any()
            .hasRole("USER");
</code>```

EDIT
If you use #hasRole(), then your role should not start with "ROLE_" as this is automatically inserted.

Body:
Just want to see whether I'm interpreting the answer to this question the right way.

If we only need to secure one path like this:

http.antMatcher("/api/**").authorizeRequests()....

Then use antMatcher().

If we need to secure multiple URL paths like this:

http
.authorizeRequests()
    .antMatchers("/high_level_url_A/sub_level_1").hasRole('USER')
    .antMatchers("/high_level_url_A/sub_level_2").hasRole('USER2')
    ...

Then use antMatchers().

There are two answers in this question, but the example provided in each of them contradicts example given in the other.  The first answer says that the author does not need antMatcher() and the second says to always start with `antMatcher() IIUC.

Body:
HttpSecurity.antMatcher() changes the default request matcher for the HttpSecurity instance to an AntPathRequestMatcher from AnyRequestMatcher. ExpressionUrlAuthorizationConfigurer.ExpressionInterceptUrlRegistry.antMatchers() is used for applying authorization rules to a subset of endpoints associated with the current HttpSecurity instance.

Example code:

http
    .antMatcher("/api/**")
    .httpBasic()
        .disable()
    .authorizeRequests()
        .antMatchers("/api/user/**", "/api/ticket/**", "/index")
            .hasRole("USER");

In the example above, basic authorization is disabled for all endpoints matching /api/**. Additionally, endpoints matching /api/user/** or /api/ticket/** will require the request's Authentication to contain ROLE_USER. However, when a user attempts to access /index, they will be met with a basic auth prompt. Upon entering credentials, the user will be granted access to the endpoint regardless of whether or not the request's Authentication contains ROLE_USER. This is because .antMatcher("/api/**") is limiting the scope of the entire HttpSecurity instance to that specific AntMatcher.

The example below would ensure that the HttpSecurity's scope includes the three previous AntMatchers and nothing else:

http
    .requestMatchers()
        .antMatchers("/api/user/**", "/api/ticket/**", "/index")
        .and()
    .httpBasic()
        .disable()
    .authorizeRequests()
        .any()
            .hasRole("USER");

EDIT
If you use #hasRole(), then your role should not start with "ROLE_" as this is automatically inserted.


问:
Deleting rows in Pandas DataFrame based on values, from a specific range columns
I feel like this question has been asked but I can't find an exact answer.

I have a large dataset with dozens of columns. I am trying to delete rows from the dataset when the value in any column is greater than 5, but I don't want to search the first two columns (those first two columns can have values greater than 5). I understand that specific columns can be named eg.( df.colname > 5), but how do I do it for a range of columns?

like this:

df = df[df.columns[2:34] > 5]

Body:
By using .any from pandas and the data frame from Brad

df[~(df.iloc[:,2:]>5).any(1)]
Out[403]:
     a    b    c    d    e
0  0.0  0.0  0.0  0.0  0.0
2  0.0  0.0  0.0  0.0  0.0
3  0.0  0.0  0.0  0.0  0.0


问:
creating a color that will be shared by Mac and iOS code
I want to create my colors in a consistent way across both the Mac and iOS versions of my app.  According to CGColor.h, the function

```<code>CGColorCreate(CGColorSpaceRef space, const CGFloat components[])
</code>```

is available on both platforms.  But it seems annoyingly heavyweight.  Is there an easier way?

Thanks.

答:
Personally, I'd probably just go with:

```<code>#if TARGET_OS_IPHONE
#define HSBA(h,s,b,a) [UIColor colorWithHue: h saturation: s brightness: b alpha: a]
#else
#define HSBA(h,s,b,a) [NSColor colorWithHue: h saturation: s brightness: b alpha: a]
#endif

id tangerine = HSBA(0.084,1.0,1.0,1.0);
</code>```

Another choice is:

```<code>#if TARGET_OS_IPHONE
#define MYCOLOR UIColor
#else
#define MYCOLOR NSColor
#endif

MYCOLOR *tangerine = [MYCOLOR colorWithHue:0.084 saturation:1.0 brightness:1.0 alpha:1.0];
</code>```

Yet another choice would be creating your own function. :)

Body:
I want to create my colors in a consistent way across both the Mac and iOS versions of my app.  According to CGColor.h, the function

CGColorCreate(CGColorSpaceRef space, const CGFloat components[])

is available on both platforms.  But it seems annoyingly heavyweight.  Is there an easier way?

Thanks.

Body:
Personally, I'd probably just go with:

#if TARGET_OS_IPHONE
#define HSBA(h,s,b,a) [UIColor colorWithHue: h saturation: s brightness: b alpha: a]
#else
#define HSBA(h,s,b,a) [NSColor colorWithHue: h saturation: s brightness: b alpha: a]
#endif

id tangerine = HSBA(0.084,1.0,1.0,1.0);

Another choice is:

#if TARGET_OS_IPHONE
#define MYCOLOR UIColor
#else
#define MYCOLOR NSColor
#endif

MYCOLOR *tangerine = [MYCOLOR colorWithHue:0.084 saturation:1.0 brightness:1.0 alpha:1.0];

Yet another choice would be creating your own function. :)


问:
closure not performing as anticipated
Here's my code:

```<code>$array = ['foo' => 'bar', 'bis' => 'ter'];
$finalData=[];
$closure = function ($value, $key) use ($finalData) {
    $finalData[]=$value;
};
foreach ($array as $key => $value) {
    $closure($value, $key);
}
var_dump($finalData); // array (0)
</code>```

Why does $finalData have 0 elements inside? Shouldn't it be ['bar','ter']

答:
You merely need to make your use variable modifiable by reference:

```<code>$closure = function ($value, $key) use (&$finalData) {
// add this-----------------------------^
</code>```

Demo Link

Title: closure not performing as anticipated

Body:
Here's my code:

$array = ['foo' => 'bar', 'bis' => 'ter'];
$finalData=[];
$closure = function ($value, $key) use ($finalData) {
    $finalData[]=$value;
};
foreach ($array as $key => $value) {
    $closure($value, $key);
}
var_dump($finalData); // array (0)

Why does $finalData have 0 elements inside? Shouldn't it be ['bar','ter']

Body:
You merely need to make your use variable modifiable by reference:

$closure = function ($value, $key) use (&$finalData) {
// add this-----------------------------^

Demo Link