问:
Xamarin Forms: TemplatedItems returns only viewcells from grouped headings
I need to get all the viewcells of my listview programmatically so I could change the background color of a specific child layout within the viewcell.
There's no problem with updating the color for a viewcell when it's tapped, but I need to change the color of all viewcells to the default color, whenever a different viewcell is tapped.

While searching for a solution I often found answers where the viewcells were accessed by the runtime properties of the listview (see code below or the second answer in here: Xamarin.Forms: Get all cells/items of a listview), while testing the code I realized that this doesn't work for listviews where grouping is enabled.

```<code>IEnumerable<PropertyInfo> pInfos = (connectionsListView as ItemsView<Cell>).GetType().GetRuntimeProperties();
var templatedItems = pInfos.FirstOrDefault(info => info.Name == "TemplatedItems");
if (templatedItems != null)
{
  var cells = templatedItems.GetValue(connectionsListView);
    foreach (ViewCell cell in cells as Xamarin.Forms.ITemplatedItemsList<Xamarin.Forms.Cell>)
    {
        if (cell.BindingContext != null && cell.BindingContext is MyModelClass)
        {
              // Change background color of viewcell
        }
    }
}
</code>```

When grouping is enabled this code only returns the grouped header viewcells. I couldn't find any answer to change this code so the actual "body" viewcells are returned instead of only the headings.
Is there any possible approach to change this code so I get my expected result or do I have to use a custom renderer for this?

Update - Listview xaml code

Here you can see the listview I'm currently using in my XAML. I try to work out a solution where I can bind the background color of each viewcell to the model (to each "document" in my case) but at the moment I couldn't work out how to change the color for each specific viewcell when one is tapped. (I need to only have the background color of the currently selected viewcell to be changed, so all other viewcells have the default background color.)

```<code>            <ListView x:Name="DocumentListView"
                      ItemsSource="{Binding GroupedDocuments}"
                      BackgroundColor="WhiteSmoke"
                      HasUnevenRows="True"
                      RefreshCommand="{Binding LoadDocumentsCommand}"
                      IsPullToRefreshEnabled="True"
                      Refreshing="DocumentListView_OnRefreshing"
                      IsRefreshing="{Binding IsBusy, Mode=OneWay}"
                      CachingStrategy="RecycleElement"
                      IsGroupingEnabled="True"
                      GroupDisplayBinding="{Binding Key}"
                      GroupShortNameBinding="{Binding Key}"
                      VerticalOptions="StartAndExpand"
                      HorizontalOptions="StartAndExpand"
                      Margin="0, -20, 0, 0">
                <ListView.GroupHeaderTemplate>
                    <DataTemplate>
                        <ViewCell Height="25">
                            <Label x:Name="DocumentDate"
                                   FontSize="Medium"
                                   TextColor="#2E588C"
                                   VerticalOptions="Center"
                                   HorizontalTextAlignment="Center"
                                   Text="{Binding Key}"/>
                        </ViewCell>
                    </DataTemplate>
                </ListView.GroupHeaderTemplate>
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell Height="155" Tapped="DocumentViewCell_OnTapped">
                            <StackLayout Padding="10, 5, 10, 5">
                                <Frame Padding="0" HorizontalOptions="FillAndExpand" HasShadow="True">
                                    <StackLayout Padding="10" Orientation="Horizontal" HorizontalOptions="FillAndExpand" VerticalOptions="StartAndExpand">
                                        <StackLayout HorizontalOptions="StartAndExpand">
                                            <StackLayout Orientation="Horizontal" Spacing="15" Margin="10, 10, 10, 0" HorizontalOptions="StartAndExpand">
                                                <Label Text="{Binding Name}"
                                                       LineBreakMode="NoWrap"
                                                       FontSize="20"
                                                       TextColor="CornflowerBlue"
                                                       FontAttributes="Bold"/>
                                            </StackLayout>
                                            <StackLayout Orientation="Horizontal" Spacing="5" Margin="12, 0, 0, 0" HorizontalOptions="StartAndExpand">
                                                <Label Text="{Binding DocumentType.Name, StringFormat='Typ: {0}'}"
                                                       LineBreakMode="NoWrap"
                                                       FontSize="16"
                                                       TextColor="Black"/>
                                            </StackLayout>
                                            <StackLayout Orientation="Horizontal" Spacing="5" Margin="12, 3, 0, 0" HorizontalOptions="StartAndExpand">
                                                <Label Text="{Binding TotalValue, StringFormat='Gesamtwert: {0:F2} €'}"
                                                       LineBreakMode="NoWrap"
                                                       FontSize="16"
                                                       TextColor="Black"/>
                                            </StackLayout>
                                            <StackLayout Spacing="5" Margin="12, 3, 0, 0" Orientation="Horizontal" HorizontalOptions="StartAndExpand" VerticalOptions="Start">
                                                <Label Text="{Binding TagCollectionString, StringFormat='Tags: {0}'}"
                                                       LineBreakMode="WordWrap"
                                                       FontSize="14"
                                                       TextColor="Black"
                                                       VerticalOptions="CenterAndExpand"/>
                                            </StackLayout>
                                        </StackLayout>
                                        <StackLayout HorizontalOptions="EndAndExpand" VerticalOptions="Start" Margin="0, 25, 25, 0">
                                            <ImageButton HeightRequest="85" MinimumWidthRequest="85" x:Name="ButtonEditDocument" Source="baseline_more_vert_black_48.png" Clicked="ButtonEditDocument_OnClicked" Margin="0, 0, 15, 0" BackgroundColor="Transparent" WidthRequest="25" />
                                        </StackLayout>
                                    </StackLayout>
                                </Frame>
                            </StackLayout>
                        </ViewCell>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
</code>```

Update 2 - Usage of Bindings

I worked out how I could use bindings to store the currently selected background of each viewcell in my model. At the moment I'm facing the issue that the UI doesn't update properly when the bound values have changed.
Here is the code I have written so far and how the page is updated when a different viewcell is tapped:

Document model class:

```<code>public class Document
{
        public bool HasDefaultColor { get; set; }

        public string CurrentlySelectedColorFromHex
        {
            get => ColorConverter.GetHexString(CurrentlySelectedColor);
        }

        [NotMapped]
        public Color CurrentlySelectedColor => HasDefaultColor ? DefaultColor : ActivatedColor;

        private static readonly Color DefaultColor = Color.WhiteSmoke;
        private static readonly Color ActivatedColor = Color.FromHex("#2E588C");
}
</code>```

OnTapped function in code-behind:

```<code>        private void DocumentViewCell_OnTapped(object sender, EventArgs e)
        {
                    var documents = documentRepository.GetAll();
                    foreach (var document in documents)
                        document.HasDefaultColor = true;

                    selectedDocument.HasDefaultColor = false;
                    unitOfWork.Complete();
                    UpdatePage();
}
</code>```

In UpdatePage() I want to refresh the listview properly after the bound collection has changed:

```<code>                viewModel.LoadDocuments();
                DocumentListView.BeginRefresh();
</code>```

Sorry if this is a beginner question but I couldn't find an answer to this yet or couldn't figure out how to properly update the UI so that the background color of each viewcell is properly updated.
At least the bounded values are stored correctly at each OnTapped() call.

Update 3 - Added Converter

Hey guys, I have tried a few things and get stuck with updating the bound property of the model.
I have tried data triggers as well but couldn't change those data triggers correctly so they didn't worked as I expected them to do.

Until now I have added a custom bool to Color converter to convert the bound property:

```<code>    public class BoolToColorConverter : IValueConverter
    {
        private static readonly Color DefaultColor = Color.WhiteSmoke;
        private static readonly Color ActivatedColor = Color.FromHex("#2E588C");

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is bool activated)
                return activated ? ActivatedColor : DefaultColor;

            return DefaultColor;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is Color color)
            {
                if (color == DefaultColor)
                    return true;
            }

            return false;
        }
</code>```

The Color converter returns the correct values, but I can't figure out how to update the model property at runtime in the OnTapped() method of each viewcell.

Currently this is my OnTapped() method:

```<code>        private void DocumentViewCell_OnTapped(object sender, EventArgs e)
        {
                // Determine which document was selected
                if (sender.GetType() == typeof(ViewCell))
                {
                    ViewCell selectedViewCell = (ViewCell)sender;

                    if (selectedViewCell.BindingContext != null && selectedViewCell.BindingContext.GetType() == typeof(Document))
                    {
                        Document document = (Document)selectedViewCell.BindingContext;

                        // Update backing field selectedDocument for correct bindings and to show correct detail page
                        if (document != null)
                            selectedDocument = document;
                    }
                }
</code>```

Thanks for any help in advance and thanks to anyone who commented so far.

答:
I finally had some time to work out an answer for you.

