问:
insertSubview: AtIndex: does not work
I went through the material regarding this issue but still can't figure it out completely.
The main issue is that i am using this method but the view does not show...
The app is built out of two view - the main one (i added it as a subview to the main nib) -
Has of a text field where i write some text.
Has a button that when pressed, the action method loads a second view that has a label with some text in it.
the source code of the first viewController:

```<code>#import <UIKit/UIKit.h>

@class TxtRunnerViewController;

@interface Itai_s_text_app_take_2ViewController : UIViewController {
 int sliderSpeed;
 IBOutlet UITextField  *textInput;
 TxtRunnerViewController *trvc;
}

@property (nonatomic, retain) IBOutlet UITextField *textInput;
@property (retain, nonatomic) TxtRunnerViewController *trvc;

- (IBAction)sliderChanged:(id)sender;//speed of text show changed

- (IBAction)textFieldDoneEditing:(id)sender;//dor 'DONE' on keyboard
- (IBAction)backgroundTap:(id)sender;//for handling tapping on background

- (IBAction)textEmButtonPressed:(id)sender;

@end
</code>```

the .m of the first ViewController:
    #import "Itai_s_text_app_take_2ViewController.h"
    #import "TxtRunnerViewController.h"

```<code>@implementation Itai_s_text_app_take_2ViewController
@synthesize textInput;
@synthesize trvc;

- (IBAction)sliderChanged:(id)sender
{
 UISlider *slider = (UISlider *)sender;
 sliderSpeed =  (int)(slider.value + 0.5f);//setting the speed determinned by the usr in slider
 NSLog(@"Slider value is %@", sliderSpeed);
}

- (IBAction)textFieldDoneEditing:(id)sender
{
    [sender resignFirstResponder];
 NSLog(@"our text input  is %@", textInput.text);
}

- (IBAction)backgroundTap:(id)sender
{
 [textInput resignFirstResponder];
}

- (IBAction)textEmButtonPressed:(id)sender
{
 NSLog(@"button pressed");
 if ([textInput.text length]==0)
 {
  NSString *msg = nil;
  msg = @"Write text to transmit";
  UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Forgot something?"
              message:msg
                delegate:self
             cancelButtonTitle:@"Back"
             otherButtonTitles:nil];

  [alert show];
  [alert release];
  [msg release];
 }
 else { //init
  NSLog(@"HI!");
  if (self.trvc == nil)
  {
   NSLog(@"if accepted");
   TxtRunnerViewController *tr = [[TxtRunnerViewController alloc] initWithNibName:@"TxtRunner"
                       bundle:nil];
   self.trvc = tr;
   [tr release];
  }
  [self.view removeFromSuperview];
  [self.view insertSubview:trvc.view atIndex:0];
  NSLog(@"InsertAtIndex was operated...!");
  //[self.view addSubview:tvc.view];
 }

}
/*
// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
*/

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/

/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
}
*/

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
 // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

 // Release any cached data, images, etc that aren't in use.
 if(self.trvc.view.superview == nil)
  self.trvc = nil;
}

- (void)viewDidUnload {
 // Release any retained subviews of the main view.
 // e.g. self.myOutlet = nil;
}

- (void)dealloc {
 [trvc release];
    [super dealloc];
}
</code>```

The second View is simply empty (has a label added to it in it's nib file):
    #import

```<code>@interface TxtRunnerViewController : UIViewController {

}

@end
</code>```

It's .m file is the default one, added no code to it.
When i press the button in the first view - it's view disappears but the second view does not appear instead, only a blank white view appears, nothing on it.

Doe

答:
If you push the TxtRunnerViewController it will completely hide the first one, but it still exist in background. (without removeFromSuperview)

```<code>TxtRunnerViewController *vw = [[TxtRunnerViewController alloc]initWithNibName:@"TxtRunner" bundle:nil];
[self.view pushViewController:vw.view animated:NO];
[vw release];
</code>```

To remove the first view it's a bit more difficult. You would need to implement a delegate in RootViewController which will be fired after clicking the done Button of the first view. Then in your RootViewController some code is executed which displays the second view and removes the first view.

For a delegate sample open the Utility Application Sample when creating a new project and figure out how it works or search some examples online.

Title: insertSubview: AtIndex: does not work

Body:
I went through the material regarding this issue but still can't figure it out completely.
The main issue is that i am using this method but the view does not show...
The app is built out of two view - the main one (i added it as a subview to the main nib) -
Has of a text field where i write some text.
Has a button that when pressed, the action method loads a second view that has a label with some text in it.
the source code of the first viewController:

#import <UIKit/UIKit.h>

@class TxtRunnerViewController;

@interface Itai_s_text_app_take_2ViewController : UIViewController {
 int sliderSpeed;
 IBOutlet UITextField  *textInput;
 TxtRunnerViewController *trvc;
}

@property (nonatomic, retain) IBOutlet UITextField *textInput;
@property (retain, nonatomic) TxtRunnerViewController *trvc;

- (IBAction)sliderChanged:(id)sender;//speed of text show changed

- (IBAction)textFieldDoneEditing:(id)sender;//dor 'DONE' on keyboard
- (IBAction)backgroundTap:(id)sender;//for handling tapping on background

- (IBAction)textEmButtonPressed:(id)sender;

@end

the .m of the first ViewController:
    #import "Itai_s_text_app_take_2ViewController.h"
    #import "TxtRunnerViewController.h"

@implementation Itai_s_text_app_take_2ViewController
@synthesize textInput;
@synthesize trvc;

- (IBAction)sliderChanged:(id)sender
{
 UISlider *slider = (UISlider *)sender;
 sliderSpeed =  (int)(slider.value + 0.5f);//setting the speed determinned by the usr in slider
 NSLog(@"Slider value is %@", sliderSpeed);
}

- (IBAction)textFieldDoneEditing:(id)sender
{
    [sender resignFirstResponder];
 NSLog(@"our text input  is %@", textInput.text);
}

- (IBAction)backgroundTap:(id)sender
{
 [textInput resignFirstResponder];
}

- (IBAction)textEmButtonPressed:(id)sender
{
 NSLog(@"button pressed");
 if ([textInput.text length]==0)
 {
  NSString *msg = nil;
  msg = @"Write text to transmit";
  UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Forgot something?"
              message:msg
                delegate:self
             cancelButtonTitle:@"Back"
             otherButtonTitles:nil];

  [alert show];
  [alert release];
  [msg release];
 }
 else { //init
  NSLog(@"HI!");
  if (self.trvc == nil)
  {
   NSLog(@"if accepted");
   TxtRunnerViewController *tr = [[TxtRunnerViewController alloc] initWithNibName:@"TxtRunner"
                       bundle:nil];
   self.trvc = tr;
   [tr release];
  }
  [self.view removeFromSuperview];
  [self.view insertSubview:trvc.view atIndex:0];
  NSLog(@"InsertAtIndex was operated...!");
  //[self.view addSubview:tvc.view];
 }

}
/*
// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
*/

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/

/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
}
*/

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
 // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

 // Release any cached data, images, etc that aren't in use.
 if(self.trvc.view.superview == nil)
  self.trvc = nil;
}

- (void)viewDidUnload {
 // Release any retained subviews of the main view.
 // e.g. self.myOutlet = nil;
}

- (void)dealloc {
 [trvc release];
    [super dealloc];
}