I see by now you've already found a work around, but since it's not really in the line of the design philosophy of Xamarin.Forms (It's doing hardcoded work in the code-behind to get what you want instead of using Xamarin.Forms functionality.

Anyway I'll work out 2 possible solutions that are, in my opinion, better in line with a good Xamarin.Forms design.

Option 1:

This option keeps track of the currently selected item and uses a value converter for each item in the list to check if it's equal to that selected item and return a color based on that.

In our ViewModel we need to setup both the collection for our ListView our SelectedItem property that notifies us of property changes, and finally the ItemTappedCommand that will change our SelectedItem:

```<code>private ObservableCollection<ItemGroup> _itemGroups;
public ObservableCollection<ItemGroup> ItemGroups
{
    get => _itemGroups;
    set => SetProperty(ref _itemGroups, value);
}

private Item _selectedItem;
public Item SelectedItem
{
    get => _selectedItem;
    set => SetProperty(ref _selectedItem, value);
}

private ICommand _itemTappedCommand;
public ICommand ItemTappedCommand => _itemTappedCommand ?? (_itemTappedCommand = new Command<Item>((item) =>
{
    SelectedItem = item;
}));
</code>```

Then we will need a ValueConverter that will check equality and return the right Color:

```<code>public class EqualityToColorConverter : IValueConverter
{
    public Color EqualityColor { get; set; }

    public Color InequalityColor { get; set; }
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {

        if (value == null || parameter == null)
            return InequalityColor;

        if (parameter is Binding binding && binding.Source is View view)
        {
            parameter = view.BindingContext;
        }

        return value == parameter ? EqualityColor : InequalityColor;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
</code>```

This converter uses a small work around to extract the actual item from the parameter, since for some reason it kept returning me a Binding instead of the actual Item.

Now that we have everything in place we can create our page:

```<code><ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:converters="clr-namespace:ColorChangeDemo.Converters"
             x:Class="ColorChangeDemo.Views.SelectedItemPage">
    <ContentPage.Resources>
        <ResourceDictionary>
            <converters:EqualityToColorConverter x:Key="equalityToColorConverter" EqualityColor="Green" InequalityColor="Gray" />
        </ResourceDictionary>
    </ContentPage.Resources>
    <ContentPage.Content>
        <ListView x:Name="ListView"  ItemsSource="{Binding ItemGroups}" GroupShortNameBinding="{Binding Key}" GroupDisplayBinding="{Binding Key}" IsGroupingEnabled="True">
            <ListView.GroupHeaderTemplate>
                <DataTemplate>
                    <ViewCell>
                        <Label Text="{Binding Key}" />
                    </ViewCell>
                </DataTemplate>
            </ListView.GroupHeaderTemplate>
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <Button
                            x:Name="Button"
                            Text="{Binding Id}"
                            BackgroundColor="{Binding Source={x:Reference ListView}, Path=BindingContext.SelectedItem, Converter={StaticResource equalityToColorConverter}, ConverterParameter={Binding Source={x:Reference Button}}}"
                            Command="{Binding Source={x:Reference ListView}, Path=BindingContext.ItemTappedCommand}"
                            CommandParameter="{Binding .}"/>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </ContentPage.Content>
</ContentPage>
</code>```

The upside of this solution is that you don't have to change your Item class (in case you don't have any control over it), the downside however is that every selection change all items will react to the changed value. So if a lot of items are shown this might not be optimal.

Option 2:

This option will add a Selected property to the Item class, and keep track of the previously selected item to be able to deselect it when another item is selected.

Once again we start off with our ViewModel, first our properties:

```<code>private ObservableCollection<SelectableItemGroup> _selectableItemGroups;
public ObservableCollection<SelectableItemGroup> SelectableItemGroups
{
    get => _selectableItemGroups;
    set => SetProperty(ref _selectableItemGroups, value);
}

public ICommand ItemTappedCommand { get; }
</code>```

And in the constructor we create our command. For this to work we create a local variable that we can use to capture in the command so we can keep track of the previously selected item:

```<code>SelectableItem previous = null;

ItemTappedCommand = new Command<SelectableItem>((item) =>
{
    if (previous != null)
        previous.Selected = false;
    previous = item;
    item.Selected = true;
});
</code>```

Now we need a ValueConverter that can convert our Selected property into the right Color:

```<code>public class BoolToColorConverter: IValueConverter
{
    public Color TrueColor { get; set; }

    public Color FalseColor { get; set; }

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value != null && value is bool boolValue)
            return boolValue ? TrueColor : FalseColor;
        return FalseColor;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
</code>```

And once again we have everything setup to create our page:

```<code><ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:converters="clr-namespace:ColorChangeDemo.Converters"
             x:Class="ColorChangeDemo.Views.DeselectPage">
    <ContentPage.Resources>
        <ResourceDictionary>
            <converters:BoolToColorConverter x:Key="boolToColorConverter" TrueColor="Green" FalseColor="Gray" />
        </ResourceDictionary>
    </ContentPage.Resources>
    <ContentPage.Content>
        <ListView x:Name="ListView"  ItemsSource="{Binding SelectableItemGroups}" GroupShortNameBinding="{Binding Key}" GroupDisplayBinding="{Binding Key}" IsGroupingEnabled="True">
            <ListView.GroupHeaderTemplate>
                <DataTemplate>
                    <ViewCell>
                        <Label Text="{Binding Key}" />
                    </ViewCell>
                </DataTemplate>
            </ListView.GroupHeaderTemplate>
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <Button
                            x:Name="Button"
                            Text="{Binding Id}"
                            BackgroundColor="{Binding Selected, Converter={StaticResource boolToColorConverter}}"
                            Command="{Binding Source={x:Reference ListView}, Path=BindingContext.ItemTappedCommand}"
                            CommandParameter="{Binding .}"/>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </ContentPage.Content>
</ContentPage>
</code>```

The upside of this option is that it doesn't traverse the entire list to make sure everything has the right Color.

Demo project

To be able to view this in action I've uploaded a small demo project where I implemented both solutions:

https://github.com/nknoop/ChangeColorDemo

Body:
I need to get all the viewcells of my listview programmatically so I could change the background color of a specific child layout within the viewcell.
There's no problem with updating the color for a viewcell when it's tapped, but I need to change the color of all viewcells to the default color, whenever a different viewcell is tapped.

While searching for a solution I often found answers where the viewcells were accessed by the runtime properties of the listview (see code below or the second answer in here: Xamarin.Forms: Get all cells/items of a listview), while testing the code I realized that this doesn't work for listviews where grouping is enabled.

IEnumerable<PropertyInfo> pInfos = (connectionsListView as ItemsView<Cell>).GetType().GetRuntimeProperties();
var templatedItems = pInfos.FirstOrDefault(info => info.Name == "TemplatedItems");
if (templatedItems != null)
{
  var cells = templatedItems.GetValue(connectionsListView);
    foreach (ViewCell cell in cells as Xamarin.Forms.ITemplatedItemsList<Xamarin.Forms.Cell>)
    {
        if (cell.BindingContext != null && cell.BindingContext is MyModelClass)
        {
              // Change background color of viewcell
        }
    }
}

When grouping is enabled this code only returns the grouped header viewcells. I couldn't find any answer to change this code so the actual "body" viewcells are returned instead of only the headings.
Is there any possible approach to change this code so I get my expected result or do I have to use a custom renderer for this?

Update - Listview xaml code

Here you can see the listview I'm currently using in my XAML. I try to work out a solution where I can bind the background color of each viewcell to the model (to each "document" in my case) but at the moment I couldn't work out how to change the color for each specific viewcell when one is tapped. (I need to only have the background color of the currently selected viewcell to be changed, so all other viewcells have the default background color.)

            <ListView x:Name="DocumentListView"
                      ItemsSource="{Binding GroupedDocuments}"
                      BackgroundColor="WhiteSmoke"
                      HasUnevenRows="True"
                      RefreshCommand="{Binding LoadDocumentsCommand}"
                      IsPullToRefreshEnabled="True"
                      Refreshing="DocumentListView_OnRefreshing"
                      IsRefreshing="{Binding IsBusy, Mode=OneWay}"
                      CachingStrategy="RecycleElement"
                      IsGroupingEnabled="True"
                      GroupDisplayBinding="{Binding Key}"
                      GroupShortNameBinding="{Binding Key}"
                      VerticalOptions="StartAndExpand"
                      HorizontalOptions="StartAndExpand"
                      Margin="0, -20, 0, 0">
                <ListView.GroupHeaderTemplate>
                    <DataTemplate>
                        <ViewCell Height="25">

                        </ViewCell>
                    </DataTemplate>
                </ListView.GroupHeaderTemplate>
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell Height="155" Tapped="DocumentViewCell_OnTapped">
                            <StackLayout Padding="10, 5, 10, 5">
                                <Frame Padding="0" HorizontalOptions="FillAndExpand" HasShadow="True">
                                    <StackLayout Padding="10" Orientation="Horizontal" HorizontalOptions="FillAndExpand" VerticalOptions="StartAndExpand">
                                        <StackLayout HorizontalOptions="StartAndExpand">
                                            <StackLayout Orientation="Horizontal" Spacing="15" Margin="10, 10, 10, 0" HorizontalOptions="StartAndExpand">

                                            </StackLayout>
                                            <StackLayout Orientation="Horizontal" Spacing="5" Margin="12, 0, 0, 0" HorizontalOptions="StartAndExpand">

                                            </StackLayout>
                                            <StackLayout Orientation="Horizontal" Spacing="5" Margin="12, 3, 0, 0" HorizontalOptions="StartAndExpand">

                                            </StackLayout>
                                            <StackLayout Spacing="5" Margin="12, 3, 0, 0" Orientation="Horizontal" HorizontalOptions="StartAndExpand" VerticalOptions="Start">

                                            </StackLayout>
                                        </StackLayout>
                                        <StackLayout HorizontalOptions="EndAndExpand" VerticalOptions="Start" Margin="0, 25, 25, 0">
                                            <ImageButton HeightRequest="85" MinimumWidthRequest="85" x:Name="ButtonEditDocument" Source="baseline_more_vert_black_48.png" Clicked="ButtonEditDocument_OnClicked" Margin="0, 0, 15, 0" BackgroundColor="Transparent" WidthRequest="25" />
                                        </StackLayout>
                                    </StackLayout>
                                </Frame>
                            </StackLayout>
                        </ViewCell>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>

Update 2 - Usage of Bindings

I worked out how I could use bindings to store the currently selected background of each viewcell in my model. At the moment I'm facing the issue that the UI doesn't update properly when the bound values have changed.
Here is the code I have written so far and how the page is updated when a different viewcell is tapped:

Document model class:

public class Document
{
        public bool HasDefaultColor { get; set; }

        public string CurrentlySelectedColorFromHex
        {
            get => ColorConverter.GetHexString(CurrentlySelectedColor);
        }

        [NotMapped]
        public Color CurrentlySelectedColor => HasDefaultColor ? DefaultColor : ActivatedColor;

        private static readonly Color DefaultColor = Color.WhiteSmoke;
        private static readonly Color ActivatedColor = Color.FromHex("#2E588C");
}

OnTapped function in code-behind:

        private void DocumentViewCell_OnTapped(object sender, EventArgs e)
        {
                    var documents = documentRepository.GetAll();
                    foreach (var document in documents)
                        document.HasDefaultColor = true;

                    selectedDocument.HasDefaultColor = false;
                    unitOfWork.Complete();
                    UpdatePage();
}

In UpdatePage() I want to refresh the listview properly after the bound collection has changed:

                viewModel.LoadDocuments();
                DocumentListView.BeginRefresh();

Sorry if this is a beginner question but I couldn't find an answer to this yet or couldn't figure out how to properly update the UI so that the background color of each viewcell is properly updated.
At least the bounded values are stored correctly at each OnTapped() call.

Update 3 - Added Converter

Hey guys, I have tried a few things and get stuck with updating the bound property of the model.
I have tried data triggers as well but couldn't change those data triggers correctly so they didn't worked as I expected them to do.

Until now I have added a custom bool to Color converter to convert the bound property:

    public class BoolToColorConverter : IValueConverter
    {
        private static readonly Color DefaultColor = Color.WhiteSmoke;
        private static readonly Color ActivatedColor = Color.FromHex("#2E588C");

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is bool activated)
                return activated ? ActivatedColor : DefaultColor;

            return DefaultColor;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is Color color)
            {
                if (color == DefaultColor)
                    return true;
            }

            return false;
        }

The Color converter returns the correct values, but I can't figure out how to update the model property at runtime in the OnTapped() method of each viewcell.

Currently this is my OnTapped() method:

        private void DocumentViewCell_OnTapped(object sender, EventArgs e)
        {
                // Determine which document was selected
                if (sender.GetType() == typeof(ViewCell))
                {
                    ViewCell selectedViewCell = (ViewCell)sender;

                    if (selectedViewCell.BindingContext != null && selectedViewCell.BindingContext.GetType() == typeof(Document))
                    {
                        Document document = (Document)selectedViewCell.BindingContext;

                        // Update backing field selectedDocument for correct bindings and to show correct detail page
                        if (document != null)
                            selectedDocument = document;
                    }
                }

Thanks for any help in advance and thanks to anyone who commented so far.

Body:
I finally had some time to work out an answer for you.

I see by now you've already found a work around, but since it's not really in the line of the design philosophy of Xamarin.Forms (It's doing hardcoded work in the code-behind to get what you want instead of using Xamarin.Forms functionality.

Anyway I'll work out 2 possible solutions that are, in my opinion, better in line with a good Xamarin.Forms design.

Option 1:

This option keeps track of the currently selected item and uses a value converter for each item in the list to check if it's equal to that selected item and return a color based on that.

In our ViewModel we need to setup both the collection for our ListView our SelectedItem property that notifies us of property changes, and finally the ItemTappedCommand that will change our SelectedItem:

private ObservableCollection<ItemGroup> _itemGroups;
public ObservableCollection<ItemGroup> ItemGroups
{
    get => _itemGroups;
    set => SetProperty(ref _itemGroups, value);
}

private Item _selectedItem;
public Item SelectedItem
{
    get => _selectedItem;
    set => SetProperty(ref _selectedItem, value);
}

private ICommand _itemTappedCommand;
public ICommand ItemTappedCommand => _itemTappedCommand ?? (_itemTappedCommand = new Command<Item>((item) =>
{
    SelectedItem = item;
}));

Then we will need a ValueConverter that will check equality and return the right Color:

public class EqualityToColorConverter : IValueConverter
{
    public Color EqualityColor { get; set; }

    public Color InequalityColor { get; set; }
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {

        if (value == null || parameter == null)
            return InequalityColor;

        if (parameter is Binding binding && binding.Source is View view)
        {
            parameter = view.BindingContext;
        }

        return value == parameter ? EqualityColor : InequalityColor;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

This converter uses a small work around to extract the actual item from the parameter, since for some reason it kept returning me a Binding instead of the actual Item.

Now that we have everything in place we can create our page:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:converters="clr-namespace:ColorChangeDemo.Converters"
             x:Class="ColorChangeDemo.Views.SelectedItemPage">
    <ContentPage.Resources>
        <ResourceDictionary>
            <converters:EqualityToColorConverter x:Key="equalityToColorConverter" EqualityColor="Green" InequalityColor="Gray" />
        </ResourceDictionary>
    </ContentPage.Resources>
    <ContentPage.Content>
        <ListView x:Name="ListView"  ItemsSource="{Binding ItemGroups}" GroupShortNameBinding="{Binding Key}" GroupDisplayBinding="{Binding Key}" IsGroupingEnabled="True">
            <ListView.GroupHeaderTemplate>
                <DataTemplate>
                    <ViewCell>
                        <Label Text="{Binding Key}" />
                    </ViewCell>
                </DataTemplate>
            </ListView.GroupHeaderTemplate>
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <Button
                            x:Name="Button"
                            Text="{Binding Id}"
                            BackgroundColor="{Binding Source={x:Reference ListView}, Path=BindingContext.SelectedItem, Converter={StaticResource equalityToColorConverter}, ConverterParameter={Binding Source={x:Reference Button}}}"
                            Command="{Binding Source={x:Reference ListView}, Path=BindingContext.ItemTappedCommand}"
                            CommandParameter="{Binding .}"/>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </ContentPage.Content>
</ContentPage>

The upside of this solution is that you don't have to change your Item class (in case you don't have any control over it), the downside however is that every selection change all items will react to the changed value. So if a lot of items are shown this might not be optimal.

Option 2:

This option will add a Selected property to the Item class, and keep track of the previously selected item to be able to deselect it when another item is selected.

Once again we start off with our ViewModel, first our properties:

private ObservableCollection<SelectableItemGroup> _selectableItemGroups;
public ObservableCollection<SelectableItemGroup> SelectableItemGroups
{
    get => _selectableItemGroups;
    set => SetProperty(ref _selectableItemGroups, value);
}

public ICommand ItemTappedCommand { get; }

And in the constructor we create our command. For this to work we create a local variable that we can use to capture in the command so we can keep track of the previously selected item:

SelectableItem previous = null;

ItemTappedCommand = new Command<SelectableItem>((item) =>
{
    if (previous != null)
        previous.Selected = false;
    previous = item;
    item.Selected = true;
});

Now we need a ValueConverter that can convert our Selected property into the right Color:

public class BoolToColorConverter: IValueConverter
{
    public Color TrueColor { get; set; }

    public Color FalseColor { get; set; }

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value != null && value is bool boolValue)
            return boolValue ? TrueColor : FalseColor;
        return FalseColor;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

And once again we have everything setup to create our page:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:converters="clr-namespace:ColorChangeDemo.Converters"
             x:Class="ColorChangeDemo.Views.DeselectPage">
    <ContentPage.Resources>
        <ResourceDictionary>
            <converters:BoolToColorConverter x:Key="boolToColorConverter" TrueColor="Green" FalseColor="Gray" />
        </ResourceDictionary>
    </ContentPage.Resources>
    <ContentPage.Content>
        <ListView x:Name="ListView"  ItemsSource="{Binding SelectableItemGroups}" GroupShortNameBinding="{Binding Key}" GroupDisplayBinding="{Binding Key}" IsGroupingEnabled="True">
            <ListView.GroupHeaderTemplate>
                <DataTemplate>
                    <ViewCell>
                        <Label Text="{Binding Key}" />
                    </ViewCell>
                </DataTemplate>
            </ListView.GroupHeaderTemplate>
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <Button
                            x:Name="Button"
                            Text="{Binding Id}"
                            BackgroundColor="{Binding Selected, Converter={StaticResource boolToColorConverter}}"
                            Command="{Binding Source={x:Reference ListView}, Path=BindingContext.ItemTappedCommand}"
                            CommandParameter="{Binding .}"/>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </ContentPage.Content>
</ContentPage>

The upside of this option is that it doesn't traverse the entire list to make sure everything has the right Color.

Demo project

To be able to view this in action I've uploaded a small demo project where I implemented both solutions:

https://github.com/nknoop/ChangeColorDemo


来源: stackexchange

问:
If I leave the 'for' statement, the data will disappear
I did for loop. but The data in for loop is valid. but the data disappear except a few. I don't know why it is. I used two for loop(not same each other). and The two is same. I work in jupyter note. but I don't know this is the reason.

In the first for loop. I thought It just my mistake. so I save the file as CSV in the first for loop. but In the second for loop, the problem appear.

```<code>for i in range(0,191):

    coord_i = np.load(''+st[i].id+'.npy')
    print(coord_i)   # It is valid. I can see all coord_i. because It is in this for loop

print(coord_1)   # error : name 'coord_1' is not defined. beacuse It is not in above for loop
</code>```

I don't know what I miss. Please help me.

答:
First of all, as mentioned in a comment by MrGeek, coord_1 is not defined, coord_i is the only thing defined.
Secondly,if you want to print it after with

```<code>print(coord_i)
</code>```

command, that will just show you last one, number 190 coord_i, as every time you reset this variable. If you want to keep all of them and print afterwards ill recommend you to do following adjustments:

```<code>list_coord=[]
for i in range(0,191):

    coord_i = np.load(''+st[i].id+'.npy')
    list_coord.append(coord_i)
    print(coord_i)
print(list_coord)
</code>```

So u can have all your data stored

ContentLicense: CC BY-SA 4.0

Body:
I did for loop. but The data in for loop is valid. but the data disappear except a few. I don't know why it is. I used two for loop(not same each other). and The two is same. I work in jupyter note. but I don't know this is the reason.

In the first for loop. I thought It just my mistake. so I save the file as CSV in the first for loop. but In the second for loop, the problem appear.

for i in range(0,191):

    coord_i = np.load(''+st[i].id+'.npy')
    print(coord_i)   # It is valid. I can see all coord_i. because It is in this for loop

print(coord_1)   # error : name 'coord_1' is not defined. beacuse It is not in above for loop

I don't know what I miss. Please help me.

Body:
First of all, as mentioned in a comment by MrGeek, coord_1 is not defined, coord_i is the only thing defined.
Secondly,if you want to print it after with

print(coord_i)

command, that will just show you last one, number 190 coord_i, as every time you reset this variable. If you want to keep all of them and print afterwards ill recommend you to do following adjustments:

list_coord=[]
for i in range(0,191):

    coord_i = np.load(''+st[i].id+'.npy')
    list_coord.append(coord_i)
    print(coord_i)
print(list_coord)

So u can have all your data stored


问:
"Missing credentials" with PassportJS when I put enctype="multipart/form-data" and an input[type="file"]

THE PROBLEM

I've got a problem, when I use enctype="multipart/form-data" to my form (with an upload (.jpg/.png, etc.)) and I sumbit it, my flash displays "Missing credentials", without precisions. So how do I fix this ?

What I've tried

I searched solutions, but no one answered my problem. So I tried to resolve this, during 1-2 hours. I've found nothing. I asked too in another forum (alsacreations.com, if you know)

What I know, it is NOT a problem with my config/passport.js because otherwise, in my console, I would have logs.

Some code

```<code>[2] GET /api/auth/user 304 0.621 ms - -
[2] GET /api/auth/user 304 0.816 ms - -
[2] GET /favicon.ico 200 0.072 ms - 2780
[2] GET /assets/dist/app.js 304 1.433 ms - -
[2] GET /signup 304 2.842 ms - -
[2] POST /api/auth/user 200 5.250 ms - 2
[2] POST /signup 302 0.951 ms - 58
[2] GET /signup 200 3.036 ms - 3596
[2] GET /assets/styles/main-css.css 304 0.919 ms - -
[2] GET /assets/dist/main-js.js 304 2.542 ms - -
[2] GET /assets/dist/app.js 304 1.797 ms - -
[2] GET /assets/config/config-en.json 304 0.720 ms - -
[2] GET /assets/dist/manifest.json 304 0.584 ms - -
[2] GET /api/auth/user 200 0.529 ms - 5
[2] GET /api/auth/user 304 1.049 ms - -
[2] GET /assets/dist/app.js 304 0.994 ms - -
[2] GET /signup 200 4.576 ms - 3376
</code>```

As you see it there's no log...

Let's the demo!

https://forum.alsacreations.com/upload/1559134328-67719-alsa.png

I've a form (with enctype="multipart/form-data", etc.)

https://forum.alsacreations.com/upload/1559134431-67719-alsa.png

I upload my picture (as it happens an avatar)

https://forum.alsacreations.com/upload/1559134534-67719-alsa.png

BUT (else it'll be too easy...)
When I upload it, I've got this message ("Missing credentials"), is there any callback that I've not caught? (I wanna have more informations)

Thanks for your help.

(Sorry I can't place images, I'm under the 10 points of reputations, lol)

答:
Yes I did!

You can see too in my github: https://github.com/Soldat8889/psearch/tree/develop in app folder, routes and signupRouter.js

```<code>module.exports = {
    get: (req, res, _Template) => {
        fs.readFile(`public/config/config-${req.cookies.lang}.json`, 'utf-8', (e, data) => {
            if(e) {
                // REDIRECT
                res.redirect('/lang-select');
                return;
            }

            if(req.isAuthenticated()) {
                // REDIRECT
                res.redirect('/dashboard');
                return;
            }

            res.render('main', {
                title: JSON.parse(data)['title']['signup'],
                description: JSON.parse(data)['description']['signup'],
                lang: req.cookies.lang,
                url: `${req.protocol}://${req.get('host')}${req.originalUrl}`,
                env: nodeEnv,
                mainCSS: _Template.mainCSS,
                mainJS: _Template.mainJS,
                appJS: _Template.appJS,
                params: {
                    email: req.session.email,
                    username: req.session.username,
                    errorTarget: req.session.errorTarget
                }
            });
        });
    },
    authenticate: passport.authenticate('local-signup', { successRedirect: '/dashboard', failureRedirect: '/signup', failureFlash: true })
}
</code>```

Body:
THE PROBLEM

I've got a problem, when I use enctype="multipart/form-data" to my form (with an upload (.jpg/.png, etc.)) and I sumbit it, my flash displays "Missing credentials", without precisions. So how do I fix this ?

What I've tried

I searched solutions, but no one answered my problem. So I tried to resolve this, during 1-2 hours. I've found nothing. I asked too in another forum (alsacreations.com, if you know)

What I know, it is NOT a problem with my config/passport.js because otherwise, in my console, I would have logs.

Some code

[2] GET /api/auth/user 304 0.621 ms - -
[2] GET /api/auth/user 304 0.816 ms - -
[2] GET /favicon.ico 200 0.072 ms - 2780
[2] GET /assets/dist/app.js 304 1.433 ms - -
[2] GET /signup 304 2.842 ms - -
[2] POST /api/auth/user 200 5.250 ms - 2
[2] POST /signup 302 0.951 ms - 58
[2] GET /signup 200 3.036 ms - 3596
[2] GET /assets/styles/main-css.css 304 0.919 ms - -
[2] GET /assets/dist/main-js.js 304 2.542 ms - -
[2] GET /assets/dist/app.js 304 1.797 ms - -
[2] GET /assets/config/config-en.json 304 0.720 ms - -
[2] GET /assets/dist/manifest.json 304 0.584 ms - -
[2] GET /api/auth/user 200 0.529 ms - 5
[2] GET /api/auth/user 304 1.049 ms - -
[2] GET /assets/dist/app.js 304 0.994 ms - -
[2] GET /signup 200 4.576 ms - 3376

As you see it there's no log...

Let's the demo!

https://forum.alsacreations.com/upload/1559134328-67719-alsa.png

I've a form (with enctype="multipart/form-data", etc.)

https://forum.alsacreations.com/upload/1559134431-67719-alsa.png

I upload my picture (as it happens an avatar)

https://forum.alsacreations.com/upload/1559134534-67719-alsa.png

BUT (else it'll be too easy...)
When I upload it, I've got this message ("Missing credentials"), is there any callback that I've not caught? (I wanna have more informations)

Thanks for your help.

(Sorry I can't place images, I'm under the 10 points of reputations, lol)

Body:
Yes I did!

You can see too in my github: https://github.com/Soldat8889/psearch/tree/develop in app folder, routes and signupRouter.js

module.exports = {
    get: (req, res, _Template) => {
        fs.readFile(`public/config/config-${req.cookies.lang}.json`, 'utf-8', (e, data) => {
            if(e) {
                // REDIRECT
                res.redirect('/lang-select');
                return;
            }

            if(req.isAuthenticated()) {
                // REDIRECT
                res.redirect('/dashboard');
                return;
            }

            res.render('main', {
                title: JSON.parse(data)['title']['signup'],
                description: JSON.parse(data)['description']['signup'],
                lang: req.cookies.lang,
                url: `${req.protocol}://${req.get('host')}${req.originalUrl}`,
                env: nodeEnv,
                mainCSS: _Template.mainCSS,
                mainJS: _Template.mainJS,
                appJS: _Template.appJS,
                params: {
                    email: req.session.email,
                    username: req.session.username,
                    errorTarget: req.session.errorTarget
                }
            });
        });
    },
    authenticate: passport.authenticate('local-signup', { successRedirect: '/dashboard', failureRedirect: '/signup', failureFlash: true })
}