The second View is simply empty (has a label added to it in it's nib file):
    #import

@interface TxtRunnerViewController : UIViewController {

}

@end

It's .m file is the default one, added no code to it.
When i press the button in the first view - it's view disappears but the second view does not appear instead, only a blank white view appears, nothing on it.

Doe

Body:
If you push the TxtRunnerViewController it will completely hide the first one, but it still exist in background. (without removeFromSuperview)

TxtRunnerViewController *vw = [[TxtRunnerViewController alloc]initWithNibName:@"TxtRunner" bundle:nil];
[self.view pushViewController:vw.view animated:NO];
[vw release];

To remove the first view it's a bit more difficult. You would need to implement a delegate in RootViewController which will be fired after clicking the done Button of the first view. Then in your RootViewController some code is executed which displays the second view and removes the first view.

For a delegate sample open the Utility Application Sample when creating a new project and figure out how it works or search some examples online.


来源: stackexchange

问:
Reduce Nested Dictionary
I am trying to sum all numbers that fall under "sales" in the following dictionary:

```<code>{'a': {'sales': {}, 'revenue': {}}, 'b': {'sales': {}, 'revenue': {}}, 'c': {'sales': {'February2017': 6240.0, 'March2017': 8869.75, 'January2017': 15720.0}, 'revenue': {'February2017': 312.0, 'March2017': 432.4, 'January2017': 786.0}}, 'd': {'sales': {'February2017': 4184.9, 'March2017': 6181.709999999999, 'January2017': 6080.55}, 'revenue': {'February2017': 188.86, 'March2017': 292.61, 'January2017': 273.45}}}
 #
</code>```

The output should be: 6240 + 8869.75 + 15720 + 4184.9 + 6181.7099 + 6080.55

I am able to cycle through the keys one by one and get the right answer but is there a more efficient way to do this?

```<code>total_sum = 0
for key,value in dict.items():
    for key_a, value_a in value['sales'].items():
        total_sum += value_a
</code>```

For example, is there a way I can do this by using something like reduce?

Thanks

答:
Why reduce() when you can sum() with a generator expression, e.g.:

```<code>>>> sum(sum(value['sales'].values()) for value in data.values())
47276.91
</code>```

Or alternatively in nested form:

```<code>>>> sum(n for value in data.values() for n in value['sales'].values())
47276.91
</code>```

Note: you shouldn't call your variable dict as it hides python's builtin dict type.

ContentLicense: CC BY-SA 3.0

Title: Reduce Nested Dictionary

Body:
I am trying to sum all numbers that fall under "sales" in the following dictionary:

{'a': {'sales': {}, 'revenue': {}}, 'b': {'sales': {}, 'revenue': {}}, 'c': {'sales': {'February2017': 6240.0, 'March2017': 8869.75, 'January2017': 15720.0}, 'revenue': {'February2017': 312.0, 'March2017': 432.4, 'January2017': 786.0}}, 'd': {'sales': {'February2017': 4184.9, 'March2017': 6181.709999999999, 'January2017': 6080.55}, 'revenue': {'February2017': 188.86, 'March2017': 292.61, 'January2017': 273.45}}}
 #

The output should be: 6240 + 8869.75 + 15720 + 4184.9 + 6181.7099 + 6080.55

I am able to cycle through the keys one by one and get the right answer but is there a more efficient way to do this?

total_sum = 0
for key,value in dict.items():
    for key_a, value_a in value['sales'].items():
        total_sum += value_a

For example, is there a way I can do this by using something like reduce?

Thanks

Body:
Why reduce() when you can sum() with a generator expression, e.g.:

>>> sum(sum(value['sales'].values()) for value in data.values())
47276.91

Or alternatively in nested form:

>>> sum(n for value in data.values() for n in value['sales'].values())
47276.91

Note: you shouldn't call your variable dict as it hides python's builtin dict type.


问:
How to have a dynamic DataTemplateSelector
I have an observable collection that I am displaying in a Xamarin Forms ListView.  I have defined a detail and a summary template that I use to view each list item.  I want to be able to dynamically change between summary and detail template based on a Boolean property in each item.

Here is the item.

```<code>public class MyItem : INotifyPropertyChanged
{
    bool _switch = false;
    public bool Switch
    {
        get
        {
            return _switch;
        }
        set
        {
            if (_switch != value)
            {
                _switch = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Switch"));
            }
        }

    }
    public int Addend1 { get; set; }
    public int Addend2 { get; set; }
    public int Result
    {
        get
        {
            return Addend1 + Addend2;
        }
    }
    public string Summary
    {
        get
        {
            return Addend1 + " + " + Addend2 + " = " + Result;
        }
    }
    public event PropertyChangedEventHandler PropertyChanged;
}
</code>```

Here is the observable collection.  Note that whenever the switch value changes I remove the item and reinsert.  The reason this is done is to force the ListView to reselect the DataTemplate.

```<code>public class MyItems : ObservableCollection<MyItem>
{
    protected override void InsertItem(int index, MyItem item)
    {
        item.PropertyChanged += MyItems_PropertyChanged;
        base.InsertItem(index, item);
    }
    protected override void RemoveItem(int index)
    {
        this[index].PropertyChanged -= MyItems_PropertyChanged;
        base.RemoveItem(index);
    }
    private void MyItems_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
    {
        int index = IndexOf(sender as MyItem);
        if(index >= 0)
        {
            RemoveAt(index);
            Insert(index, sender as MyItem);
        }
    }
}
</code>```

Here is my data template selector...

```<code>public class MyItemTemplateSelector : DataTemplateSelector
{
    DataTemplate Detail { get; set; }
    DataTemplate Summary { get; set; }

    protected override DataTemplate OnSelectTemplate(object item, BindableObject container)
    {
        if(item is MyItem)
        {
            return (item as MyItem).Switch ? Detail : Summary;
        }
        return null;
    }
}
</code>```

Here are my resource definitions...

```<code>        <DataTemplate x:Key="MyDetail">
            <ViewCell>
                <StackLayout Orientation="Horizontal">
                    <Switch IsToggled="{Binding Switch}"/>
                    <Entry Text="{Binding Addend1}"/>
                    <Entry Text="{Binding Addend2}"/>
                    <Label Text="{Binding Result}"/>
                </StackLayout>
            </ViewCell>
        </DataTemplate>
        <DataTemplate x:Key="MySummary">
            <ViewCell>
                <StackLayout Orientation="Horizontal">
                    <Switch IsToggled="{Binding Switch}"/>
                    <Label Text="{Binding Summary}" VerticalOptions="Center"/>
                </StackLayout>
            </ViewCell>
        </DataTemplate>
        <local:MyItemTemplateSelector x:Key="MySelector" Detail="{StaticResource MyDetail}" Summary="{StaticResource MySummary}"/>
</code>```

Here is my collection initialization...

```<code>        MyItems = new MyItems();
        MyItems.Add(new MyItem() { Switch = true, Addend1 = 1, Addend2 = 2 });
        MyItems.Add(new MyItem() { Switch = false, Addend1 = 1, Addend2 = 2 });
        MyItems.Add(new MyItem() { Switch = true, Addend1 = 2, Addend2 = 3 });
        MyItems.Add(new MyItem() { Switch = false, Addend1 = 2, Addend2 = 3 });
</code>```

And this is what it looks like...

Right.  So everything works fine. If the switch is toggled the view of the item changes from summary to detail.  The problem is that this cannot be the right way of doing this!  It is a complete kluge to remove a list item and put it back in the same place in order to get the data template to reselect.  But I cannot figure out another way of doing it.  In WPF I used a data trigger in an item container style to set the content template based on the switch value, but there seems to be no way to do the equivalent thing in Xamarin.

答:
This was tricky issue for me few years ago. I've came to MarkupExtensions and converters (IValueConverter). After heavy struggle with XAML extensions realm I've figured an obvious thing: it shouldn't be done like that.

For dynamic change of (m)any property(ies) of the component you should use Styles. Reactions of property (it has to be DependencyProperty to work with components) changes are simple to set via Stryle.Triggers and Setters.

```<code><Style x:Key="imbXmlTreeView_itemstyle" TargetType="TreeViewItem">
    <Setter Property="Margin" Value="-23,0,0,0" />
    <Setter Property="Padding" Value="1" />
    <Setter Property="Panel.Margin" Value="0"/>
    <Style.Triggers>
        <Trigger Property="IsSelected" Value="True">
            <Setter Property="Background" Value="{DynamicResource fade_lightGray}" />
            <Setter Property="Foreground"  Value="{DynamicResource fade_darkGray}" />
        </Trigger>
        <Trigger Property="IsSelected" Value="False">
            <Setter Property="Background" Value="{DynamicResource fade_lightGray}" />
            <Setter Property="Foreground" Value="{DynamicResource fade_darkGray}" />
        </Trigger>
    </Style.Triggers>
</Style>
</code>```

Consider above (just copied from my old project): DynamicResource can be your DataTemplate.

Here is more accurate example you might use:

```<code><Style x:Key="executionFlowBorder" TargetType="ContentControl" >
        <Setter Property="Margin" Value="5" />
        <Setter Property="ContentTemplate" >
            <Setter.Value>
                <DataTemplate>
                    <StackPanel Orientation="Vertical">
                    <Border Style="{DynamicResource executionBorder}" DataContext="{Binding}">
                        <Grid>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="20" />
                                <ColumnDefinition Width="1*"/>
                                <ColumnDefinition Width="20" />
                            </Grid.ColumnDefinitions>
                            <CheckBox IsChecked="{Binding Path=isExecuting}" Content="" Grid.Column="0" VerticalAlignment="Center"/>
                            <Label Content="{Binding Path=displayName, Mode=OneWay}" FontSize="10" Grid.Column="1" FontStretch="Expanded"  FontWeight="Black"/>
                            <Image Source="{Binding Path=iconSource, Mode=OneWay}" Width="16" Height="16" Grid.Column="2" HorizontalAlignment="Right" Margin="0,0,5,0"/>
                        </Grid>
                    </Border>
                    <Label Content="{Binding Path=displayComment, Mode=OneWay}" FontSize="9" HorizontalAlignment="Left"/>
                    </StackPanel>
                </DataTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</code>```

Where the value of setter can be DynamicResource or one delivered via your MarkupExtension - some thing like I had here:

```<code>using System;
    using System.Windows;
    using System.Windows.Markup;

    #endregion

    /// <summary>
    /// Pristup glavnom registru resursa
    /// </summary>
    [MarkupExtensionReturnType(typeof (ResourceDictionary))]
    public class masterResourceExtension : MarkupExtension
    {
        public masterResourceExtension()
        {
        }

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            try
            {
                return imbXamlResourceManager.current.masterResourceDictionary;
            }
            catch
            {
                return null;
            }
        }
    }
</code>```

The MarkupExtensions you are using as in example below:
In the XAML code:

```<code><Image Grid.Row="1" Name="image_splash" Source="{imb:imbImageSource ImageName=splash}" Stretch="Fill" />
</code>```

Added later: just don't forget to add namespace/assembly reference (pointing to the code with the custom MarkupExtension) at top of the XAML Window/Control (in this example it is imbCore.xaml from separate library project of the same solution):

```<code><Window x:Class="imbAPI.imbDialogs.imbSplash"
        xmlns:imb="clr-namespace:imbCore.xaml;assembly=imbCore"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="{Binding Path=splashTitle}" Height="666" Width="896" ResizeMode="NoResize" WindowStyle="ToolWindow" Topmost="False" WindowStartupLocation="CenterScreen"
        xmlns:imbControls="clr-namespace:imbAPI.imbControls">
    <Grid>
</code>```

Also have in mind you have to compile it first in order to get it working in XAML designer.

The C# code of the extension used:

```<code> using System;
    using System.Windows.Markup;
    using System.Windows.Media;
    using imbCore.resources;

    #endregion

    [MarkupExtensionReturnType(typeof (ImageSource))]
    public class imbImageSourceExtension : MarkupExtension
    {
        public imbImageSourceExtension()
        {
        }

        public imbImageSourceExtension(String imageName)
        {
            this.ImageName = imageName;
        }

        [ConstructorArgument("imageName")]
        public String ImageName { get; set; }

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            try
            {

                if (imbCoreApplicationSettings.doDisableIconWorks) return null;
                return imbIconWorks.getIconSource(ImageName);

            }
            catch
            {
                return null;
            }
        }
    }
</code>```

Hope I got your question right on the first place :).
Now I have to sleap :). Good luck!

Added later: ok, I missed your point :) sorry. However, I would leave the response in case you find something useful in the codes I've posted. Bye!

Body:
I have an observable collection that I am displaying in a Xamarin Forms ListView.  I have defined a detail and a summary template that I use to view each list item.  I want to be able to dynamically change between summary and detail template based on a Boolean property in each item.

Here is the item.

public class MyItem : INotifyPropertyChanged
{
    bool _switch = false;
    public bool Switch
    {
        get
        {
            return _switch;
        }
        set
        {
            if (_switch != value)
            {
                _switch = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Switch"));
            }
        }

    }
    public int Addend1 { get; set; }
    public int Addend2 { get; set; }
    public int Result
    {
        get
        {
            return Addend1 + Addend2;
        }
    }
    public string Summary
    {
        get
        {
            return Addend1 + " + " + Addend2 + " = " + Result;
        }
    }
    public event PropertyChangedEventHandler PropertyChanged;
}

Here is the observable collection.  Note that whenever the switch value changes I remove the item and reinsert.  The reason this is done is to force the ListView to reselect the DataTemplate.

public class MyItems : ObservableCollection<MyItem>
{
    protected override void InsertItem(int index, MyItem item)
    {
        item.PropertyChanged += MyItems_PropertyChanged;
        base.InsertItem(index, item);
    }
    protected override void RemoveItem(int index)
    {
        this[index].PropertyChanged -= MyItems_PropertyChanged;
        base.RemoveItem(index);
    }
    private void MyItems_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
    {
        int index = IndexOf(sender as MyItem);
        if(index >= 0)
        {
            RemoveAt(index);
            Insert(index, sender as MyItem);
        }
    }
}

Here is my data template selector...

public class MyItemTemplateSelector : DataTemplateSelector
{
    DataTemplate Detail { get; set; }
    DataTemplate Summary { get; set; }

    protected override DataTemplate OnSelectTemplate(object item, BindableObject container)
    {
        if(item is MyItem)
        {
            return (item as MyItem).Switch ? Detail : Summary;
        }
        return null;
    }
}

Here are my resource definitions...

        <DataTemplate x:Key="MyDetail">
            <ViewCell>
                <StackLayout Orientation="Horizontal">
                    <Switch IsToggled="{Binding Switch}"/>
                    <Entry Text="{Binding Addend1}"/>
                    <Entry Text="{Binding Addend2}"/>

                </StackLayout>
            </ViewCell>
        </DataTemplate>
        <DataTemplate x:Key="MySummary">
            <ViewCell>
                <StackLayout Orientation="Horizontal">
                    <Switch IsToggled="{Binding Switch}"/>

                </StackLayout>
            </ViewCell>
        </DataTemplate>
        <local:MyItemTemplateSelector x:Key="MySelector" Detail="{StaticResource MyDetail}" Summary="{StaticResource MySummary}"/>

Here is my collection initialization...

        MyItems = new MyItems();
        MyItems.Add(new MyItem() { Switch = true, Addend1 = 1, Addend2 = 2 });
        MyItems.Add(new MyItem() { Switch = false, Addend1 = 1, Addend2 = 2 });
        MyItems.Add(new MyItem() { Switch = true, Addend1 = 2, Addend2 = 3 });
        MyItems.Add(new MyItem() { Switch = false, Addend1 = 2, Addend2 = 3 });

And this is what it looks like...

Right.  So everything works fine. If the switch is toggled the view of the item changes from summary to detail.  The problem is that this cannot be the right way of doing this!  It is a complete kluge to remove a list item and put it back in the same place in order to get the data template to reselect.  But I cannot figure out another way of doing it.  In WPF I used a data trigger in an item container style to set the content template based on the switch value, but there seems to be no way to do the equivalent thing in Xamarin.

Body:
This was tricky issue for me few years ago. I've came to MarkupExtensions and converters (IValueConverter). After heavy struggle with XAML extensions realm I've figured an obvious thing: it shouldn't be done like that.

For dynamic change of (m)any property(ies) of the component you should use Styles. Reactions of property (it has to be DependencyProperty to work with components) changes are simple to set via Stryle.Triggers and Setters.

<Style x:Key="imbXmlTreeView_itemstyle" TargetType="TreeViewItem">
    <Setter Property="Margin" Value="-23,0,0,0" />
    <Setter Property="Padding" Value="1" />
    <Setter Property="Panel.Margin" Value="0"/>
    <Style.Triggers>
        <Trigger Property="IsSelected" Value="True">
            <Setter Property="Background" Value="{DynamicResource fade_lightGray}" />
            <Setter Property="Foreground"  Value="{DynamicResource fade_darkGray}" />
        </Trigger>
        <Trigger Property="IsSelected" Value="False">
            <Setter Property="Background" Value="{DynamicResource fade_lightGray}" />
            <Setter Property="Foreground" Value="{DynamicResource fade_darkGray}" />
        </Trigger>
    </Style.Triggers>
</Style>

Consider above (just copied from my old project): DynamicResource can be your DataTemplate.

Here is more accurate example you might use:

<Style x:Key="executionFlowBorder" TargetType="ContentControl" >
        <Setter Property="Margin" Value="5" />
        <Setter Property="ContentTemplate" >
            <Setter.Value>
                <DataTemplate>
                    <StackPanel Orientation="Vertical">
                    <Border Style="{DynamicResource executionBorder}" DataContext="{Binding}">
                        <Grid>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="20" />
                                <ColumnDefinition Width="1*"/>
                                <ColumnDefinition Width="20" />
                            </Grid.ColumnDefinitions>
                            <CheckBox IsChecked="{Binding Path=isExecuting}" Content="" Grid.Column="0" VerticalAlignment="Center"/>
                            <Label Content="{Binding Path=displayName, Mode=OneWay}" FontSize="10" Grid.Column="1" FontStretch="Expanded"  FontWeight="Black"/>
                            <Image Source="{Binding Path=iconSource, Mode=OneWay}" Width="16" Height="16" Grid.Column="2" HorizontalAlignment="Right" Margin="0,0,5,0"/>
                        </Grid>
                    </Border>
                    <Label Content="{Binding Path=displayComment, Mode=OneWay}" FontSize="9" HorizontalAlignment="Left"/>
                    </StackPanel>
                </DataTemplate>
            </Setter.Value>
        </Setter>
    </Style>

Where the value of setter can be DynamicResource or one delivered via your MarkupExtension - some thing like I had here:

using System;
    using System.Windows;
    using System.Windows.Markup;

    #endregion

    /// <summary>
    /// Pristup glavnom registru resursa
    /// </summary>
    [MarkupExtensionReturnType(typeof (ResourceDictionary))]
    public class masterResourceExtension : MarkupExtension
    {
        public masterResourceExtension()
        {
        }

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            try
            {
                return imbXamlResourceManager.current.masterResourceDictionary;
            }
            catch
            {
                return null;
            }
        }
    }

The MarkupExtensions you are using as in example below:
In the XAML code:

<Image Grid.Row="1" Name="image_splash" Source="{imb:imbImageSource ImageName=splash}" Stretch="Fill" />

Added later: just don't forget to add namespace/assembly reference (pointing to the code with the custom MarkupExtension) at top of the XAML Window/Control (in this example it is imbCore.xaml from separate library project of the same solution):

<Window x:Class="imbAPI.imbDialogs.imbSplash"
        xmlns:imb="clr-namespace:imbCore.xaml;assembly=imbCore"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="{Binding Path=splashTitle}" Height="666" Width="896" ResizeMode="NoResize" WindowStyle="ToolWindow" Topmost="False" WindowStartupLocation="CenterScreen"
        xmlns:imbControls="clr-namespace:imbAPI.imbControls">
    <Grid>

Also have in mind you have to compile it first in order to get it working in XAML designer.

The C# code of the extension used:

 using System;
    using System.Windows.Markup;
    using System.Windows.Media;
    using imbCore.resources;

    #endregion

    [MarkupExtensionReturnType(typeof (ImageSource))]
    public class imbImageSourceExtension : MarkupExtension
    {
        public imbImageSourceExtension()
        {
        }

        public imbImageSourceExtension(String imageName)
        {
            this.ImageName = imageName;
        }

        [ConstructorArgument("imageName")]
        public String ImageName { get; set; }

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            try
            {

                if (imbCoreApplicationSettings.doDisableIconWorks) return null;
                return imbIconWorks.getIconSource(ImageName);

            }
            catch
            {
                return null;
            }
        }
    }

Hope I got your question right on the first place :).
Now I have to sleap :). Good luck!

Added later: ok, I missed your point :) sorry. However, I would leave the response in case you find something useful in the codes I've posted. Bye!


问:
Google IAP Public Keys Expiry?
This page provides public keys to decrypt headers from Google's Identity Aware Proxy. Making a request to the page provides its own set of headers, one of which is Expires (it contains a datetime).

What does the expiration date actually mean? I have noticed it fluctuating occasionally, and have not noticed the public keys changing at the expiry time.

I have read about Securing Your App With Signed Headers, and it goes over how to fetch the keys after every key ID mismatch, but I am looking to make a more efficient cache that can fetch the keys less often based on the expiry time.

Here are all the headers from the public keys page:

```<code>Accept-Ranges →bytes
Age →1358
Alt-Svc →quic=":443"; ma=2592000; v="39,38,37,36,35"
Cache-Control →public, max-age=3000
Content-Encoding →gzip
Content-Length →519
Content-Type →text/html
Date →Thu, 29 Jun 2017 14:46:55 GMT
Expires →Thu, 29 Jun 2017 15:36:55 GMT
Last-Modified →Thu, 29 Jun 2017 04:46:21 GMT
Server →sffe
Vary →Accept-Encoding
X-Content-Type-Options →nosniff
X-XSS-Protection →1; mode=block
</code>```

答:
The Expires header controls how long HTTP caches are supposed to hold onto that page. We didn't bother giving Google's content-serving infrastructure any special instructions for the keyfile, so whatever you're seeing there is the default value.

Is there a reason the "refresh the keyfile on lookup failure" approach isn't a good fit for your application? I'm not sure you'll be able to do any better than that, since:

Unless there's a bug or problem, you should never get a key lookup failure.

Even if you did have some scheduled key fetch, it'd probably still be advisable to refresh the keyfile on lookup failure as a fail-safe.

We don't currently rotate the keys super-frequently, though that could change in the future (which is why we don't publish the rotation interval), so it shouldn't be a significant source of load. Are you observing that refreshing the keys is impacting you?

--Matthew, Google Cloud IAP engineer

Title: Google IAP Public Keys Expiry?

Body:
This page provides public keys to decrypt headers from Google's Identity Aware Proxy. Making a request to the page provides its own set of headers, one of which is Expires (it contains a datetime).

What does the expiration date actually mean? I have noticed it fluctuating occasionally, and have not noticed the public keys changing at the expiry time.

I have read about Securing Your App With Signed Headers, and it goes over how to fetch the keys after every key ID mismatch, but I am looking to make a more efficient cache that can fetch the keys less often based on the expiry time.

Here are all the headers from the public keys page:

Accept-Ranges →bytes
Age →1358
Alt-Svc →quic=":443"; ma=2592000; v="39,38,37,36,35"
Cache-Control →public, max-age=3000
Content-Encoding →gzip
Content-Length →519
Content-Type →text/html
Date →Thu, 29 Jun 2017 14:46:55 GMT
Expires →Thu, 29 Jun 2017 15:36:55 GMT
Last-Modified →Thu, 29 Jun 2017 04:46:21 GMT
Server →sffe
Vary →Accept-Encoding
X-Content-Type-Options →nosniff
X-XSS-Protection →1; mode=block


问:
Running Wildfly Swarm with KeyCloak on docker image
I created small Wildfly Swarm application with KeyCloak server using WildFly Swarm Project Generator I Added some code, built and started my fat jar using:

```<code>java -jar -Dswarm.port.offset=100 login-service-swarm.jar
</code>```

After app stared i created new realm added users etc. Then I noticed keycloak created 3 files in my target folders. Those files where:

keycloak.h2.db

keycloak.lock.db

keycloak.trace.db

Then I decided to create docker images and run it in local docker enviroment. So I created docker file:

```<code>FROM java:openjdk-8-jdk
ADD login-service-swarm.jar /opt/login-service-swarm.jar
ADD keycloak.h2.db /opt/keycloak.h2.db
ADD keycloak.lock.db /opt/keycloak.lock.db
ADD keycloak.trace.db /opt/keycloak.trace.db

EXPOSE 8180
ENTRYPOINT ["java", "-jar", "-Dswarm.port.offset=100", "/opt/login-service-swarm.jar"]
</code>```

Built image using:

```<code>docker build -f Dockerfile -t login-service-swarm-v1 .
</code>```

And image is visible in my docker image list:

```<code>   C:\Work\Java\login-service\docker>docker images
REPOSITORY                   TAG                 IMAGE ID            CREATED              SIZE
login-service-swarm-v1       latest              710cddc59623        About a minute ago   790 MB
<none>                       <none>              100c0ee60f25        3 hours ago          779 MB
demo                         latest              03d12d49ba5e        4 hours ago          760 MB
java                         openjdk-8-jdk       d23bdf5b1b1b        5 months ago         643 MB
</code>```

So I started it using:

```<code>docker run -p 8180:8180 login-service-swarm-v1
</code>```

And it stared ok but when i go to localhost:8180/auth and try to login i get wrong username and password message so I'm unable to login to keycloak. So I wonder why is this? Because I manuayl included
keycloak database files in docker image and if I run following commands you can see all files are there as expected.