问:
How can you include variables that stay the same in jQuery functions?
I'm writing a web app that has multiple buttons. I want each button to have almost the same behaviour, but i have a variable that needs to be different at each button.

I use jQuery. I have a loop that sets the functionality of each button, like in the following example:

```<code>for (var i = 1; i <= 7; i++) {
    $("#button" + i).click(function() {
        $("#result").html("Button " + i + " was clicked.");
    });
}
</code>```

When i click Button 4 i want to get displayed that button 4 was clicked, but it says that button 8 was clicked, because that is the value of i at the end of the loop.
How can i solve this, so that i can have different results for every button?

EDIT: I solved it by using "let" instead of "var" for the i variable

答:
You can check it with id start with and then fetch number from id and show

$(document).ready(function() {
  $("[id^='button']").click(function() {
    var num = $(this).attr("id").match(/\d+/)[0];
    $("#result").html("Button " + num + " was clicked.");
  });
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="button" name="btn1" id="button1" value="Button 1">
<input type="button" name="btn2" id="button2" value="Button 2">
<input type="button" name="btn3" id="button3" value="Button 3">
<input type="button" name="btn4" id="button4" value="Button 4">
<input type="button" name="btn5" id="button5" value="Button 5">
<input type="button" name="btn6" id="button6" value="Button 6">
<input type="button" name="btn7" id="button7" value="Button 7">
<br/>
<div id="result"></div></code>```

Body:
I'm writing a web app that has multiple buttons. I want each button to have almost the same behaviour, but i have a variable that needs to be different at each button.

I use jQuery. I have a loop that sets the functionality of each button, like in the following example:

for (var i = 1; i <= 7; i++) {
    $("#button" + i).click(function() {
        $("#result").html("Button " + i + " was clicked.");
    });
}

When i click Button 4 i want to get displayed that button 4 was clicked, but it says that button 8 was clicked, because that is the value of i at the end of the loop.
How can i solve this, so that i can have different results for every button?

EDIT: I solved it by using "let" instead of "var" for the i variable

Body:
You can check it with id start with and then fetch number from id and show

$(document).ready(function() {
  $("[id^='button']").click(function() {
    var num = $(this).attr("id").match(/\d+/)[0];
    $("#result").html("Button " + num + " was clicked.");
  });
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="button" name="btn1" id="button1" value="Button 1">
<input type="button" name="btn2" id="button2" value="Button 2">
<input type="button" name="btn3" id="button3" value="Button 3">
<input type="button" name="btn4" id="button4" value="Button 4">
<input type="button" name="btn5" id="button5" value="Button 5">
<input type="button" name="btn6" id="button6" value="Button 6">
<input type="button" name="btn7" id="button7" value="Button 7">
<br/>
<div id="result"></div>


问:
The loop does not work for the second iteration

The loop does not run after the first time

```<code>class Solution {
    public static void main(String[] argh) {
        int sum = 0;
        Scanner in = new Scanner(System.in);
        int t = in.nextInt();
        for (int i = 0; i < t; i++) {
            int a = in.nextInt();
            int b = in.nextInt();
            int n = in.nextInt();

            for (i = 0; i < n; i++) {
                sum += (a + (Math.pow(2, i) * b));
                System.out.print(sum + " ");
            }

        }
        in.close();
    }
}
</code>```

Input   2  0 2 10  5 3 5

Your Output (stdout)  2 6 14 30 62 126 254 510 1022 2046

Expected Output Download  2 6 14 30 62 126 254 510 1022 2046 8 14 26 50
  98

答:
use separate int variable in inner loop</p>

```<code>for (int i = 0; i < t; i++) {
            int a = in.nextInt();
            int b = in.nextInt();
            int n = in.nextInt();
        for (int j = 0; j < n; j++) {
            sum += (a + (Math.pow(2, i) * b));
            System.out.print(sum + " ");
        }

    }
</code>```

Body:
The loop does not run after the first time

class Solution {
    public static void main(String[] argh) {
        int sum = 0;
        Scanner in = new Scanner(System.in);
        int t = in.nextInt();
        for (int i = 0; i < t; i++) {
            int a = in.nextInt();
            int b = in.nextInt();
            int n = in.nextInt();

            for (i = 0; i < n; i++) {
                sum += (a + (Math.pow(2, i) * b));
                System.out.print(sum + " ");
            }

        }
        in.close();
    }
}

Input   2  0 2 10  5 3 5

Your Output (stdout)  2 6 14 30 62 126 254 510 1022 2046

Expected Output Download  2 6 14 30 62 126 254 510 1022 2046 8 14 26 50
  98

Body:
use separate int variable in inner loop

for (int i = 0; i < t; i++) {
            int a = in.nextInt();
            int b = in.nextInt();
            int n = in.nextInt();
        for (int j = 0; j < n; j++) {
            sum += (a + (Math.pow(2, i) * b));
            System.out.print(sum + " ");
        }

    }


问:
How to select date and previous date
I have a table of referral records with a start date and end date. If the person has had previous referrals I need to retrieve the start and end date of the referral previous to the current one.

Any ideas would be greatly appreciated!

Example of what I hope to achieve

```<code>Per ID    Ref ID    Refrl_Start_D    Refrl_End_D    Prev_Refrl_S    Prev_Refrl_S
1         5         10/10/2018       Null           01/02/2018      03/03/2018
2         4         05/04/2018       Null           01/01/2017      01/03/2017
1         3         01/02/2018       03/03/2018     02/01/2017      20/01/2017
1         2         02/01/2018       20/01/2018     Null            Null
2         1         01/01/2018       01/03/2018     Null            Null
</code>```

Is have tried adding a Rank calc grouped by person. My plan was to create another table offset it by 1 and join them (i.e. Join referral 5 with 4). However I couldn't figure out how to get the join right.

```<code>SELECT DIM_PERSON_ID,
       FACT_REFERRAL_ID,
       REFRL_START_DTTM,
       REFRL_END_DTTM
FROM FACT_REFERRALS;
</code>```

答:
You can use LAG here</p>

```<code>SELECT DIM_PERSON_ID,
       FACT_REFERRAL_ID,
       REFRL_START_DTTM,
       REFRL_END_DTTM
       PrevStart = LAG(REFRL_START_DTTM)
                       OVER(PARTITION BY DIM_PERSON_ID
                           ORDER BY REFRL_START_DTTM DESC),
       PrevEnd = LAG(REFRL_END_DTTM)
                     OVER(PARTITION BY DIM_PERSON_ID
                         ORDER BY REFRL_END_DTTMDESC)
FROM FACT_REFERRALS R;
</code>```

Title: How to select date and previous date

Body:
I have a table of referral records with a start date and end date. If the person has had previous referrals I need to retrieve the start and end date of the referral previous to the current one.

Any ideas would be greatly appreciated!

Example of what I hope to achieve

Per ID    Ref ID    Refrl_Start_D    Refrl_End_D    Prev_Refrl_S    Prev_Refrl_S
1         5         10/10/2018       Null           01/02/2018      03/03/2018
2         4         05/04/2018       Null           01/01/2017      01/03/2017
1         3         01/02/2018       03/03/2018     02/01/2017      20/01/2017
1         2         02/01/2018       20/01/2018     Null            Null
2         1         01/01/2018       01/03/2018     Null            Null

Is have tried adding a Rank calc grouped by person. My plan was to create another table offset it by 1 and join them (i.e. Join referral 5 with 4). However I couldn't figure out how to get the join right.

SELECT DIM_PERSON_ID,
       FACT_REFERRAL_ID,
       REFRL_START_DTTM,
       REFRL_END_DTTM
FROM FACT_REFERRALS;

Body:
You can use LAG here

SELECT DIM_PERSON_ID,
       FACT_REFERRAL_ID,
       REFRL_START_DTTM,
       REFRL_END_DTTM
       PrevStart = LAG(REFRL_START_DTTM)
                       OVER(PARTITION BY DIM_PERSON_ID
                           ORDER BY REFRL_START_DTTM DESC),
       PrevEnd = LAG(REFRL_END_DTTM)
                     OVER(PARTITION BY DIM_PERSON_ID
                         ORDER BY REFRL_END_DTTMDESC)
FROM FACT_REFERRALS R;


问:
Editing header of all HTTP request made by mapbox-gl-native iOS SDK
I'm using mapbox-gl-native SDK. It can be used with custom servers to provide map tilesets. I'm working with a server which needs an API key in the HTTP request header. I want to edit the header for every request and add the API key.
can anyone help me with this?

I'm using mapbox-gl-native iOS v5.0 (latest untill now)

答:
there is a file named http_file_source.mm in platform/darwin/src/ which is responsible for making HTTP requests. there is a method in this file:

HTTPFileSource::request(const Resource& resource, Callback callback) {
```

<p>in this mehtod you can see this line:</p>

<pre class="lang-m prettyprint-override"><code>NSMutableURLRequest* req = [NSMutableURLRequest requestWithURL:url];
</code>```

this line makes a http request you can add your own header to it, like so: (value for header field)

[req addValue:(NSString *)value forHTTPHeaderField:(NSString *)field]
```

Body:
there is a file named http_file_source.mm in platform/darwin/src/ which is responsible for making HTTP requests. there is a method in this file:

HTTPFileSource::request(const Resource& resource, Callback callback) {

in this mehtod you can see this line:

NSMutableURLRequest* req = [NSMutableURLRequest requestWithURL:url];

this line makes a http request you can add your own header to it, like so: (value for header field)

[req addValue:(NSString *)value forHTTPHeaderField:(NSString *)field]


问:
Google Sheets ImportXml() to extract data from table
I am trying to retrieve a single cell data from an URL using IMPORTXML function but don't know how to expand the query. The below query retrieves all the rows.

```<code>=IMPORTXML("https://www.bullion-rates.com/gold.htm", "//td[@class='rate']")

    1,276.84    ChartsHistory
    1,146.68    ChartsHistory
    1,011.26    ChartsHistory
    82,979      ChartsHistory
</code>```

But I need only the data in the 4th row and 1st column (82,979). How to query it using importxml.

答:
This has been answered before. Try:</p>

```<code>=index(IMPORTXML("https://www.bullion-rates.com/gold.htm", "//td[@class='rate']"),4,1)
</code>```

Body:
I am trying to retrieve a single cell data from an URL using IMPORTXML function but don't know how to expand the query. The below query retrieves all the rows.

=IMPORTXML("https://www.bullion-rates.com/gold.htm", "//td[@class='rate']")

    1,276.84    ChartsHistory
    1,146.68    ChartsHistory
    1,011.26    ChartsHistory
    82,979      ChartsHistory

But I need only the data in the 4th row and 1st column (82,979). How to query it using importxml.

Body:
This has been answered before. Try:

=index(IMPORTXML("https://www.bullion-rates.com/gold.htm", "//td[@class='rate']"),4,1)


问:
Unit testing, statics, and factories
I am implementing a model in Java which requires iterating over a collection and going through a number of identification stages, it involves for loops, while loops etc. It is the sort of thing I want to test at a fine-grained level so that I have confidence it has been implemented properly.

I have used it as an opportunity to start unit testing, as it is something I recognise as being beneficial to my code. I have since been reading a forest of books to get up to speed with JUnit and unit testing.

Basically my question comes down to two conflicting pieces of advice I have received:

1) Statics are evil. Do not touch statics. Do not test privates either, you probably want a class there instead.

2) Use factories for creation to allow dependency injection using parameters - potentially allowing use of mocks and stubs for isolation.

In my example I am looking to perform an operation along the lines of:

```<code>double height = 223.42; // this was set iterating over a collection of doubles
//blah
HeightBounds b = HeightBounds.getHeightBounds(height);
//more blah
</code>```

I have done this in order to avoid building up what would become a very long and complicated block of code, which I can only test in its entirety. This way I have public accessible objects that I can test to ensure the system components all perform correctly.

Common sense says to me there is nothing wrong with static factories, and that they are easily tested, but am I missing something blindingly obvious given I am learning test-driven design?

Thank you

答:
The static factory class introduces coupling between your class and the HeightBounds class.  this might make your class difficult to test, if for example HeightBounds goes off and looks in DB for information, or reads from a web service etc etc.

If you instead injected an IHeightBounds implementation into your class then you could mock that out so you could test what happens when the dependencies of you class do certain things.

For example what if HeightBounds throws an exception?  or returns null?  Or you want to test when a particular HeightBound is returned?  With an interface it is easy to mock this behaviour, with a static factory it is more difficult as you have manufacture the data to create the desired results in the class.

You could still only have a single implementation of HeightBounds and would be able to test that in isolation, but you would be able to test your method above without even having an real implementation.

I would probably have an IHeightBoundFactory interface and inject an implementation into the class.

As for testing the privates, generally you don't want to.  You want to be testing one of 2 things, either that the results are what you expected or that the interactions are what you expected.

If you have a method called  Add and a method called GetAll then you might want to test that when you call Add and then call GetAll you get back the one you added.  you don't care how this is implemented, just that it works.  this is testing the results.  Generally in this situation you want to create mock objects that return data.  This seems to be your situation.

If when you call Add you expect that what is being added is logged, then you want to test the interactions with the logging dependency, so you inject a mock dependency and verify that the interaction with that class happened when you called Add.  Generally in this situation you want to create mock objects that have expectations set, and you verify that those expectations have been met.  It doesn't look this is necessary in the situation you described above.

ContentLicense: CC BY-SA 3.0

Title: Unit testing, statics, and factories

Body:
I am implementing a model in Java which requires iterating over a collection and going through a number of identification stages, it involves for loops, while loops etc. It is the sort of thing I want to test at a fine-grained level so that I have confidence it has been implemented properly.

I have used it as an opportunity to start unit testing, as it is something I recognise as being beneficial to my code. I have since been reading a forest of books to get up to speed with JUnit and unit testing.

Basically my question comes down to two conflicting pieces of advice I have received:

1) Statics are evil. Do not touch statics. Do not test privates either, you probably want a class there instead.