```<code>PS C:\> docker ps
CONTAINER ID        IMAGE                        COMMAND                  CREATED             STATUS              PORTS                    NAMES
8bb4bdb3945e        login-service-swarm-v1       "java -jar -Dswarm..."   2 minutes ago       Up 2 minutes        0.0.0.0:8180->8180/tcp   blissful_knuth
PS C:\> docker exec -it 8bb4bdb3945e bash
root@8bb4bdb3945e:/# ls
bin  boot  dev  etc  home  keycloak.h2.db  keycloak.lock.db  keycloak.trace.db  lib  lib64  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
root@8bb4bdb3945e:/# cd opt
root@8bb4bdb3945e:/opt# ls
keycloak.h2.db  keycloak.lock.db  keycloak.trace.db  login-service-swarm.jar
</code>```

So where is the catch??

答:
It looks like the Swarm Keycloak Server reads the keycloak*.db in the dir executed java(means user.dir) in default. The swarm process in container doesn't read /opt/keycloak*.db because java runs on /.

You can change the data dir with wildfly.swarm.keycloak.server.db sysprop.
https://github.com/wildfly-swarm/wildfly-swarm/blob/2017.6.1/fractions/keycloak-server/src/main/java/org/wildfly/swarm/keycloak/server/runtime/KeycloakDatasourceCustomizer.java#L52

Please give it a try in Dockerfile;

```<code>ENTRYPOINT ["java", "-jar", "/opt/login-service-swarm.jar", "-Dwildfly.swarm.keycloak.server.db=/opt/keycloak"]
</code>```

Or, you can also use -w option with docker run.

```<code>$ docker run --help
-w, --workdir string              Working directory inside the container
</code>```

The following command is supposed to work as well.

```<code>docker run -p 8180:8180 -w /opt login-service-swarm-v1
</code>```

P.S.

I recommend using Volume or Volume Container instead of adding the data files in Dockerfile.
https://docs.docker.com/engine/tutorials/dockervolumes/

Body:
I created small Wildfly Swarm application with KeyCloak server using WildFly Swarm Project Generator I Added some code, built and started my fat jar using:

java -jar -Dswarm.port.offset=100 login-service-swarm.jar

After app stared i created new realm added users etc. Then I noticed keycloak created 3 files in my target folders. Those files where:

keycloak.h2.db

keycloak.lock.db

keycloak.trace.db

Then I decided to create docker images and run it in local docker enviroment. So I created docker file:

FROM java:openjdk-8-jdk
ADD login-service-swarm.jar /opt/login-service-swarm.jar
ADD keycloak.h2.db /opt/keycloak.h2.db
ADD keycloak.lock.db /opt/keycloak.lock.db
ADD keycloak.trace.db /opt/keycloak.trace.db

EXPOSE 8180
ENTRYPOINT ["java", "-jar", "-Dswarm.port.offset=100", "/opt/login-service-swarm.jar"]

Built image using:

docker build -f Dockerfile -t login-service-swarm-v1 .

And image is visible in my docker image list:

   C:\Work\Java\login-service\docker>docker images
REPOSITORY                   TAG                 IMAGE ID            CREATED              SIZE
login-service-swarm-v1       latest              710cddc59623        About a minute ago   790 MB
<none>                       <none>              100c0ee60f25        3 hours ago          779 MB
demo                         latest              03d12d49ba5e        4 hours ago          760 MB
java                         openjdk-8-jdk       d23bdf5b1b1b        5 months ago         643 MB

So I started it using:

docker run -p 8180:8180 login-service-swarm-v1

And it stared ok but when i go to localhost:8180/auth and try to login i get wrong username and password message so I'm unable to login to keycloak. So I wonder why is this? Because I manuayl included
keycloak database files in docker image and if I run following commands you can see all files are there as expected.

PS C:\> docker ps
CONTAINER ID        IMAGE                        COMMAND                  CREATED             STATUS              PORTS                    NAMES
8bb4bdb3945e        login-service-swarm-v1       "java -jar -Dswarm..."   2 minutes ago       Up 2 minutes        0.0.0.0:8180->8180/tcp   blissful_knuth
PS C:\> docker exec -it 8bb4bdb3945e bash
root@8bb4bdb3945e:/# ls
bin  boot  dev  etc  home  keycloak.h2.db  keycloak.lock.db  keycloak.trace.db  lib  lib64  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
root@8bb4bdb3945e:/# cd opt
root@8bb4bdb3945e:/opt# ls
keycloak.h2.db  keycloak.lock.db  keycloak.trace.db  login-service-swarm.jar

So where is the catch??

Body:
It looks like the Swarm Keycloak Server reads the keycloak*.db in the dir executed java(means user.dir) in default. The swarm process in container doesn't read /opt/keycloak*.db because java runs on /.

You can change the data dir with wildfly.swarm.keycloak.server.db sysprop.
https://github.com/wildfly-swarm/wildfly-swarm/blob/2017.6.1/fractions/keycloak-server/src/main/java/org/wildfly/swarm/keycloak/server/runtime/KeycloakDatasourceCustomizer.java#L52

Please give it a try in Dockerfile;

ENTRYPOINT ["java", "-jar", "/opt/login-service-swarm.jar", "-Dwildfly.swarm.keycloak.server.db=/opt/keycloak"]

Or, you can also use -w option with docker run.

$ docker run --help
-w, --workdir string              Working directory inside the container

The following command is supposed to work as well.

docker run -p 8180:8180 -w /opt login-service-swarm-v1

P.S.

I recommend using Volume or Volume Container instead of adding the data files in Dockerfile.
https://docs.docker.com/engine/tutorials/dockervolumes/


问:
R - Comparing strings that are similar but not identical
I have a data set that contains the sender's name and/or sender's email address.

```<code>sender_info = c('Kelvin [mailto:kelvin0354@gmail.com]','Kelvin','Sheryl [mailto:sheryl@hotmail.com]','Sheryl <sheryl@hotmail.com>','Oscar',)
</code>```

I want to check for the number of unique senders. As you can tell from sender_info, there are 3 unique senders - Kelvin, Sheryl and Oscar.

I tried implementing a couple of methods but they don't work. One of it involves the use of the levenshteinSim() function from the R RecordLinkage library to check for how similar each of the elements are. However, this method fails when the elements are too different (eg. 'Kelvin [mailto:kelvin0354@gmail.com]' and 'Kelvin').

I would really appreciate if anyone can give me a hint or two on how to solve this problem. Thank you!

答:
If your data structure is always like the mentioned sample, these codes would help:</p>

```<code>    sender_info = c('Kelvin [mailto:kelvin0354@gmail.com]','Kelvin','Sheryl [mailto:sheryl@hotmail.com]','Sheryl <sheryl@hotmail.com>','Oscar')
    new_sender <- sapply(strsplit(sender_info, split = " "), "[[", 1)
    unique(new_sender)
    #[1] "Kelvin" "Sheryl" "Oscar"
</code>```

Body:
I have a data set that contains the sender's name and/or sender's email address.

sender_info = c('Kelvin [mailto:kelvin0354@gmail.com]','Kelvin','Sheryl [mailto:sheryl@hotmail.com]','Sheryl <sheryl@hotmail.com>','Oscar',)

I want to check for the number of unique senders. As you can tell from sender_info, there are 3 unique senders - Kelvin, Sheryl and Oscar.

I tried implementing a couple of methods but they don't work. One of it involves the use of the levenshteinSim() function from the R RecordLinkage library to check for how similar each of the elements are. However, this method fails when the elements are too different (eg. 'Kelvin [mailto:kelvin0354@gmail.com]' and 'Kelvin').

I would really appreciate if anyone can give me a hint or two on how to solve this problem. Thank you!

Body:
If your data structure is always like the mentioned sample, these codes would help:

    sender_info = c('Kelvin [mailto:kelvin0354@gmail.com]','Kelvin','Sheryl [mailto:sheryl@hotmail.com]','Sheryl <sheryl@hotmail.com>','Oscar')
    new_sender <- sapply(strsplit(sender_info, split = " "), "[[", 1)
    unique(new_sender)
    #[1] "Kelvin" "Sheryl" "Oscar"


问:
Accessing Field Settings of Pivot Table using Apache POI
I am creating a workbook with a sheet populated data from a data source then creating a second sheet with a pivot table view of that data. Everything works fine, but I can't seem to change the default look of the pivot table. I am trying to get the setting ( Row Labels-->Click one from the list-->Field Settings-->Subtotals-->None  and Row Labels-->Click one from the list-->Field Settings-->Layout & Print-->'Show item labels in tabular form' ) checked while creating the pivot table but couldn't find the handle / flag in the POI. Tried finding something under pivotTable.getCTPivotTableDefinition() or pivotTable.getCTPivotTableDefinition().getPivotTableStyleInfo(), but no lock. Please advise if there is a way to set these settings using poi during pivot table creation, not after the fact following the steps mentioned in the parenthesis. Here is my pivot table code :</p>

```<code>XSSFSheet sheet = (XSSFSheet)wb.createSheet("Data");
...
...
//filling data sheet, skipping this part as it's not relevant
...
XSSFSheet pivotSheet = (XSSFSheet)wb.createSheet("Pivot Table");
AreaReference source = new AreaReference(sheet.getSheetName()+"!A$1:W$"+String.valueOf(sheet.getLastRowNum()));
CellReference position = new CellReference("A3");
XSSFPivotTable pivotTable = pivotSheet.createPivotTable(source, position);

        /* Add filters */
        pivotTable.addRowLabel(17);
        pivotTable.addRowLabel(20);
        pivotTable.addRowLabel(21);
        pivotTable.addRowLabel(22);
        pivotTable.addRowLabel(13);
        pivotTable.addRowLabel(19);
        pivotTable.addRowLabel(6);
        pivotTable.addRowLabel(0);
        pivotTable.addRowLabel(18);
        pivotTable.addRowLabel(1);
        pivotTable.addRowLabel(7);
        pivotTable.addRowLabel(9);
</code>```

答:
@ninjaxelite here how it goes :</p>

```<code>       List<Object[]> resultSet = //get raw data

        XSSFWorkbook wb = null;
        try {
            wb = new XSSFWorkbook(new FileInputStream(this.getClass().getResource("/content/XLS_template.xlsx").getPath()));
        } catch (FileNotFoundException e1) {
            //error
        } catch (IOException e1) {
            //error
        }

        Map<String, CellStyle> styles = createStyles(wb); // some local function to get styles
        XSSFSheet sheet = (XSSFSheet)wb.getSheetAt(0);

        XSSFRow row;
        XSSFCell cell;
        int rowNum = 0;
        for (Object[] aRow : resultSet) {
            rowNum++;
            row = sheet.createRow(rowNum);

            cell = row.createCell(0);
            cell.setCellValue((String)aRow[0]);
            cell.setCellStyle(styles.get("cell_normal_centered"));

             ...
             ..
             .
</code>```

Body:
I am creating a workbook with a sheet populated data from a data source then creating a second sheet with a pivot table view of that data. Everything works fine, but I can't seem to change the default look of the pivot table. I am trying to get the setting ( Row Labels-->Click one from the list-->Field Settings-->Subtotals-->None  and Row Labels-->Click one from the list-->Field Settings-->Layout & Print-->'Show item labels in tabular form' ) checked while creating the pivot table but couldn't find the handle / flag in the POI. Tried finding something under pivotTable.getCTPivotTableDefinition() or pivotTable.getCTPivotTableDefinition().getPivotTableStyleInfo(), but no lock. Please advise if there is a way to set these settings using poi during pivot table creation, not after the fact following the steps mentioned in the parenthesis. Here is my pivot table code :

XSSFSheet sheet = (XSSFSheet)wb.createSheet("Data");
...
...
//filling data sheet, skipping this part as it's not relevant
...
XSSFSheet pivotSheet = (XSSFSheet)wb.createSheet("Pivot Table");
AreaReference source = new AreaReference(sheet.getSheetName()+"!A$1:W$"+String.valueOf(sheet.getLastRowNum()));
CellReference position = new CellReference("A3");
XSSFPivotTable pivotTable = pivotSheet.createPivotTable(source, position);

        /* Add filters */
        pivotTable.addRowLabel(17);
        pivotTable.addRowLabel(20);
        pivotTable.addRowLabel(21);
        pivotTable.addRowLabel(22);
        pivotTable.addRowLabel(13);
        pivotTable.addRowLabel(19);
        pivotTable.addRowLabel(6);
        pivotTable.addRowLabel(0);
        pivotTable.addRowLabel(18);
        pivotTable.addRowLabel(1);
        pivotTable.addRowLabel(7);
        pivotTable.addRowLabel(9);

Body:
@ninjaxelite here how it goes :

       List<Object[]> resultSet = //get raw data

        XSSFWorkbook wb = null;
        try {
            wb = new XSSFWorkbook(new FileInputStream(this.getClass().getResource("/content/XLS_template.xlsx").getPath()));
        } catch (FileNotFoundException e1) {
            //error
        } catch (IOException e1) {
            //error
        }

        Map<String, CellStyle> styles = createStyles(wb); // some local function to get styles
        XSSFSheet sheet = (XSSFSheet)wb.getSheetAt(0);

        XSSFRow row;
        XSSFCell cell;
        int rowNum = 0;
        for (Object[] aRow : resultSet) {
            rowNum++;
            row = sheet.createRow(rowNum);

            cell = row.createCell(0);
            cell.setCellValue((String)aRow[0]);
            cell.setCellStyle(styles.get("cell_normal_centered"));

             ...
             ..
             .


问:
Why isn't my div changing color in IE?
The below scenario is not woking in IE.

Styles:

```<code>.tabmenu {
    background-color: #990000;
    display: inline-block;
    width: 150px;
    position: relative;
    left: 59%;
    border-top-left-radius: 10em;
    margin-bottom: -8px;
    min-width: 75px;
    max-width: 150px;
    font-size: 13px;
    font-weight: bold;
    font-style: normal;
    font-family: Arial;
    border: none;
    padding: 5px 5px;
    height: auto !important;
    cursor: pointer !important;
    color: #ffffff !important;
    text-align: center;
}
</code>```

In .cshtml file

```<code><div class="tabmenu" style="width:100px;" onclick="btnCommonOnClick()" id="btnCommon">Common</div>
<div class="tabmenu" style="background-color:#999999!important;"  onclick="EquipmentSpecificOnClick(1)" id="btnEquipment">Specific</div>
<div class="tabmenu" style="background-color:#999999!important;width:100px;" onclick=" btnUnassignedonClick(this)" id="btnUnassigned">Unassigned</div>
<div class="tabmenu" style="background-color:#999999!important;width:100px;" onclick="OrphanOnClick()" id="btnOrphan">Orphan</div>
</code>```

First load the background colors are looking fine. When I click on any other div, change the background color of that div. For that purpose, I have given the code:

```<code>$("#btnCommon").css("background-color","#999999 !important");//grey
$("#btnEquipment").css("background-color","#999999 !important");//grey
$('#btnOrphan').css("backgroundColor","#999999!important");//grey
$('#btnUnassigned').css("backgroundColor","#990000!important");//red
</code>```

Above code is not working in IE. The div color is not changed as red. still in grey.

Any solution?

答:
Can confirm with IE Edge,with the inline background-color:#999999!important the css does not get overridden.

If you remove the !important declarations it will work fine.

I added to an html page:

```<code><div class="tabmenu" style="background-color:#999999!important;width:100px;" onclick="OrphanOnClick()" id="btnOrphan">Orphan</div>
</code>```

and ran in the developer console:

```<code>$('#btnOrphan').css("backgroundColor","#990000!important");
</code>```

But the background color did not change.

When changing the html to:

```<code><div class="tabmenu" style="background-color:#999999;width:100px;" onclick="OrphanOnClick()" id="btnOrphan">Orphan</div>
</code>```

and running:

```<code>$('#btnOrphan').css("backgroundColor","#990000");
</code>```

the background color changes.

If you need to keep the !important declarations you can try defining two css classes:

```<code>.bg-gray {background-color:#999999 !important;}
.bg-red{background-color:#990000 !important;}
</code>```

and markup your HTML like this:

```<code><div class="tabmenu bg-gray" style="width:100px;" onclick="OrphanOnClick()" id="btnOrphan">
</code>```

And to change the colors in your click handlers:

```<code>$('#btnOrphan').removeClass("bg-gray").addClass("bg-red");
</code>```

Title: Why isn't my div changing color in IE?

Body:
The below scenario is not woking in IE.

Styles:

.tabmenu {
    background-color: #990000;
    display: inline-block;
    width: 150px;
    position: relative;
    left: 59%;
    border-top-left-radius: 10em;
    margin-bottom: -8px;
    min-width: 75px;
    max-width: 150px;
    font-size: 13px;
    font-weight: bold;
    font-style: normal;
    font-family: Arial;
    border: none;
    padding: 5px 5px;
    height: auto !important;
    cursor: pointer !important;
    color: #ffffff !important;
    text-align: center;
}

In .cshtml file

Common

Specific

Unassigned

Orphan

First load the background colors are looking fine. When I click on any other div, change the background color of that div. For that purpose, I have given the code:

$("#btnCommon").css("background-color","#999999 !important");//grey
$("#btnEquipment").css("background-color","#999999 !important");//grey
$('#btnOrphan').css("backgroundColor","#999999!important");//grey
$('#btnUnassigned').css("backgroundColor","#990000!important");//red

Above code is not working in IE. The div color is not changed as red. still in grey.

Any solution?

Body:
Can confirm with IE Edge,with the inline background-color:#999999!important the css does not get overridden.

If you remove the !important declarations it will work fine.

I added to an html page:

<div class="tabmenu" style="background-color:#999999!important;width:100px;" onclick="OrphanOnClick()" id="btnOrphan">Orphan</div>

and ran in the developer console:

$('#btnOrphan').css("backgroundColor","#990000!important");

But the background color did not change.

When changing the html to:

<div class="tabmenu" style="background-color:#999999;width:100px;" onclick="OrphanOnClick()" id="btnOrphan">Orphan</div>

and running:

$('#btnOrphan').css("backgroundColor","#990000");

the background color changes.

If you need to keep the !important declarations you can try defining two css classes:

.bg-gray {background-color:#999999 !important;}
.bg-red{background-color:#990000 !important;}

and markup your HTML like this:

<div class="tabmenu bg-gray" style="width:100px;" onclick="OrphanOnClick()" id="btnOrphan">

And to change the colors in your click handlers:

$('#btnOrphan').removeClass("bg-gray").addClass("bg-red");


问:
bash for script and input parameter
Can anyone help me to modify my script. Because it does not work. Here are three scripts.
1) pb.sh, use delphicpp_release software to read the 1brs.ab.sh and will give the output as 1brs.ab.out

2) 1brs.ab.sh, use for input parameter where a.sh(another script for protein structure), chramm.siz, charmm.crg are file for atom size and charge etc. rest of the parameters for run the delphicpp_release software.

3) a.sh, use for read several protein structures, which will be in the same directory.

my script_1 = pb.sh:

```<code>  ./delphicpp_release 1brs.ab.sh >1brs.ab.out
   echo PB-Energy-AB = $(grep -oP '(?<=Energy> Corrected:).*' 1brs.ab.out) >>PB-energy.dat

   cat PB-energy.dat
</code>```

script_2 = 1brs.ab.sh:

```<code>in(pdb,file="a.sh")
in(siz,file="charmm.siz")
in(crg,file="charmm.crg")
perfil=70
scale=2.0
indi=4
exdi=80.0
prbrad=1.4
salt=0.15
bndcon=2
maxc=0.0001
linit=800
energy(s)
</code>```

script_3 = a.sh:

```<code>for i in $(seq 90000 20 90040); do
   $i.pdb
done
</code>```

答:
As we don't know what software is, something like

```<code>for ((i=90000;i<=100000;i+=20)); do
    ./software << "    DATA_END" > 1brs.$i.a.out
    scale=2.0
    in(pdb,file="../$i.ab.pdb")
    in(siz,file="charmm.siz")
    in(crg,file="charmm.crg")
    indi=z
    exdi=x
    prbrad=y
    DATA_END
    echo Energy-A = $(grep -oP '(?<=Energy>:).*' 1brs.$i.a.out) >>PB-energy.dat
done
</code>```

A more POSIX shell compliant version

```<code>i=90000
while ((i<=100000)); do
    ...
    ((i+=20));
done
</code>```

EDIT: Without heredoc

```<code>{
    echo 'scale=2.0'
    echo 'in(pdb,file="../'"$i"'.ab.pdb")'
    echo 'in(siz,file="charmm.siz")'
    echo 'in(crg,file="charmm.crg")'
    echo 'indi=z'
    echo 'exdi=x'
    echo 'prbrad=y'
} > $i.ab.sh
./software <$i.ab.sh >$i.ab.out
</code>```

but as question was changed I'm not sure to understand it.

Title: bash for script and input parameter

Body:
Can anyone help me to modify my script. Because it does not work. Here are three scripts.
1) pb.sh, use delphicpp_release software to read the 1brs.ab.sh and will give the output as 1brs.ab.out

2) 1brs.ab.sh, use for input parameter where a.sh(another script for protein structure), chramm.siz, charmm.crg are file for atom size and charge etc. rest of the parameters for run the delphicpp_release software.

3) a.sh, use for read several protein structures, which will be in the same directory.

my script_1 = pb.sh:

  ./delphicpp_release 1brs.ab.sh >1brs.ab.out
   echo PB-Energy-AB = $(grep -oP '(?<=Energy> Corrected:).*' 1brs.ab.out) >>PB-energy.dat

   cat PB-energy.dat

script_2 = 1brs.ab.sh:

in(pdb,file="a.sh")
in(siz,file="charmm.siz")
in(crg,file="charmm.crg")
perfil=70
scale=2.0
indi=4
exdi=80.0
prbrad=1.4
salt=0.15
bndcon=2
maxc=0.0001
linit=800
energy(s)

script_3 = a.sh:

for i in $(seq 90000 20 90040); do
   $i.pdb
done

Body:
As we don't know what software is, something like