2) Use factories for creation to allow dependency injection using parameters - potentially allowing use of mocks and stubs for isolation.

In my example I am looking to perform an operation along the lines of:

double height = 223.42; // this was set iterating over a collection of doubles
//blah
HeightBounds b = HeightBounds.getHeightBounds(height);
//more blah

I have done this in order to avoid building up what would become a very long and complicated block of code, which I can only test in its entirety. This way I have public accessible objects that I can test to ensure the system components all perform correctly.

Common sense says to me there is nothing wrong with static factories, and that they are easily tested, but am I missing something blindingly obvious given I am learning test-driven design?

Thank you


问:
DAML when running da new
When running da new I am getting this error (indented to improve readability):

```<code>RepoError (
  ErrorDownload (
    ServantErrorWithContext (
      FailureResponse (
        Response {
          responseStatusCode = Status {
            statusCode = 404,
            statusMessage = "Not Found"
          },
          responseHeaders = fromList [
            ("Server","nginx"),
            ("Date","Sun, 21 Apr 2019 14:20:58 GMT"),
            ("Content-Type","text/plain"),
            ("Transfer-Encoding","chunk")
          ]
        }
      )
    )
  )
)
</code>```

What's its meaning?

答: Using the latest version of DAML we have introduced a daml command. I suggest you try using that.

Title: DAML when running da new

Body:
When running da new I am getting this error (indented to improve readability):

RepoError (
  ErrorDownload (
    ServantErrorWithContext (
      FailureResponse (
        Response {
          responseStatusCode = Status {
            statusCode = 404,
            statusMessage = "Not Found"
          },
          responseHeaders = fromList [
            ("Server","nginx"),
            ("Date","Sun, 21 Apr 2019 14:20:58 GMT"),
            ("Content-Type","text/plain"),
            ("Transfer-Encoding","chunk")
          ]
        }
      )
    )
  )
)

What's its meaning?


问:
IntelliJ IDEA is not recognizing my java files as runnable and instead wants to run the class files. Any ideas of how to fix?
Anytime I try to run a java file by clicking run, it instead tries to run the class file and thus gives a no main method error.

When I try to right click on a java file and run that, it doesn't recogize it as a file that is runable.

I am still able to run programs from the command prompt but I would prefer to be able to run them in IntelliJ.

This occurred after trying to create a Class path when using JSon Libraries.

Edit:

Normally it shows java files with this icon:

But instead it's showing this icon for java files:

I think the change in icon might have something to do with it.

Edit 2:
the exact error I get is "C:\Program Files (x86)\Java\jdk1.8.0_181\bin\java.exe"...bunch of other program file locations

Error: Could not find or load main class sample.Main

Process finished with exit code 1

答:
I had the same problem and found out that my src wasn't marked as Sources Root. To change this:

right-mouse click on your src

navigate to "Mark Directory As"

choose "Sources Root"
It will now recognize your files correctly and your main classes will be able to run again

IntelliJ not recognizing my .java-files

Problem solved


问:
Is it better practice to use String.format over string Concatenation in Java?
Is there a perceptible difference between using String.format and String concatenation in Java?

I tend to use String.format but occasionally will slip and use a concatenation. I was wondering if one was better than the other.

The way I see it, String.format gives you more power in "formatting" the string; and concatenation means you don't have to worry about accidentally putting in an extra %s or missing one out.

String.format is also shorter.

Which one is more readable depends on how your head works.

答:
I think we can go with MessageFormat.format as it should be good at both readability and also performance aspects.

I used the same program which one used by Icaro in his above answer and I enhanced it with appending code for using MessageFormat to explain the performance numbers.

```<code>  public static void main(String[] args) {
    long start = System.currentTimeMillis();
    for (int i = 0; i < 1000000; i++) {
      String s = "Hi " + i + "; Hi to you " + i * 2;
    }
    long end = System.currentTimeMillis();
    System.out.println("Concatenation = " + ((end - start)) + " millisecond");

    start = System.currentTimeMillis();
    for (int i = 0; i < 1000000; i++) {
      String s = String.format("Hi %s; Hi to you %s", i, +i * 2);
    }
    end = System.currentTimeMillis();
    System.out.println("Format = " + ((end - start)) + " millisecond");

    start = System.currentTimeMillis();
    for (int i = 0; i < 1000000; i++) {
      String s = MessageFormat.format("Hi %s; Hi to you %s", i, +i * 2);
    }
    end = System.currentTimeMillis();
    System.out.println("MessageFormat = " + ((end - start)) + " millisecond");
  }
</code>```

Concatenation = 69 millisecond

Format = 1435 millisecond

MessageFormat = 200 millisecond

UPDATES:

As per SonarLint Report, Printf-style format strings should be used correctly (squid:S3457)

Because printf-style format strings are interpreted at runtime, rather than validated by the compiler, they can contain errors that result in the wrong strings being created. This rule statically validates the correlation of printf-style format strings to their arguments when calling the format(...) methods of java.util.Formatter, java.lang.String, java.io.PrintStream, MessageFormat, and java.io.PrintWriter classes and the printf(...) methods of java.io.PrintStream or java.io.PrintWriter classes.

I replace the printf-style with the curly-brackets and I got something interesting results as below.

Concatenation = 69 millisecond
 Format = 1107 millisecond

  Format:curly-brackets = 416 millisecond
 MessageFormat = 215
  millisecond
 MessageFormat:curly-brackets = 2517 millisecond

My Conclusion:

As I highlighted above, using String.format with curly-brackets should be a good choice to get benefits of good readability and also performance.

Body:
I think we can go with MessageFormat.format as it should be good at both readability and also performance aspects.

I used the same program which one used by Icaro in his above answer and I enhanced it with appending code for using MessageFormat to explain the performance numbers.

  public static void main(String[] args) {
    long start = System.currentTimeMillis();
    for (int i = 0; i < 1000000; i++) {
      String s = "Hi " + i + "; Hi to you " + i * 2;
    }
    long end = System.currentTimeMillis();
    System.out.println("Concatenation = " + ((end - start)) + " millisecond");

    start = System.currentTimeMillis();
    for (int i = 0; i < 1000000; i++) {
      String s = String.format("Hi %s; Hi to you %s", i, +i * 2);
    }
    end = System.currentTimeMillis();
    System.out.println("Format = " + ((end - start)) + " millisecond");

    start = System.currentTimeMillis();
    for (int i = 0; i < 1000000; i++) {
      String s = MessageFormat.format("Hi %s; Hi to you %s", i, +i * 2);
    }
    end = System.currentTimeMillis();
    System.out.println("MessageFormat = " + ((end - start)) + " millisecond");
  }

Concatenation = 69 millisecond

Format = 1435 millisecond

MessageFormat = 200 millisecond

UPDATES:

As per SonarLint Report, Printf-style format strings should be used correctly (squid:S3457)

Because printf-style format strings are interpreted at runtime, rather than validated by the compiler, they can contain errors that result in the wrong strings being created. This rule statically validates the correlation of printf-style format strings to their arguments when calling the format(...) methods of java.util.Formatter, java.lang.String, java.io.PrintStream, MessageFormat, and java.io.PrintWriter classes and the printf(...) methods of java.io.PrintStream or java.io.PrintWriter classes.

I replace the printf-style with the curly-brackets and I got something interesting results as below.

Concatenation = 69 millisecond
 Format = 1107 millisecond

  Format:curly-brackets = 416 millisecond
 MessageFormat = 215
  millisecond
 MessageFormat:curly-brackets = 2517 millisecond

My Conclusion:

As I highlighted above, using String.format with curly-brackets should be a good choice to get benefits of good readability and also performance.


答:
There are lots of ways to approach this. Overkill would be to use a closure to maintain the scope of i:

```<code>for (var i = 1; i <= 7; i++) {
  (function(i) {
    $("#button" + i).click(function() {
      $("#result").html("Button " + i + " was clicked.");
    });
  })(i);
}
</code>```

Alternatively you could just read the id from the button which was clicked directly:

```<code>for (var i = 1; i <= 7; i++) {
  $("#button" + i).click(function() {
    $("#result").html(this.id + ' was clicked.');
  });
}
</code>```

Taking that a step further you could use a common class on all the buttons to avoid the loop entirely:

$(".button").click(function() {
  $("#result").html(this.id + ' was clicked.');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="button1" class="button">1</button>
<button id="button2" class="button">2</button>
<button id="button3" class="button">3</button>
<button id="button4" class="button">4</button>
<button id="button5" class="button">5</button>
<button id="button6" class="button">6</button>
<button id="button7" class="button">7</button>
<div id="result"></div></code>```

Title: How can you include variables that stay the same in jQuery functions?

Body:
There are lots of ways to approach this. Overkill would be to use a closure to maintain the scope of i:

for (var i = 1; i <= 7; i++) {
  (function(i) {
    $("#button" + i).click(function() {
      $("#result").html("Button " + i + " was clicked.");
    });
  })(i);
}

Alternatively you could just read the id from the button which was clicked directly:

for (var i = 1; i <= 7; i++) {
  $("#button" + i).click(function() {
    $("#result").html(this.id + ' was clicked.');
  });
}

Taking that a step further you could use a common class on all the buttons to avoid the loop entirely:

$(".button").click(function() {
  $("#result").html(this.id + ' was clicked.');
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="button1" class="button">1</button>
<button id="button2" class="button">2</button>
<button id="button3" class="button">3</button>
<button id="button4" class="button">4</button>
<button id="button5" class="button">5</button>
<button id="button6" class="button">6</button>
<button id="button7" class="button">7</button>
<div id="result"></div>


问:
Get the records of last month in SQL server
I want to get the records of last month based on my db table [member] field "date_created".

What's the sql to do this?

For clarification,
last month - 1/8/2009 to 31/8/2009

If today is 3/1/2010, I'll need to get the records of 1/12/2009 to 31/12/2009.

答:
A simple query which works for me is:

select * from table where DATEADD(month, 1,DATEFIELD) >= getdate()

ContentLicense: CC BY-SA 2.5


问:
How to replace a text in pdf file with ITextPDF library?
I have a requirement to replace a placeholder like ${placeholder} with an actual value, but I could not find any working solution... I've ben following by https://itextpdf.com/en/resources/examples/itext-7/replacing-pdf-objects and it doesn't work. Does anybody know how to do it?</p>

答:
In general, it's not so easy to "replace" the content of a pdf file, since it could have been written in a different way. For example, suppose that you want to replace a chunk "Hello" with a chunk "World". You'd be lucky if "Hello" has been written to a pdf as a whole word. It might have been written as "He" and "llo", or even "o", "l" , "l", "e", "H", and the letters migth be placed in a different parts of the content stream.

However one can remove the content and then place some other content on the same place.

Let's look at how it could be done.

1) I advice you to use iText's pdfSweep, since this tool is able to detect the areas on which the content has been placed and remove the content (it's important to mention that pdfSweep doesn't hide content, it removes it completely)

Please look at the next sample: https://github.com/itext/i7j-pdfsweep/blob/develop/src/test/java/com/itextpdf/pdfcleanup/BigDocumentAutoCleanUpTest.java

Let's discuss redactTonySoprano test. As you can see, one can provide some regexes (for example, ""Tony( |_)Soprano", "Soprano" and "Sopranoes") and iText will redact all the matches of the content.

Then you can just write some text upon these areas using iText either via lowlevel api (PdfCanvas) or via more complex highlevel api (Canvas, etc).

Let's modify the soprano sample I've mentioned before a bit:

2) Let's add some text upon the redacted areas:

```<code>for (IPdfTextLocation location : strategy.getResultantLocations()) {
PdfPage page = pdf.getPage(location.getPageNumber()+1);
PdfCanvas pdfCanvas = new PdfCanvas(page.newContentStreamAfter(), page.getResources(), page.getDocument());
Canvas canvas = new Canvas(pdfCanvas, pdf, location.getRectangle());
canvas.add(new Paragraph("SECURED").setFontSize(8));
</code>```

}

The result is not ideal, but that is just a proof of concept. It's possible to override the extraction strategies and define the font of the redacted content, so that it could be used for the new text to be placed on the redacted area.

Body:
In general, it's not so easy to "replace" the content of a pdf file, since it could have been written in a different way. For example, suppose that you want to replace a chunk "Hello" with a chunk "World". You'd be lucky if "Hello" has been written to a pdf as a whole word. It might have been written as "He" and "llo", or even "o", "l" , "l", "e", "H", and the letters migth be placed in a different parts of the content stream.

However one can remove the content and then place some other content on the same place.

Let's look at how it could be done.

1) I advice you to use iText's pdfSweep, since this tool is able to detect the areas on which the content has been placed and remove the content (it's important to mention that pdfSweep doesn't hide content, it removes it completely)

Please look at the next sample: https://github.com/itext/i7j-pdfsweep/blob/develop/src/test/java/com/itextpdf/pdfcleanup/BigDocumentAutoCleanUpTest.java

Let's discuss redactTonySoprano test. As you can see, one can provide some regexes (for example, ""Tony( |_)Soprano", "Soprano" and "Sopranoes") and iText will redact all the matches of the content.

Then you can just write some text upon these areas using iText either via lowlevel api (PdfCanvas) or via more complex highlevel api (Canvas, etc).

Let's modify the soprano sample I've mentioned before a bit:

2) Let's add some text upon the redacted areas:

for (IPdfTextLocation location : strategy.getResultantLocations()) {
PdfPage page = pdf.getPage(location.getPageNumber()+1);
PdfCanvas pdfCanvas = new PdfCanvas(page.newContentStreamAfter(), page.getResources(), page.getDocument());
Canvas canvas = new Canvas(pdfCanvas, pdf, location.getRectangle());
canvas.add(new Paragraph("SECURED").setFontSize(8));

}

The result is not ideal, but that is just a proof of concept. It's possible to override the extraction strategies and define the font of the redacted content, so that it could be used for the new text to be placed on the redacted area.


问:
How is the coordinator node in cassandra determined by a client driver?
I don't understand the load balancing algorithm in cassandra.

It seems that the TokenAwarePolicy can be used to route my request to the coordinator node holding the data. In particular, the documentation states (https://docs.datastax.com/en/developer/java-driver/3.6/manual/load_balancing/) that it works when the driver is able to automatically calculate a routing-key. If it can, I am routed to the coordinator node holding the data, if not, I am routed to another node. I can still specify the routing-key myself if I really want to reach the data without any extra hop.

What does not make sense to me:

If the driver cannot calculate the routing-key automatically, then why can the coordinator do this? Does it have more information than the client driver? Or does the coordinator node then ask every other node in the cluster on my behalf? This would then not scale, right?

I thought that the gossip protocol is used to share the topology of the ring among all nodes (AND the client driver). The client driver than has the complete 'ring' structure and should be equal to any 'hop' node.

Load balancing makes sense to me when the client driver determines the N replicas holding the data, and then prioritizes them (host-distance, etc), but it doesn't make sense to me when I reach a random node that is unlikey to have my data.

答:
Token aware load balancing happens only for that statements that are able to hold routing information. For example, for prepared queries, driver receives information from cluster about fields in query, and has information about partition key(s), so it's able to calculate token for data, and select the node. You can also specify the routing key youself, and driver will send request to corresponding node.

It's all explained in the documentation:

For simple statements, routing information can never be computed automatically

For built statements, the keyspace is available if it was provided while building the query; the routing key is available only if the statement was built using the table metadata, and all components of the partition key appear in the query

For bound statements, the keyspace is always available; the routing key is only available if all components of the partition key are bound as variables

For batch statements, the routing information of each child statement is inspected; the first non-null keyspace is used as the keyspace of the batch, and the first non-null routing key as its routing key

When statement doesn't have routing information, the request is sent to node selected by nested load balancing policy, and the node-coordinator, performs parsing of the statement, extract necessary information and calculates the token, and forwards request to correct node.


问:
How to search for a specific dynamic pattern of a field's in mongodb.?
I need to search mongodb collection for a specific pattern field. I tried using {$exists:true}; However, this gives results only if you provide exact field.

I tried using {$exists:true} for my field. But this does not give results if you give some pattern.

```<code>{
"field1":"value1",
"field2":"value2",
"field3":object
{/arjun1/pat1: 1,
/arjun2/pat2: 3,
/arjun3/pat3: 5
}
"field4":"value4",
}
</code>```

From some field, I get the keys pat3 & field3. From this I would need to find out if the value /arjun3/pat3 exists in the document.
If I use {"field3./arjun3/pat3":{$exists:true}}, this would give me results. But the problem is I get only field3 and pat3 and I need to use some pattern matching like field3.*.pat3 and then use $expr or $exists; which I'm not exactly sure how to. Please help.

答:
You can either go for regex (re module) for SQL like pattern matching, and compile your own custom wildcard. But if you don't want that then you can simple use the fnmatch module, it is a builtin library of python which allows wildcard matching for multiple characters (via*) or a single character (via ?).

```<code>import fnmatch

a = "hello"
print(fnmatch.fnmatch(a, "h*"))
</code>```

OUTPUT:-

```<code>True
</code>```

Body:
I need to search mongodb collection for a specific pattern field. I tried using {$exists:true}; However, this gives results only if you provide exact field.

I tried using {$exists:true} for my field. But this does not give results if you give some pattern.

{
"field1":"value1",
"field2":"value2",
"field3":object
{/arjun1/pat1: 1,
/arjun2/pat2: 3,
/arjun3/pat3: 5
}
"field4":"value4",
}

From some field, I get the keys pat3 & field3. From this I would need to find out if the value /arjun3/pat3 exists in the document.
If I use {"field3./arjun3/pat3":{$exists:true}}, this would give me results. But the problem is I get only field3 and pat3 and I need to use some pattern matching like field3.*.pat3 and then use $expr or $exists; which I'm not exactly sure how to. Please help.

Body:
You can either go for regex (re module) for SQL like pattern matching, and compile your own custom wildcard. But if you don't want that then you can simple use the fnmatch module, it is a builtin library of python which allows wildcard matching for multiple characters (via*) or a single character (via ?).

import fnmatch

a = "hello"
print(fnmatch.fnmatch(a, "h*"))

OUTPUT:-

True


问:
jquery ui tab appending content when reloaded
I have a jquery ui tab that gets loaded via ajax and remote page:

```<code><div id="tabs" style="width:1200px" class="ui-tabs">
    <ul>
        <li><a href="/bugs/loadTab1">View</a></li>
        <li><a href="#tabs-2">Add Bug/Request</a></li>
    </ul>...

<script type="text/javascript">
    jQuery(function($) {
        $('#tabs').tabs({
            ajaxOptions: {
                error: function(xhr, status, index, anchor) {
                    $(anchor.hash).html("Couldn't load this tab.");
                },
                data: {},
                success: function(data, textStatus) {
                },
            }
        });
    });
</script>
</code>```

in the page that gets loaded is a table with rows of PHP data, and jquery-ui boxes. The problem is that when I reload the tab via .tabs("load",0);, the tabi s reloading, but appending the div's that contain the Dialog's. Once for each time it's reloaded.

Here is the page that is being returned to the tab. It seems to be structurally correct (no out of place div's, etc...).

```<code><div style="height:300px;overflow:auto;width:1110px;">
    <img src="/shared/img/icons2.0/16x16/arrow_refresh.png" onclick="bug_updateList()" style="cursor:pointer" title='reload'>
</div>
<?php
$w=1;
foreach($bugs->result() as $row){
    switch($row->status){
        case 0:
         $status='<b class="stat-0">NEW</b>';
        break;
        case 1:
         $status='<b class="stat-1">REVIEW</b>';
        break;
        case 2:
         $status='<b class="stat-2">IN PROCESS</b>';
        break;
        case 3:
         $status='<b class="stat-3">TESTING</b>';
        break;
        case 4:
         $status='<b class="stat-4">COMPLETE</b>';
        break;
    }
    switch($row->importance){
        case 0:
         $import='<b class="imp-0">FEATURE</b>';
        break;
        case 1:
         $import='<b class="imp-1">VERY LOW</b>';
        break;
        case 2:
         $import='<b class="imp-2">LOW</b>';
        break;
        case 3:
         $import='<b class="imp-3">MEDIUM</b>';
        break;
        case 4:
         $import='<b class="imp-4">HIGH</b>';
        break;
        case 5:
         $import='<b class="imp-5">URGENT</b>';
        break;
    }
    $notes=$this->db->query('SELECT * FROM bugs_notes WHERE bug_id='.$row->id);
    echo"
        <div id='dialog_$w' title='$row->description'>
            <p>$row->detail</p>
            <hr>
            <fieldset><legend>Notes</legend>
            <div id='notes-$w'>";
            foreach($notes->result() as $nrow){
                echo '
                <div style="border-bottom:1px dotted #000;width:98%;padding:5px"><b>'.$nrow->user.'</b>: '.$nrow->note.'</div>';
            }
            echo "

                <hr>
                <div id='addNote'>
                    <label for='noteInput'>Add note:</label>
                    <form name='bugs_note-$w'>
                    <input type='text' id='bugs_note-$w' name='note' size='60' />
                    <input type='hidden' name='bug_id' value='$row->id' />
                    <input type='button' value='add note' onclick='bug_addNote(\"bugs_note-$w\",$row->id,\"notes-$w\")' />
                    </form>
                </div>
            </div>
            </fieldset>
            <hr>
            <fieldset><legend>Update Status</legend>
            <div id='updateStatus-$w'>
                Current status:<span id='curStatus-$w'>$status</span><br><br>
                <form name='status-radio-$w' id='status-radio-$w'>
                    <span style='border:1px dotted #666;padding:3px;margin-right:3px'>
                        <label for='radio-new-$w'>New</label>
                            <input type='radio' id='radio-new-$w' name='status' value='0'>
                    </span>
                    <span style='border:1px dotted #666;padding:3px;margin-right:3px'>
                        <label for='radio-rev-$w'>Review</label>
                            <input type='radio' id='radio-rev-$w' name='status' value='1'>
                    </span>
                    <span style='border:1px dotted #666;padding:3px;margin-right:3px'>
                        <label for='radio-proc-$w'>In process</label>
                            <input type='radio' id='radio-proc-$w' name='status' value='2'>
                    </span>
                    <span style='border:1px dotted #666;padding:3px;margin-right:3px'>
                        <label for='radio-test-$w'>Testing</label>
                            <input type='radio' id='radio-test-$w' name='status' value='3'>
                    </span>
                    <span style='border:1px dotted #666;padding:3px;margin-right:3px'>
                        <label for='radio-comp-$w'>Complete</label>
                            <input type='radio' id='radio-comp-$w' name='status' value='4'>
                    </span>
                    <input type='button' style='float:right' value='update status' onclick='bug_updateStatus(\"status-radio-$w\",$row->id,$i,\"curStatus-$w\",\"dialog_$w\")'>
                </form>
            </div>
            </fieldset>

            <fieldset><legend>Update Importance</legend>
            <div id='updateImportance-$w'>
                Current importance:<span id='curImport-$w'>$import</span><br><br>
                <form name='status-import-$w' id='status-import-$w'>
                    <span style='border:1px dotted #666;padding:3px;margin-right:3px'>
                        <label for='radio-fet-$w'>Feature</label>
                            <input type='radio' id='radio-new-$w' name='import' value='0'>
                    </span>
                    <span style='border:1px dotted #666;padding:3px;margin-right:3px'>
                        <label for='radio-vlow-$w'>Very Low</label>
                            <input type='radio' id='radio-vlow-$w' name='import' value='1'>
                    </span>
                    <span style='border:1px dotted #666;padding:3px;margin-right:3px'>
                        <label for='radio-low-$w'>Low</label>
                            <input type='radio' id='radio-low-$w' name='import' value='2'>
                    </span>
                    <span style='border:1px dotted #666;padding:3px;margin-right:3px'>
                        <label for='radio-med-$w'>Medium</label>
                            <input type='radio' id='radio-med-$w' name='import' value='3'>
                    </span>
                    <span style='border:1px dotted #666;padding:3px;margin-right:3px'>
                        <label for='radio-high-$w'>High</label>
                            <input type='radio' id='radio-high-$w' name='import' value='4'>
                    </span>
                    <span style='border:1px dotted #666;padding:3px;margin-right:3px'>
                        <label for='radio-urg-$w'>Urgent</label>
                            <input type='radio' id='radio-urg-$w' name='import' value='5'>
                    </span>
                    <input type='button' style='float:right' value='update importance' onclick='bug_updateImport(\"status-import-$w\",$row->id,$i,\"curImport-$w\",\"dialog_$w\")'>

                </form>
            </div>
            </fieldset>
            <div align='center'><br>
                <input type='button' value='delete' onclick='bug_delete($row->id,\"dialog_$w\",\"tr-$w\")'>
                <input type='button' value='close' onclick='bug_dialog_close(\"dialog_$w\")'>
                <br>asdf-dialog_$w</br>
            </div>
        </div>";
        $w++;
}
?>

<script>
<?php
$ee=1;
foreach($bugs->result() as $rr){
    echo "jQuery(\"#dialog_$ee\").dialog({autoOpen:false,width:850,height:550});\n";
    $ee++;
}
?>
</script>
</code>```

I can't for the life of me figure out why the .tabs("load",0) is appending data... Any help would be appreciated...

EDIT:

This is insanely frustrating... I've tried 3 different workarounds, including loading the listing and dialogs separately, and only refreshing whichever is appropriate. But, whenever I need to refresh the dialogs, it is appending them. I've checked the transport.responseText.length just to make sure somehow PHP wasn't spitting out more data, but it checks out. The tabs plugin is doing something to append this stuff, and I can't find out how to replace it...

答:
http://blog.nemikor.com/category/jquery-ui/jquery-ui-dialog/

I think this may be related...

Body:
I have a jquery ui tab that gets loaded via ajax and remote page:

View

Add Bug/Request

...

in the page that gets loaded is a table with rows of PHP data, and jquery-ui boxes. The problem is that when I reload the tab via .tabs("load",0);, the tabi s reloading, but appending the div's that contain the Dialog's. Once for each time it's reloaded.

Here is the page that is being returned to the tab. It seems to be structurally correct (no out of place div's, etc...).

<?php
$w=1;
foreach($bugs->result() as $row){
    switch($row->status){
        case 0:
         $status='NEW';
        break;
        case 1:
         $status='REVIEW';
        break;
        case 2:
         $status='IN PROCESS';
        break;
        case 3:
         $status='TESTING';
        break;
        case 4:
         $status='COMPLETE';
        break;
    }
    switch($row->importance){
        case 0:
         $import='FEATURE';
        break;
        case 1:
         $import='VERY LOW';
        break;
        case 2:
         $import='LOW';
        break;
        case 3:
         $import='MEDIUM';
        break;
        case 4:
         $import='HIGH';
        break;
        case 5:
         $import='URGENT';
        break;
    }
    $notes=$this->db->query('SELECT * FROM bugs_notes WHERE bug_id='.$row->id);
    echo"

description'>

$row->detail

            <fieldset><legend>Notes</legend>

";
            foreach($notes->result() as $nrow){
                echo '

'.$nrow->user.': '.$nrow->note.'
';
            }
            echo "

                    Add note:
                    <form name='bugs_note-$w'>
                    <input type='text' id='bugs_note-$w' name='note' size='60' />
                    <input type='hidden' name='bug_id' value='$row->id' />
                    <input type='button' value='add note' onclick='bug_addNote(\"bugs_note-$w\",$row->id,\"notes-$w\")' />
                    </form>

            </fieldset>

            <fieldset><legend>Update Status</legend>

                Current status:$status

                <form name='status-radio-$w' id='status-radio-$w'>

                        New
                            <input type='radio' id='radio-new-$w' name='status' value='0'>

                        Review
                            <input type='radio' id='radio-rev-$w' name='status' value='1'>

                        In process
                            <input type='radio' id='radio-proc-$w' name='status' value='2'>

                        Testing
                            <input type='radio' id='radio-test-$w' name='status' value='3'>

                        Complete
                            <input type='radio' id='radio-comp-$w' name='status' value='4'>

                    <input type='button' style='float:right' value='update status' onclick='bug_updateStatus(\"status-radio-$w\",$row->id,$i,\"curStatus-$w\",\"dialog_$w\")'>
                </form>

            </fieldset>

            <fieldset><legend>Update Importance</legend>

                Current importance:$import

                <form name='status-import-$w' id='status-import-$w'>

                        Feature
                            <input type='radio' id='radio-new-$w' name='import' value='0'>

                        Very Low
                            <input type='radio' id='radio-vlow-$w' name='import' value='1'>

                        Low
                            <input type='radio' id='radio-low-$w' name='import' value='2'>

                        Medium
                            <input type='radio' id='radio-med-$w' name='import' value='3'>

                        High
                            <input type='radio' id='radio-high-$w' name='import' value='4'>

                        Urgent
                            <input type='radio' id='radio-urg-$w' name='import' value='5'>

                    <input type='button' style='float:right' value='update importance' onclick='bug_updateImport(\"status-import-$w\",$row->id,$i,\"curImport-$w\",\"dialog_$w\")'>

                </form>

            </fieldset>

                <input type='button' value='delete' onclick='bug_delete($row->id,\"dialog_$w\",\"tr-$w\")'>
                <input type='button' value='close' onclick='bug_dialog_close(\"dialog_$w\")'>

asdf-dialog_$w

";
        $w++;
}
?>

I can't for the life of me figure out why the .tabs("load",0) is appending data... Any help would be appreciated...

EDIT:

This is insanely frustrating... I've tried 3 different workarounds, including loading the listing and dialogs separately, and only refreshing whichever is appropriate. But, whenever I need to refresh the dialogs, it is appending them. I've checked the transport.responseText.length just to make sure somehow PHP wasn't spitting out more data, but it checks out. The tabs plugin is doing something to append this stuff, and I can't find out how to replace it...