for ((i=90000;i<=100000;i+=20)); do
    ./software << "    DATA_END" > 1brs.$i.a.out
    scale=2.0
    in(pdb,file="../$i.ab.pdb")
    in(siz,file="charmm.siz")
    in(crg,file="charmm.crg")
    indi=z
    exdi=x
    prbrad=y
    DATA_END
    echo Energy-A = $(grep -oP '(?<=Energy>:).*' 1brs.$i.a.out) >>PB-energy.dat
done

A more POSIX shell compliant version

i=90000
while ((i<=100000)); do
    ...
    ((i+=20));
done

EDIT: Without heredoc

{
    echo 'scale=2.0'
    echo 'in(pdb,file="../'"$i"'.ab.pdb")'
    echo 'in(siz,file="charmm.siz")'
    echo 'in(crg,file="charmm.crg")'
    echo 'indi=z'
    echo 'exdi=x'
    echo 'prbrad=y'
} > $i.ab.sh
./software <$i.ab.sh >$i.ab.out

but as question was changed I'm not sure to understand it.


问:
tcpdf (html2pdf) is not generating table borders correctly
I am generating pdf file using html2pdf (that is using tcpdf library, _tcpdf_5.0.002). Unfourtunately I cannot generate table borders properly.

```<code>require_once('inc/html2pdf/html2pdf.class.php');
$html2pdf = new HTML2PDF('P','A4','en');
$pdf_output = '';

// HEADER
$pdf_output .='<page backtop="8mm" backbottom="8mm" backleft="10mm" backright="10mm" style="font-size: 11px;font-family:freeserif;">';
$pdf_output .= '<style>
    table {
        border-collapse:collapse;
    }
    </style>';

 $pdf_output.='<table>';
 $pdf_output.= '<tr><td style="border-top: 1px solid black;">A</td></tr>';
 $pdf_output.= '<tr><td style="border-top: 1px solid black;">A</td></tr>';
 $pdf_output.= '<tr><td style="">A</td></tr>';
 $pdf_output.= '<tr><td style="border-top: 1px solid black;">A</td></tr>';
 $pdf_output.='</table>';
 $pdf_output .='</page>';
 $html2pdf->WriteHTML($pdf_output);
 $attachment= $html2pdf->Output('attachment.pdf', 'S');
 ...
</code>```

It doesn't show top borders for cells. It shows top-border only for first row and not for others. I have simplified this html markup for test purposes (in reality it doesn't render just "A" letters in one cell, there is content in differnt columns, but top-border is not rendering either).

How to render top-border for cells ucing html2pdf (tcpdf)?

答:
Just add border to table tag</p>

```<code><table  border="1" cellspacing="0"   >
</code>```

Body:
I am generating pdf file using html2pdf (that is using tcpdf library, _tcpdf_5.0.002). Unfourtunately I cannot generate table borders properly.

require_once('inc/html2pdf/html2pdf.class.php');
$html2pdf = new HTML2PDF('P','A4','en');
$pdf_output = '';

// HEADER
$pdf_output .='<page backtop="8mm" backbottom="8mm" backleft="10mm" backright="10mm" style="font-size: 11px;font-family:freeserif;">';
$pdf_output .= '';

 $pdf_output.='
';
 $pdf_output.= '
A
';
 $pdf_output.= '
A
';
 $pdf_output.= '
A
';
 $pdf_output.= '
A
';
 $pdf_output.='
';
 $pdf_output .='</page>';
 $html2pdf->WriteHTML($pdf_output);
 $attachment= $html2pdf->Output('attachment.pdf', 'S');
 ...

It doesn't show top borders for cells. It shows top-border only for first row and not for others. I have simplified this html markup for test purposes (in reality it doesn't render just "A" letters in one cell, there is content in differnt columns, but top-border is not rendering either).

How to render top-border for cells ucing html2pdf (tcpdf)?

Body:
Just add border to table tag

<table  border="1" cellspacing="0"   >


问:
C#: catch test failure during classcleanup
Is it possible to nest TestMethods in ClassCleanup and have them run/behave as TestMethods instead of regular method calls?

I have a TestClass to test an AppMngr class I created to manage a process.  I test for the ability to Open/Close the app (e.g. MyNotepadMngrClass.Open() and ...Close()).  I have several more classes that do work inside that process (e.g. MyNotepadWorkerClass.WriteLine() or ...DoSomething() ).  When testing the other classes I need to start notepad and close it when done.  ClassInitialize/ClassCleanup are obvious places for this.  But I want to confirm notepad closed.

So I created a static [TestMethod] for the Close operation.  I call it from ClassCleanup in MyNotepadWorkerTestClass.  It performs the close operation fine.  But if I add something like -- Assert.IsFalse(true); -- to the body of my close method the test run does not fail.

Let me know if what I am trying to do fundamentally wrong.  Appreciate any you can give help.

P.S. Hey TestStand guys, I am looking for Setup/Ceanup behaviour during RunSelectedStep.  TestDriven.NET gives me RunSelectedStep.  So how do I catch failures during ClassInitialize and ClassCleanup.

答: ClassCleanup is by definition to be used "after all the tests in the test class have run" (from msdn), so you probably can't add new test methods in there. You'll need to restructure your test.</p>

ContentLicense: CC BY-SA 2.5


问:
android.widget.LinearLayout cannot be cast to android.widget.TableRow
I'm trying to add row to tablelayout. But android.widget.LinearLayout cannot be cast to android.widget.TableRow error's occuring.

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    tools:context="com.example.khash.santotootsoolol.MainActivity"
    android:orientation="vertical">

    <HorizontalScrollView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:scrollbars="horizontal"
        android:fillViewport="true">

    <TableLayout
        android:id="@+id/table_result"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">

        <TableRow>
            <TextView
                android:text="Date"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:padding="10dp"
                android:background="@drawable/table_header"
                android:textColor="@android:color/white"/>

            <TextView
                android:text="Payment"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:padding="10dp"
                android:background="@drawable/table_header"
                android:textColor="@android:color/white"/>

            <TextView
                android:text="Remainder"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:padding="10dp"
                android:background="@drawable/table_header"
                android:textColor="@android:color/white"/>

            <TextView
                android:padding="10dp"
                android:text="Interest"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:background="@drawable/table_header"
                android:textColor="@android:color/white" />

        </TableRow>

    </TableLayout>

    </HorizontalScrollView>

</LinearLayout>
</code>```

and my activity

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

    private TableLayout tableLayout = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        tableLayout = (TableLayout)findViewById(R.id.table_result);
        TableRow tr = (TableRow)LayoutInflater.from(this).inflate(R.layout.table_row, null);
        tableLayout.addView(tr);
        setContentView(R.layout.activity_main);}
}
</code>```

my custom table row is

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:weightSum="4"
    android:layout_marginBottom="3dp">

    <TextView
        android:id="@+id/tv_pay_date"
        android:text="7/31/2017"
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:gravity="center"
        android:background="@drawable/table_row_item"/>

    <TextView
        android:id="@+id/tv_monthly_payment"
        android:text="13,933,700"
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:gravity="center"
        android:background="@drawable/table_row_item"/>

    <TextView
        android:id="@+id/tv_remainder_payment"
        android:text="125,403,300"
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:gravity="center"
        android:background="@drawable/table_row_item"/>

    <TextView
        android:id="@+id/tv_interest"
        android:text=""
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:gravity="center"
        android:background="@drawable/table_row_item"/>

</LinearLayout>
</code>```

I'm changed linear layout and inflater but error is still occured. Or i can't inflate custom layout in table layout?

答:
Try this:

```<code><?xml version="1.0" encoding="utf-8"?>
<TableRow xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:weightSum="4"
    android:layout_marginBottom="3dp">

<TextView
    android:id="@+id/tv_pay_date"
    android:text="7/31/2017"
    android:layout_weight="1"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:gravity="center"
    android:background="@drawable/table_row_item"/>

<TextView
    android:id="@+id/tv_monthly_payment"
    android:text="13,933,700"
    android:layout_weight="1"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:gravity="center"
    android:background="@drawable/table_row_item"/>

<TextView
    android:id="@+id/tv_remainder_payment"
    android:text="125,403,300"
    android:layout_weight="1"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:gravity="center"
    android:background="@drawable/table_row_item"/>

<TextView
    android:id="@+id/tv_interest"
    android:text=""
    android:layout_weight="1"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:gravity="center"
    android:background="@drawable/table_row_item"/>

</TableRow>
</code>```

Hope this helps.

Body:
I'm trying to add row to tablelayout. But android.widget.LinearLayout cannot be cast to android.widget.TableRow error's occuring.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    tools:context="com.example.khash.santotootsoolol.MainActivity"
    android:orientation="vertical">

    <HorizontalScrollView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:scrollbars="horizontal"
        android:fillViewport="true">

    <TableLayout
        android:id="@+id/table_result"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">

        <TableRow>
            <TextView
                android:text="Date"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:padding="10dp"
                android:background="@drawable/table_header"
                android:textColor="@android:color/white"/>

            <TextView
                android:text="Payment"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:padding="10dp"
                android:background="@drawable/table_header"
                android:textColor="@android:color/white"/>

            <TextView
                android:text="Remainder"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:padding="10dp"
                android:background="@drawable/table_header"
                android:textColor="@android:color/white"/>

            <TextView
                android:padding="10dp"
                android:text="Interest"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:background="@drawable/table_header"
                android:textColor="@android:color/white" />

        </TableRow>

    </TableLayout>

    </HorizontalScrollView>

</LinearLayout>

and my activity

public class MainActivity extends AppCompatActivity {

    private TableLayout tableLayout = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        tableLayout = (TableLayout)findViewById(R.id.table_result);
        TableRow tr = (TableRow)LayoutInflater.from(this).inflate(R.layout.table_row, null);
        tableLayout.addView(tr);
        setContentView(R.layout.activity_main);}
}

my custom table row is

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:weightSum="4"
    android:layout_marginBottom="3dp">

    <TextView
        android:id="@+id/tv_pay_date"
        android:text="7/31/2017"
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:gravity="center"
        android:background="@drawable/table_row_item"/>

    <TextView
        android:id="@+id/tv_monthly_payment"
        android:text="13,933,700"
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:gravity="center"
        android:background="@drawable/table_row_item"/>

    <TextView
        android:id="@+id/tv_remainder_payment"
        android:text="125,403,300"
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:gravity="center"
        android:background="@drawable/table_row_item"/>

    <TextView
        android:id="@+id/tv_interest"
        android:text=""
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:gravity="center"
        android:background="@drawable/table_row_item"/>

</LinearLayout>

I'm changed linear layout and inflater but error is still occured. Or i can't inflate custom layout in table layout?

Body:
Try this:

<?xml version="1.0" encoding="utf-8"?>
<TableRow xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:weightSum="4"
    android:layout_marginBottom="3dp">

<TextView
    android:id="@+id/tv_pay_date"
    android:text="7/31/2017"
    android:layout_weight="1"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:gravity="center"
    android:background="@drawable/table_row_item"/>

<TextView
    android:id="@+id/tv_monthly_payment"
    android:text="13,933,700"
    android:layout_weight="1"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:gravity="center"
    android:background="@drawable/table_row_item"/>

<TextView
    android:id="@+id/tv_remainder_payment"
    android:text="125,403,300"
    android:layout_weight="1"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:gravity="center"
    android:background="@drawable/table_row_item"/>

<TextView
    android:id="@+id/tv_interest"
    android:text=""
    android:layout_weight="1"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:gravity="center"
    android:background="@drawable/table_row_item"/>

</TableRow>

Hope this helps.


问:
docker saved image, how to run?
I have a testlink docker image running (named 'otechlabs/testlink').

Question 1: How do I get the original url from which I downloaded it (I can't remember) ? I would like to see the instructions about how to run the container.

It's running so fine that I saved a commit of it to run in another machine.

Question 2: Should I remember the run parameters(I can't remember)?

The container was created around 3 months ago.

Question 3: Instead of save/load, should I export/import?

Since I don't remember how to run the image, then I guess I should skip this step, perhaps (someway) copying the image to just start it in another host.

答:
Q1:

You can try looking up the image in docker hub. The name otechlabs/testlink suggests that the user otechlabs in dockerhub has an image called testlink.

Now, I tried looking up the user's profile here but it appears that he doesn't have anything uploaded yet, maybe it is a private image.

If you're lucky you might be able to find something useful from other people's testlink image page.

Example:
https://hub.docker.com/r/rodrigodirk/testlink/

Q2:

Not quite sure what you meant here. Well if you have a running container of it, you can always do a docker inspect [CONTAINER_ID] to revisit the parameters used for starting it.

Example:

```<code>  "Config": {
        "ExposedPorts": {
            "5432/tcp": {},
            "9001/tcp": {}
        },
        "Env": [
            "affinity:container==47eea8a078ad47583b4f5343302e7939a6d5f04ad929a079d8d9ae7cbee96d6a",
            "POSTGRES_USER=bigCat01"
        ]
  }
</code>```

Title: docker saved image, how to run?

Body:
Q1:

You can try looking up the image in docker hub. The name otechlabs/testlink suggests that the user otechlabs in dockerhub has an image called testlink.

Now, I tried looking up the user's profile here but it appears that he doesn't have anything uploaded yet, maybe it is a private image.

If you're lucky you might be able to find something useful from other people's testlink image page.

Example:
https://hub.docker.com/r/rodrigodirk/testlink/

Q2:

Not quite sure what you meant here. Well if you have a running container of it, you can always do a docker inspect [CONTAINER_ID] to revisit the parameters used for starting it.

Example:

  "Config": {
        "ExposedPorts": {
            "5432/tcp": {},
            "9001/tcp": {}
        },
        "Env": [
            "affinity:container==47eea8a078ad47583b4f5343302e7939a6d5f04ad929a079d8d9ae7cbee96d6a",
            "POSTGRES_USER=bigCat01"
        ]
  }


问:
NSTextField insertText method is deprecated, what is the replacement?
I have a NSTextField where I would like to enter text at the insertion point. I have a code that don't generate errors:

```<code>    let str = "Abc"
    myTextField.insertText(str)
</code>```

[edit]
When, in the field there is 123|45 (the "|" represents the text insertion point), the output should be 123Abc|45.

Unfortunately don't work because it's deprecated. Here is the documentation. What is the replacement?

Please note that this question is for NSTextField not NSTextView, which has a question here: NSTextView's insertText method is deprecated in OS X v10.11. What is the replacement?

答:
Get the field editor for the window that the text field is in, then use insertText(_:, replacementRange:) on that:

```<code>let textfield = NSTextField()...
if let fieldEditor = textfield.window?.fieldEditor(false, for: textfield) as? NSTextView {
    fieldEditor.insertText("abc", replacementRange: fieldEditor.selectedRange())
}
</code>```

To clarify: this requires that the text field has input focus. If some other field has input focus the field editor will insert text there instead.

Body:
I have a NSTextField where I would like to enter text at the insertion point. I have a code that don't generate errors:

    let str = "Abc"
    myTextField.insertText(str)

[edit]
When, in the field there is 123|45 (the "|" represents the text insertion point), the output should be 123Abc|45.

Unfortunately don't work because it's deprecated. Here is the documentation. What is the replacement?

Please note that this question is for NSTextField not NSTextView, which has a question here: NSTextView's insertText method is deprecated in OS X v10.11. What is the replacement?

Body:
Get the field editor for the window that the text field is in, then use insertText(_:, replacementRange:) on that:

let textfield = NSTextField()...
if let fieldEditor = textfield.window?.fieldEditor(false, for: textfield) as? NSTextView {
    fieldEditor.insertText("abc", replacementRange: fieldEditor.selectedRange())
}

To clarify: this requires that the text field has input focus. If some other field has input focus the field editor will insert text there instead.


问:
Parse Json nested dictionaries with Python (not dictionaries inside lists)
I have these horrible nested JSON dictionaries:

```<code>  "data": {
            "assetID": "VMSA0000000000310652",
            "lastModified": "2017-06-02T19:36:36.535-04:00",
            "locale": {
              "MetadataAlbum": {
                "Artists": {
                  "Artist": {
                    "ArtistName": "Various Artists",
                    "ArtistRole": "MainArtist"
                  }
                },
                "Publishable": "true",
                "genres": {
                  "genre": {
                    "extraInfos": null,
                  }
                },
                "lastModified": "2017-06-02T19:32:46.296-04:00",
                "locale": {
                  "country": "UK",
                  "language": "en",
</code>```

And want to be able to match the value of the language with the method below. I am passing in language ('en') and the data is the nested dictionary above.

```<code>def get_localized_metadataalbum(language, data):
    for locale in data['locale']:
        if data['locale'].get('MetadataAlbum') is not None:
            if data['locale'].get('MetadataAlbum').get('locale') is not None:
                if data['locale'].get('MetadataAlbum').get('locale').get('language') is not None:
                    if data['locale'].get('MetadataAlbum').get('locale').get('language') == language:
                        return data['locale']

return None
</code>```

The method works with a list of dictionaries, but not with dictionaries inside dictionaries... Can anyone point me to a place where I can learn how to parse through nested dictionaries? I'm a little lost here and all examples I've found show how to parse to a list of dictionaries.

I've been getting: TypeError: string indices must be integers

答:
I fixed your json. I put into string and closed the brackets correctly. This works as expected:

```<code>import json

json_string = """
  {"data": {
            "assetID": "VMSA0000000000310652",
            "lastModified": "2017-06-02T19:36:36.535-04:00",
            "locale": {
              "MetadataAlbum": {
                "Artists": {
                  "Artist": {
                    "ArtistName": "Various Artists",
                    "ArtistRole": "MainArtist"
                  }
                },
                "Publishable": "true",
                "genres": {
                  "genre": {
                    "extraInfos": null
                  }
                },
                "lastModified": "2017-06-02T19:32:46.296-04:00",
                "locale": {
                  "country": "UK",
                  "language": "en"
                }
              }
           }
         }
   }
   """

json_data = json.loads(json_string)

print(json_data)

def get_localized_metadataalbum(language, data):
    for locale in data['locale']:
        if data['locale'].get('MetadataAlbum') is not None:
            if data['locale'].get('MetadataAlbum').get('locale') is not None:
                if data['locale'].get('MetadataAlbum').get('locale').get('language') is not None:
                    if data['locale'].get('MetadataAlbum').get('locale').get('language') == language:
                        return data['locale']

    return None

print('RESULT:')
print(get_localized_metadataalbum("en", json_data['data']))
</code>```

I ran it on python 2.7.12.

Body:
I have these horrible nested JSON dictionaries:

  "data": {
            "assetID": "VMSA0000000000310652",
            "lastModified": "2017-06-02T19:36:36.535-04:00",
            "locale": {
              "MetadataAlbum": {
                "Artists": {
                  "Artist": {
                    "ArtistName": "Various Artists",
                    "ArtistRole": "MainArtist"
                  }
                },
                "Publishable": "true",
                "genres": {
                  "genre": {
                    "extraInfos": null,
                  }
                },
                "lastModified": "2017-06-02T19:32:46.296-04:00",
                "locale": {
                  "country": "UK",
                  "language": "en",

And want to be able to match the value of the language with the method below. I am passing in language ('en') and the data is the nested dictionary above.

def get_localized_metadataalbum(language, data):
    for locale in data['locale']:
        if data['locale'].get('MetadataAlbum') is not None:
            if data['locale'].get('MetadataAlbum').get('locale') is not None:
                if data['locale'].get('MetadataAlbum').get('locale').get('language') is not None:
                    if data['locale'].get('MetadataAlbum').get('locale').get('language') == language:
                        return data['locale']

return None

The method works with a list of dictionaries, but not with dictionaries inside dictionaries... Can anyone point me to a place where I can learn how to parse through nested dictionaries? I'm a little lost here and all examples I've found show how to parse to a list of dictionaries.

I've been getting: TypeError: string indices must be integers

Body:
I fixed your json. I put into string and closed the brackets correctly. This works as expected:

import json

json_string = """
  {"data": {
            "assetID": "VMSA0000000000310652",
            "lastModified": "2017-06-02T19:36:36.535-04:00",
            "locale": {
              "MetadataAlbum": {
                "Artists": {
                  "Artist": {
                    "ArtistName": "Various Artists",
                    "ArtistRole": "MainArtist"
                  }
                },
                "Publishable": "true",
                "genres": {
                  "genre": {
                    "extraInfos": null
                  }
                },
                "lastModified": "2017-06-02T19:32:46.296-04:00",
                "locale": {
                  "country": "UK",
                  "language": "en"
                }
              }
           }
         }
   }
   """

json_data = json.loads(json_string)

print(json_data)

def get_localized_metadataalbum(language, data):
    for locale in data['locale']:
        if data['locale'].get('MetadataAlbum') is not None:
            if data['locale'].get('MetadataAlbum').get('locale') is not None:
                if data['locale'].get('MetadataAlbum').get('locale').get('language') is not None:
                    if data['locale'].get('MetadataAlbum').get('locale').get('language') == language:
                        return data['locale']

    return None

print('RESULT:')
print(get_localized_metadataalbum("en", json_data['data']))

I ran it on python 2.7.12.


问:
pyparsing a field that may or may not contain values
I have a dataset that resemebles the following:

Capture MICR - Serial:                  Pos44:  Trrt: 32904  Acct:        Tc:   2064        Opt4:          Split:

The problem that I am having is I can't figure out how I could properly write a capture for the "Capture MICR - Serial Field". This field could either be blank or contain an alphanumeric of varying length (I have the same problem with the other fields that could either be populated or blank.

I have tried some variations of the following, but am still coming up short.

pp.Literal("Capture  MICR - Serial:") + pp.White(" ", min=1, max=0) + (pp.Word(pp.printables) ^ pp.White(" ", min=1, max=0))("crd_micr_serial") + pp.FollowedBy(pp.Literal("Pos44:"))

I think that part of the problem is that the Or matches a parse for the longest match, which in this case could be a long whitespace character, with a single alphanumeric, but I would still want to capture the single value.

Thanks for everyone's help.

答:
The simplest way to parse text like "A: valueA B: valueB C: valueC" is to use pyparsing's SkipTo class:

```<code>a_expr = "A:" + SkipTo("B:")
b_expr = "B:" + SkipTo("C:")
c_expr = "C:" + SkipTo(LineEnd())
line_parser = a_expr + b_expr + c_expr
</code>```

I'd like to enhance this just a bit more:

add a parse action to strip off leading and trailing whitespace

add a results name to make it easy to get the results after the line has been parsed

Here is how that simple parser looks:

```<code>NL = LineEnd()
a_expr = "A:" + SkipTo("B:").addParseAction(lambda t: [t[0].strip()])('A')
b_expr = "B:" + SkipTo("C:").addParseAction(lambda t: [t[0].strip()])('B')
c_expr = "C:" + SkipTo(NL).addParseAction(lambda t: [t[0].strip()])('C')
line_parser = a_expr + b_expr + c_expr

line_parser.runTests("""
    A: 100 B: Fred C:
    A:  B: a value with spaces C: 42
""")
</code>```

Gives:

```<code> A: 100 B: Fred C:
['A:', '100', 'B:', 'Fred', 'C:', '']
- A: '100'
- B: 'Fred'
- C: ''

A:  B: a value with spaces C: 42
['A:', '', 'B:', 'a value with spaces', 'C:', '42']
- A: ''
- B: 'a value with spaces'
- C: '42'
</code>```

I try to avoid copy/paste code when I can, and would rather automate the "A is followed by B" and
"C is followed by end-of-line" with a list describing the different prompt strings, and then walking that list to build each
sub expression:

```<code>import pyparsing as pp

def make_prompt_expr(s):
    '''Define the expression for prompts as 'ABC:' '''
    return pp.Combine(pp.Literal(s) + ':')

def make_field_value_expr(next_expr):
    '''Define the expression for the field value as SkipTo(what comes next)'''
    return pp.SkipTo(next_expr).addParseAction(lambda t: [t[0].strip()])

def make_name(s):
    '''Convert prompt string to identifier form for results names'''
    return ''.join(s.split()).replace('-','_')

# use split to easily define list of prompts in order - makes it easy to update later if new prompts are added
prompts = "Capture MICR - Serial/Pos44/Trrt/Acct/Tc/Opt4/Split".split('/')

# keep a list of all the prompt-value expressions
exprs = []

# get a list of this-prompt, next-prompt pairs
for this_, next_ in zip(prompts, prompts[1:]  + [None]):
    field_name = make_name(this_)
    if next_ is not None:
        next_expr = make_prompt_expr(next_)
    else:
        next_expr = pp.LineEnd()

    # define the prompt-value expression for the current prompt string and add to exprs
    this_expr = make_prompt_expr(this_) + make_field_value_expr(next_expr)(field_name)
    exprs.append(this_expr)

# define a line parser as the And of all of the generated exprs
line_parser = pp.And(exprs)

line_parser.runTests("""\
Capture MICR - Serial:                  Pos44:  Trrt: 32904  Acct:        Tc:   2064        Opt4:          Split:
Capture MICR - Serial:  1729XYZ                Pos44:  Trrt: 32904  Acct:        Tc:   2064        Opt4: XXL         Split: 50
""")
</code>```

Gives:

```<code>Capture MICR - Serial:                  Pos44:  Trrt: 32904  Acct:        Tc:   2064        Opt4:          Split:
['Capture MICR - Serial:', '', 'Pos44:', '', 'Trrt:', '32904', 'Acct:', '', 'Tc:', '2064', 'Opt4:', '', 'Split:', '']
- Acct: ''
- CaptureMICR_Serial: ''
- Opt4: ''
- Pos44: ''
- Split: ''
- Tc: '2064'
- Trrt: '32904'

Capture MICR - Serial:  1729XYZ                Pos44:  Trrt: 32904  Acct:        Tc:   2064        Opt4: XXL         Split: 50
['Capture MICR - Serial:', '1729XYZ', 'Pos44:', '', 'Trrt:', '32904', 'Acct:', '', 'Tc:', '2064', 'Opt4:', 'XXL', 'Split:', '50']
- Acct: ''
- CaptureMICR_Serial: '1729XYZ'
- Opt4: 'XXL'
- Pos44: ''
- Split: '50'
- Tc: '2064'
- Trrt: '32904'
</code>```

Body:
The simplest way to parse text like "A: valueA B: valueB C: valueC" is to use pyparsing's SkipTo class:

a_expr = "A:" + SkipTo("B:")
b_expr = "B:" + SkipTo("C:")
c_expr = "C:" + SkipTo(LineEnd())
line_parser = a_expr + b_expr + c_expr

I'd like to enhance this just a bit more:

add a parse action to strip off leading and trailing whitespace

add a results name to make it easy to get the results after the line has been parsed

Here is how that simple parser looks:

NL = LineEnd()
a_expr = "A:" + SkipTo("B:").addParseAction(lambda t: [t[0].strip()])('A')
b_expr = "B:" + SkipTo("C:").addParseAction(lambda t: [t[0].strip()])('B')
c_expr = "C:" + SkipTo(NL).addParseAction(lambda t: [t[0].strip()])('C')
line_parser = a_expr + b_expr + c_expr

line_parser.runTests("""
    A: 100 B: Fred C:
    A:  B: a value with spaces C: 42
""")

Gives:

 A: 100 B: Fred C:
['A:', '100', 'B:', 'Fred', 'C:', '']
- A: '100'
- B: 'Fred'
- C: ''

A:  B: a value with spaces C: 42
['A:', '', 'B:', 'a value with spaces', 'C:', '42']
- A: ''
- B: 'a value with spaces'
- C: '42'

I try to avoid copy/paste code when I can, and would rather automate the "A is followed by B" and
"C is followed by end-of-line" with a list describing the different prompt strings, and then walking that list to build each
sub expression:

import pyparsing as pp

def make_prompt_expr(s):
    '''Define the expression for prompts as 'ABC:' '''
    return pp.Combine(pp.Literal(s) + ':')

def make_field_value_expr(next_expr):
    '''Define the expression for the field value as SkipTo(what comes next)'''
    return pp.SkipTo(next_expr).addParseAction(lambda t: [t[0].strip()])

def make_name(s):
    '''Convert prompt string to identifier form for results names'''
    return ''.join(s.split()).replace('-','_')

# use split to easily define list of prompts in order - makes it easy to update later if new prompts are added
prompts = "Capture MICR - Serial/Pos44/Trrt/Acct/Tc/Opt4/Split".split('/')

# keep a list of all the prompt-value expressions
exprs = []

# get a list of this-prompt, next-prompt pairs
for this_, next_ in zip(prompts, prompts[1:]  + [None]):
    field_name = make_name(this_)
    if next_ is not None:
        next_expr = make_prompt_expr(next_)
    else:
        next_expr = pp.LineEnd()

    # define the prompt-value expression for the current prompt string and add to exprs
    this_expr = make_prompt_expr(this_) + make_field_value_expr(next_expr)(field_name)
    exprs.append(this_expr)

# define a line parser as the And of all of the generated exprs
line_parser = pp.And(exprs)

line_parser.runTests("""\
Capture MICR - Serial:                  Pos44:  Trrt: 32904  Acct:        Tc:   2064        Opt4:          Split:
Capture MICR - Serial:  1729XYZ                Pos44:  Trrt: 32904  Acct:        Tc:   2064        Opt4: XXL         Split: 50
""")

Gives:

Capture MICR - Serial:                  Pos44:  Trrt: 32904  Acct:        Tc:   2064        Opt4:          Split:
['Capture MICR - Serial:', '', 'Pos44:', '', 'Trrt:', '32904', 'Acct:', '', 'Tc:', '2064', 'Opt4:', '', 'Split:', '']
- Acct: ''
- CaptureMICR_Serial: ''
- Opt4: ''
- Pos44: ''
- Split: ''
- Tc: '2064'
- Trrt: '32904'

Capture MICR - Serial:  1729XYZ                Pos44:  Trrt: 32904  Acct:        Tc:   2064        Opt4: XXL         Split: 50
['Capture MICR - Serial:', '1729XYZ', 'Pos44:', '', 'Trrt:', '32904', 'Acct:', '', 'Tc:', '2064', 'Opt4:', 'XXL', 'Split:', '50']
- Acct: ''
- CaptureMICR_Serial: '1729XYZ'
- Opt4: 'XXL'
- Pos44: ''
- Split: '50'
- Tc: '2064'
- Trrt: '32904'


答:
you probably want try: except
like</p>

```<code>try:
    assert x in data.keys() for x in ["x","y"]
    ...
    return data["x"]["y"]
except:
    return None
</code>```

Title: Parse Json nested dictionaries with Python (not dictionaries inside lists)

Body:
you probably want try: except
like

try:
    assert x in data.keys() for x in ["x","y"]
    ...
    return data["x"]["y"]
except:
    return None


问:
Architecture agnostic code
I have this piece of code where the aim is to determine if the packet received is valid or not:

```<code>size_t offset_to_a, offset_to_b;
u_int32_t file_name_length;
u_int32_t packet_length;

if ((offset_to_a + offset_to_b + file_name_length) > packet_length) {
    // Invalid packet
}
</code>```

size_t is u_int64_t perhaps because the cpu is a 64-bit one.

Now when file_name_length has a value 0xFFFFFFFF (which is invalid), then the packet is deemed invalid.

But if size_t becomes u_int32_t because of the underlying architecture, then for the same value of file_name_length, the condition fails because the value would wrap around, and the packet is deemed valid.

How can I make this condition generic enough to work on both 32/64-bit architectures?

Thanks!

答:
The trick is to only use subtraction, and only subtract after verifying that the subtraction won't wrap. Something like this:</p>

```<code>if (offset_to_a > packet_length || packet_length - offset_to_a < file_name_length) {
    // invalid packet
}
size_t remain = packet_length - offset_to_a;
if (offset_to_b > remain || remain - offset_to_b < file_name_length) {
    // invalid packet
}
</code>```

Title: Architecture agnostic code

Body:
I have this piece of code where the aim is to determine if the packet received is valid or not:

size_t offset_to_a, offset_to_b;
u_int32_t file_name_length;
u_int32_t packet_length;

if ((offset_to_a + offset_to_b + file_name_length) > packet_length) {
    // Invalid packet
}

size_t is u_int64_t perhaps because the cpu is a 64-bit one.

Now when file_name_length has a value 0xFFFFFFFF (which is invalid), then the packet is deemed invalid.

But if size_t becomes u_int32_t because of the underlying architecture, then for the same value of file_name_length, the condition fails because the value would wrap around, and the packet is deemed valid.

How can I make this condition generic enough to work on both 32/64-bit architectures?

Thanks!

Body:
The trick is to only use subtraction, and only subtract after verifying that the subtraction won't wrap. Something like this:

if (offset_to_a > packet_length || packet_length - offset_to_a < file_name_length) {
    // invalid packet
}
size_t remain = packet_length - offset_to_a;
if (offset_to_b > remain || remain - offset_to_b < file_name_length) {
    // invalid packet
}


问:
open webpage in firefox
i am not sure..is there any chance to open my webpage in firefox. for example i am browsing mywebsite using IE. when ever i click link of the page then automatically it will open in firefox. this option is not for all pages only for specified page.

thanks.

答: I would seriously hope this isn't possible.</p>

Title: open webpage in firefox