问:
Why does this MultiDataTrigger throw an exception on animation?
A WPF-MVVM application that displays multiple views on a viewmodel. The user can go from less detailed to more detailed view at run time. The views are contained within a border. Under a set of conditions, an alarm is triggered by the viewmodel. The alarm is rendered in the view as an animation of flashing color on the border background to attract user attention.

The problem is that when the alarm is triggered AND user changes datatemplates during run time to get more detail, the WPF engine throws an exception on animation when using a multidatatrigger alarm. The engine works when using a Datatrigger and crashes on MultiDataTrigger with everything else the same.

The exception is: Cannot animate '(0).(1)' on an immutable object

A sample application to demonstrate issue:

1 MainWindow for hosting and toggling views.

2 views, large and small.

1 viewmodel.

1 Resource dictionary for the multi and single datatriggers

App.Xaml:

```<code><Application x:Class="AnimationSample.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:AnimationSample"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
        <ResourceDictionary Source="Dictionary1.xaml"/>
    </Application.Resources>
</Application>
</code>```

MainWindow.xaml:

```<code><Window x:Class="AnimationSample.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:AnimationSample"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <DataTemplate DataType="{x:Type local:SampleViewModel}" x:Key="smallTemplate">
            <local:SmallUserControl />
        </DataTemplate>
        <DataTemplate DataType="{x:Type local:SampleViewModel}" x:Key="largeTemplate">
            <local:LargeUserControl />
        </DataTemplate>
        <DataTemplate DataType="{x:Type local:SampleViewModel}" x:Key="mainTemplate">
            <DataTemplate.Triggers>
                <DataTrigger Binding="{Binding ElementName=ZoomSlider, Path=Value}" Value="1">
                    <Setter Property="ContentTemplate" Value="{StaticResource smallTemplate}"/>
                </DataTrigger>
                <DataTrigger Binding="{Binding ElementName=ZoomSlider, Path=Value}" Value="2">
                    <Setter Property="ContentTemplate" Value="{StaticResource largeTemplate}"/>
                </DataTrigger>
            </DataTemplate.Triggers>
        </DataTemplate>
        <Style TargetType="{x:Type ContentControl}" x:Key="DisplayStyle">
            <Setter Property="ContentTemplate" Value="{StaticResource smallTemplate}" />
            <Style.Triggers>
                <DataTrigger Binding="{Binding ElementName=ZoomSlider, Path=Value}" Value="1">
                    <Setter Property="ContentTemplate" Value="{StaticResource smallTemplate}"/>
                </DataTrigger>
                <DataTrigger Binding="{Binding ElementName=ZoomSlider, Path=Value}" Value="2">
                    <Setter Property="ContentTemplate" Value="{StaticResource largeTemplate}"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Window.Resources>
    <StackPanel Margin="8">
        <Slider x:Name="ZoomSlider" Minimum="1" Maximum="2" IsSnapToTickEnabled="True" />
        <ContentControl Content="{Binding}" Style="{StaticResource DisplayStyle}">
        </ContentControl>
    </StackPanel>
</Window>
</code>```

MainWindow.cs:

```<code>using System.Windows;

namespace AnimationSample
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            DataContext = new SampleViewModel();
        }
    }
}
</code>```

SampleViewModel.cs:

```<code>using System;
using System.ComponentModel;
using System.Linq.Expressions;
using System.Windows;

namespace AnimationSample
{
    public class SampleViewModel : NotifyPropertyChangedBase<SampleViewModel>
    {
        private bool _alarm;
        public bool Alarm
        {
            get { return _alarm; }
            set
            {
                if (!_alarm.Equals(value))
                {
                    _alarm = value;
                    OnPropertyChanged("Alarm");
                }
            }
        }

        private bool _flash;
        public bool Flash
        {
            get { return _flash; }
            set
            {
                if (!_flash.Equals(value))
                {
                    _flash = value;
                    OnPropertyChanged("Flash");
                }
            }
        }

        private string _description = "I am an alarm!";
        public string Description
        {
            get { return _description; }
            set
            {
                if(!_description.Equals(value))
                {
                    _description = value;
                    OnPropertyChanged("Description");
                }
            }
        }
    }

    public abstract class NotifyPropertyChangedBase<T> : DependencyObject, INotifyPropertyChanged
    {

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            { PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName)); }
        }

        protected virtual void OnPropertyChanged<T2>(Expression<Func<T, T2>> accessor)
        {
            OnPropertyChanged(PropertyName(accessor));
        }

        public static string PropertyName<T2>(Expression<Func<T, T2>> accessor)
        {
            return ((MemberExpression)accessor.Body).Member.Name;
        }
    }
}
</code>```

Dictionary1.xaml:

```<code><ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:local="clr-namespace:AnimationSample">
    <Style x:Key="FlashyAlarmBorderStyle" TargetType="{x:Type Border}">
        <Setter Property="BorderBrush" Value="Silver"/>
        <Setter Property="Background" Value="Black" />
        <Setter Property="BorderThickness" Value="2" />
        <Setter Property="CornerRadius" Value="8" />
        <Style.Triggers>
            <MultiDataTrigger>
                <MultiDataTrigger.Conditions>
                    <Condition Binding="{Binding Alarm}" Value="True" />
                    <Condition Binding="{Binding Flash}" Value="True" />
                </MultiDataTrigger.Conditions>
                <Setter Property="Background" Value="Orange"/>
                <Setter Property="BorderBrush" Value="Orange"/>
                <MultiDataTrigger.EnterActions>
                    <BeginStoryboard Name="faultBoard">
                        <Storyboard>
                            <ColorAnimation AutoReverse="True"
                                                RepeatBehavior="Forever"
                                                Storyboard.TargetProperty="(Border.Background).(SolidColorBrush.Color)"
                                                Duration="00:00:01"
                                                From="Silver"
                                                To="Orange"/>
                        </Storyboard>
                    </BeginStoryboard>
                </MultiDataTrigger.EnterActions>
                <MultiDataTrigger.ExitActions>
                    <StopStoryboard BeginStoryboardName="faultBoard">
                    </StopStoryboard>
                </MultiDataTrigger.ExitActions>
            </MultiDataTrigger>
            <!--<DataTrigger Binding="{Binding Alarm}" Value="True" >
                <Setter Property="Background" Value="Orange"/>
                <Setter Property="BorderBrush" Value="Orange"/>
                <DataTrigger.EnterActions>
                    <BeginStoryboard Name="alarmBoard">
                        <Storyboard>
                            <ColorAnimation AutoReverse="True"
                                                RepeatBehavior="Forever"
                                                Storyboard.TargetProperty="(Border.Background).(SolidColorBrush.Color)"
                                                Duration="00:00:01"
                                                From="Silver"
                                                To="Orange"/>
                        </Storyboard>
                    </BeginStoryboard>
                </DataTrigger.EnterActions>
                <DataTrigger.ExitActions>
                    <StopStoryboard BeginStoryboardName="alarmBoard">
                    </StopStoryboard>
                </DataTrigger.ExitActions>
            </DataTrigger>-->
        </Style.Triggers>
    </Style>
</ResourceDictionary>
</code>```

LargeUserControl.xaml:

```<code><UserControl x:Class="AnimationSample.LargeUserControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:AnimationSample"
             mc:Ignorable="d" >
    <Border Margin="8"
            Style="{DynamicResource FlashyAlarmBorderStyle}">
        <StackPanel>
            <Label HorizontalAlignment="Center" Content="LARGE VIEW" Foreground="White"/>
            <CheckBox Margin="8" IsChecked="{Binding Alarm}" Content="Turn on the alarm." Foreground="White" />
            <CheckBox Margin="8"  IsChecked="{Binding Flash}" Content="Turn on the flash!" Foreground="White" />
            <Label Margin="8" Content="{Binding Description}" Foreground="White"/>
        </StackPanel>
    </Border>
</UserControl>
</code>```

SmallUserControl.xaml:

```<code><UserControl x:Class="AnimationSample.SmallUserControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:AnimationSample"
             mc:Ignorable="d" >
    <Border Margin="8"
            Style="{DynamicResource FlashyAlarmBorderStyle}">
        <StackPanel>
            <Label HorizontalAlignment="Center" Content="SMALL VIEW" Foreground="White"/>
            <CheckBox Margin="4" IsChecked="{Binding Alarm}" Content="Turn on the alarm." HorizontalAlignment="Center" Foreground="White" />
            <CheckBox Margin="4" IsChecked="{Binding Flash}" Content="Turn on the flash!" HorizontalAlignment="Center" Foreground="White" />
        </StackPanel>
    </Border>
</UserControl>
</code>```

If you run the code and click on the alarm and flash checkboxes, then the control will go from silver border with black background to a flashing orange. If you move the slider to go from small to large view, you will get a run time from wpf if using the multidatatrigger. If you uncomment the datatrigger in the the Dictionar1.xaml and comment the multidatatrigger, then repeat the above, the application runs ok.

Why does this multidatatrigger gag on DataTemplate change and datatrigger work ok? The only difference from that to the single datatrigger is one extra boolean. How can it be fixed?

(Yes, can work around by creating a property on the viewmodel to aggregate these booleans, but that should not have to be done and is beside question. This seems like a bug with wpf?)

答:
Remove the setter that sets the same property (Background) that you try to animate:

```<code><MultiDataTrigger>
    <MultiDataTrigger.Conditions>
        <Condition Binding="{Binding Alarm}" Value="True" />
        <Condition Binding="{Binding Flash}" Value="True" />
    </MultiDataTrigger.Conditions>
    <!--<Setter Property="Background" Value="Orange"/>-->
    <Setter Property="BorderBrush" Value="Orange"/>
    <MultiDataTrigger.EnterActions>
        <BeginStoryboard Name="faultBoard">
            <Storyboard>
                <ColorAnimation AutoReverse="True"
                                RepeatBehavior="Forever"
                                Storyboard.TargetProperty="(Border.Background).(SolidColorBrush.Color)"
                                Duration="00:00:01"
                                From="Silver"
                                To="Orange"/>
            </Storyboard>
        </BeginStoryboard>
    </MultiDataTrigger.EnterActions>
    <MultiDataTrigger.ExitActions>
        <StopStoryboard BeginStoryboardName="faultBoard">
        </StopStoryboard>
    </MultiDataTrigger.ExitActions>
</MultiDataTrigger>
</code>```

Body:
A WPF-MVVM application that displays multiple views on a viewmodel. The user can go from less detailed to more detailed view at run time. The views are contained within a border. Under a set of conditions, an alarm is triggered by the viewmodel. The alarm is rendered in the view as an animation of flashing color on the border background to attract user attention.

The problem is that when the alarm is triggered AND user changes datatemplates during run time to get more detail, the WPF engine throws an exception on animation when using a multidatatrigger alarm. The engine works when using a Datatrigger and crashes on MultiDataTrigger with everything else the same.

The exception is: Cannot animate '(0).(1)' on an immutable object

A sample application to demonstrate issue:

1 MainWindow for hosting and toggling views.

2 views, large and small.

1 viewmodel.

1 Resource dictionary for the multi and single datatriggers

App.Xaml:

<Application x:Class="AnimationSample.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:AnimationSample"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
        <ResourceDictionary Source="Dictionary1.xaml"/>
    </Application.Resources>
</Application>

MainWindow.xaml:

<Window x:Class="AnimationSample.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:AnimationSample"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <DataTemplate DataType="{x:Type local:SampleViewModel}" x:Key="smallTemplate">
            <local:SmallUserControl />
        </DataTemplate>
        <DataTemplate DataType="{x:Type local:SampleViewModel}" x:Key="largeTemplate">
            <local:LargeUserControl />
        </DataTemplate>
        <DataTemplate DataType="{x:Type local:SampleViewModel}" x:Key="mainTemplate">
            <DataTemplate.Triggers>
                <DataTrigger Binding="{Binding ElementName=ZoomSlider, Path=Value}" Value="1">
                    <Setter Property="ContentTemplate" Value="{StaticResource smallTemplate}"/>
                </DataTrigger>
                <DataTrigger Binding="{Binding ElementName=ZoomSlider, Path=Value}" Value="2">
                    <Setter Property="ContentTemplate" Value="{StaticResource largeTemplate}"/>
                </DataTrigger>
            </DataTemplate.Triggers>
        </DataTemplate>

        </Style>
    </Window.Resources>
    <StackPanel Margin="8">
        <Slider x:Name="ZoomSlider" Minimum="1" Maximum="2" IsSnapToTickEnabled="True" />
        <ContentControl Content="{Binding}" Style="{StaticResource DisplayStyle}">
        </ContentControl>
    </StackPanel>
</Window>

MainWindow.cs:

using System.Windows;

namespace AnimationSample
{
    ///
    /// Interaction logic for MainWindow.xaml
    ///
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            DataContext = new SampleViewModel();
        }
    }
}

SampleViewModel.cs:

using System;
using System.ComponentModel;
using System.Linq.Expressions;
using System.Windows;

namespace AnimationSample
{
    public class SampleViewModel : NotifyPropertyChangedBase<SampleViewModel>
    {
        private bool _alarm;
        public bool Alarm
        {
            get { return _alarm; }
            set
            {
                if (!_alarm.Equals(value))
                {
                    _alarm = value;
                    OnPropertyChanged("Alarm");
                }
            }
        }

        private bool _flash;
        public bool Flash
        {
            get { return _flash; }
            set
            {
                if (!_flash.Equals(value))
                {
                    _flash = value;
                    OnPropertyChanged("Flash");
                }
            }
        }

        private string _description = "I am an alarm!";
        public string Description
        {
            get { return _description; }
            set
            {
                if(!_description.Equals(value))
                {
                    _description = value;
                    OnPropertyChanged("Description");
                }
            }
        }
    }

    public abstract class NotifyPropertyChangedBase<T> : DependencyObject, INotifyPropertyChanged
    {

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            { PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName)); }
        }

        protected virtual void OnPropertyChanged<T2>(Expression<Func<T, T2>> accessor)
        {
            OnPropertyChanged(PropertyName(accessor));
        }

        public static string PropertyName<T2>(Expression<Func<T, T2>> accessor)
        {
            return ((MemberExpression)accessor.Body).Member.Name;
        }
    }
}

Dictionary1.xaml:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:local="clr-namespace:AnimationSample">

    </Style>
</ResourceDictionary>

LargeUserControl.xaml:

<UserControl x:Class="AnimationSample.LargeUserControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:AnimationSample"
             mc:Ignorable="d" >
    <Border Margin="8"
            Style="{DynamicResource FlashyAlarmBorderStyle}">
        <StackPanel>

            <CheckBox Margin="8" IsChecked="{Binding Alarm}" Content="Turn on the alarm." Foreground="White" />
            <CheckBox Margin="8"  IsChecked="{Binding Flash}" Content="Turn on the flash!" Foreground="White" />

        </StackPanel>
    </Border>
</UserControl>

SmallUserControl.xaml:

<UserControl x:Class="AnimationSample.SmallUserControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:AnimationSample"
             mc:Ignorable="d" >
    <Border Margin="8"
            Style="{DynamicResource FlashyAlarmBorderStyle}">
        <StackPanel>

            <CheckBox Margin="4" IsChecked="{Binding Alarm}" Content="Turn on the alarm." HorizontalAlignment="Center" Foreground="White" />
            <CheckBox Margin="4" IsChecked="{Binding Flash}" Content="Turn on the flash!" HorizontalAlignment="Center" Foreground="White" />
        </StackPanel>
    </Border>
</UserControl>

If you run the code and click on the alarm and flash checkboxes, then the control will go from silver border with black background to a flashing orange. If you move the slider to go from small to large view, you will get a run time from wpf if using the multidatatrigger. If you uncomment the datatrigger in the the Dictionar1.xaml and comment the multidatatrigger, then repeat the above, the application runs ok.

Why does this multidatatrigger gag on DataTemplate change and datatrigger work ok? The only difference from that to the single datatrigger is one extra boolean. How can it be fixed?

(Yes, can work around by creating a property on the viewmodel to aggregate these booleans, but that should not have to be done and is beside question. This seems like a bug with wpf?)

Body:
Remove the setter that sets the same property (Background) that you try to animate:

<MultiDataTrigger>
    <MultiDataTrigger.Conditions>
        <Condition Binding="{Binding Alarm}" Value="True" />
        <Condition Binding="{Binding Flash}" Value="True" />
    </MultiDataTrigger.Conditions>
    <!--<Setter Property="Background" Value="Orange"/>-->
    <Setter Property="BorderBrush" Value="Orange"/>
    <MultiDataTrigger.EnterActions>
        <BeginStoryboard Name="faultBoard">
            <Storyboard>
                <ColorAnimation AutoReverse="True"
                                RepeatBehavior="Forever"
                                Storyboard.TargetProperty="(Border.Background).(SolidColorBrush.Color)"
                                Duration="00:00:01"
                                From="Silver"
                                To="Orange"/>
            </Storyboard>
        </BeginStoryboard>
    </MultiDataTrigger.EnterActions>
    <MultiDataTrigger.ExitActions>
        <StopStoryboard BeginStoryboardName="faultBoard">
        </StopStoryboard>
    </MultiDataTrigger.ExitActions>
</MultiDataTrigger>


来源: stackexchange

问:
ES6 Class - Call method from within event handler
I am trying to write an ES6 class for an interactive calendar on my current project.

The Class looks similar to the below:

```<code>class Calendar {

constructor (s) {

    this.eventButtons = s.eventButtons;
    this.eventButtons.forEach(button => button.addEventListener('click', this.method1);
    this.eventBoxes = s.eventBoxes;

method1 (e) {
    e.preventDefault();
    this.method2(e.target.href);
}

method2 (url) {
    console.log(url);
}

}

export default Calendar;
</code>```

I know that the context of the 'this' keyword has changed from the constructor to the button which has been clicked within the method1 function. However I don't know how to keep the context of the button and the constructor within the same function. I tried changing the button event listener code to the following:

```<code>this.eventButtons.forEach(button => button.addEventListener('click', this.method1).bind(this);
</code>```

But this just switches the context of the 'this' keyword to the constructor rather than the button. I need to use both in my function.

Any ideas? I'm hoping this is quite a common issue?

答:
Since you are using ES6, have you tried using an arrow function?

An arrow function expression has a shorter syntax than a function
  expression and does not bind its own this, arguments, super, or
  new.target. These function expressions are best suited for non-method
  functions, and they cannot be used as constructors.

```<code>method1 = (e) => {
    e.preventDefault();
    this.method2(e.target.href);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to write an ES6 class for an interactive calendar on my current project.

The Class looks similar to the below:

class Calendar {

constructor (s) {

    this.eventButtons = s.eventButtons;
    this.eventButtons.forEach(button => button.addEventListener('click', this.method1);
    this.eventBoxes = s.eventBoxes;

method1 (e) {
    e.preventDefault();
    this.method2(e.target.href);
}

method2 (url) {
    console.log(url);
}

}

export default Calendar;

I know that the context of the 'this' keyword has changed from the constructor to the button which has been clicked within the method1 function. However I don't know how to keep the context of the button and the constructor within the same function. I tried changing the button event listener code to the following:

this.eventButtons.forEach(button => button.addEventListener('click', this.method1).bind(this);

But this just switches the context of the 'this' keyword to the constructor rather than the button. I need to use both in my function.

Any ideas? I'm hoping this is quite a common issue?

Body:
Since you are using ES6, have you tried using an arrow function?

An arrow function expression has a shorter syntax than a function
  expression and does not bind its own this, arguments, super, or
  new.target. These function expressions are best suited for non-method
  functions, and they cannot be used as constructors.

method1 = (e) => {
    e.preventDefault();
    this.method2(e.target.href);
}


问:
How to expand matplolib window without stretching the plot?
I want to increase the grey area around the plot, but keeping the plot the same size. I've already tried changing the figure size, which ends up stretching the plot.

答:
The axes inside the figure is positionned relative to the figure. Per default you have e.g. a fraction of 0.125 of figure width as space at the left. This means that resizing the figure, scales the axes as well.

You may calculate how much the spacings need to change such that if the figure is rescaled, the axes size remains constant. The new spacings then need to be set using fig.subplots_adjust.

```<code>import matplotlib.pyplot as plt

def set_figsize(figw,figh, fig=None):
    if not fig: fig=plt.gcf()
    w, h = fig.get_size_inches()
    l = fig.subplotpars.left
    r = fig.subplotpars.right
    t = fig.subplotpars.top
    b = fig.subplotpars.bottom
    hor = 1.-w/float(figw)*(r-l)
    ver = 1.-h/float(figh)*(t-b)
    fig.subplots_adjust(left=hor/2., right=1.-hor/2., top=1.-ver/2., bottom=ver/2.)

fig, ax=plt.subplots()

ax.plot([1,3,2])

set_figsize(9,7)

plt.show()
</code>```

You may then also use this function to update the subplot params when the figure window is resized.

```<code>import matplotlib.pyplot as plt

class Resizer():
    def __init__(self,fig=None):
        if not fig: fig=plt.gcf()
        self.fig=fig
        self.w, self.h = self.fig.get_size_inches()
        self.l = self.fig.subplotpars.left
        self.r = self.fig.subplotpars.right
        self.t = self.fig.subplotpars.top
        self.b = self.fig.subplotpars.bottom

    def set_figsize(self, figw,figh):
        hor = 1.-self.w/float(figw)*(self.r-self.l)
        ver = 1.-self.h/float(figh)*(self.t-self.b)
        self.fig.subplots_adjust(left=hor/2., right=1.-hor/2., top=1.-ver/2., bottom=ver/2.)

    def resize(self, event):
        figw = event.width/self.fig.dpi
        figh = event.height/self.fig.dpi
        self.set_figsize( figw,figh)

fig, ax=plt.subplots()

ax.plot([1,3,2])

r = Resizer()
cid = fig.canvas.mpl_connect("resize_event", r.resize)

plt.show()
</code>```

Body:
The axes inside the figure is positionned relative to the figure. Per default you have e.g. a fraction of 0.125 of figure width as space at the left. This means that resizing the figure, scales the axes as well.

You may calculate how much the spacings need to change such that if the figure is rescaled, the axes size remains constant. The new spacings then need to be set using fig.subplots_adjust.

import matplotlib.pyplot as plt

def set_figsize(figw,figh, fig=None):
    if not fig: fig=plt.gcf()
    w, h = fig.get_size_inches()
    l = fig.subplotpars.left
    r = fig.subplotpars.right
    t = fig.subplotpars.top
    b = fig.subplotpars.bottom
    hor = 1.-w/float(figw)*(r-l)
    ver = 1.-h/float(figh)*(t-b)
    fig.subplots_adjust(left=hor/2., right=1.-hor/2., top=1.-ver/2., bottom=ver/2.)

fig, ax=plt.subplots()

ax.plot([1,3,2])

set_figsize(9,7)

plt.show()

You may then also use this function to update the subplot params when the figure window is resized.

import matplotlib.pyplot as plt

class Resizer():
    def __init__(self,fig=None):
        if not fig: fig=plt.gcf()
        self.fig=fig
        self.w, self.h = self.fig.get_size_inches()
        self.l = self.fig.subplotpars.left
        self.r = self.fig.subplotpars.right
        self.t = self.fig.subplotpars.top
        self.b = self.fig.subplotpars.bottom

    def set_figsize(self, figw,figh):
        hor = 1.-self.w/float(figw)*(self.r-self.l)
        ver = 1.-self.h/float(figh)*(self.t-self.b)
        self.fig.subplots_adjust(left=hor/2., right=1.-hor/2., top=1.-ver/2., bottom=ver/2.)

    def resize(self, event):
        figw = event.width/self.fig.dpi
        figh = event.height/self.fig.dpi
        self.set_figsize( figw,figh)

fig, ax=plt.subplots()

ax.plot([1,3,2])

r = Resizer()
cid = fig.canvas.mpl_connect("resize_event", r.resize)

plt.show()


问:
AWS public IPv4 in userdata script
I need to dynamically discover the ip4v address of my instance (during userdata script execution and use it to replace some XML. I've tried the following but it doesn't work. Presumably because networking isn't available at the time we the instance runs the userdata script?

Also, to add complexity, assume this instance has no external internet access (so other solutions suggesting curl http://checkip.amazonaws.com/ won't work).

sudo sed -i -e "s,<listenaddress address=\",<listenaddress address=\"$(wget -qO- http://instance-data/latest/meta-data/public-ipv4),g" /tmp/my.config.xml

I'm using the default Amazon AMI (Amazon Linux AMI 2017.03.1 (HVM), SSD Volume Type - ami-ed100689)

Any ideas?

Edit: Full userdata script

```<code>#!/bin/bash
# This script starts a extra small service with 512MB heap.
# USE ONLY FOR DEMOS
sudo useradd myuser
sudo groupadd myuser
sudo usermod -a -G myuser myuser
sudo yum update -y
sudo yum install java-1.8.0-openjdk wget -y
sudo wget https://files.mysite.com/downloads/service/whatever.jar -P /opt
sudo /usr/bin/java8 -jar /opt/whatever.jar -b 64 -t /opt/software
sudo chown -R myuser:myuser /opt/software
sudo cp /opt/software/init.d/serviceFile /etc/init.d

# Other SED commands on /etc/init.d/serviceFile which ARE working

sudo chkconfig --add /etc/init.d/serviceFile

# Start service to generate XML config file
sudo service serviceFile start

# Stop service to release file locks
sudo service serviceFile stop

# Lookup IP and do replacement <-- Problem here
sudo sed -i -e "s,<listenaddress address=\",<listenaddress address=\"$(wget -qO- http://instance-data/latest/meta-data/public-ipv4),g" /opt/software/conf/collector.config.xml

# Restart service
sudo service serviceFile start
</code>```

答:
It is likely /tmp/my.config.xml is created after the execution of the script. Remember everything in /tmp is wiped out when an instance is launched.

I tried it with /home/ec2-user/my.config.xml and it worked.

Title: AWS public IPv4 in userdata script

Body:
I need to dynamically discover the ip4v address of my instance (during userdata script execution and use it to replace some XML. I've tried the following but it doesn't work. Presumably because networking isn't available at the time we the instance runs the userdata script?

Also, to add complexity, assume this instance has no external internet access (so other solutions suggesting curl http://checkip.amazonaws.com/ won't work).

sudo sed -i -e "s,<listenaddress address=\",<listenaddress address=\"$(wget -qO- http://instance-data/latest/meta-data/public-ipv4),g" /tmp/my.config.xml

I'm using the default Amazon AMI (Amazon Linux AMI 2017.03.1 (HVM), SSD Volume Type - ami-ed100689)

Any ideas?

Edit: Full userdata script

#!/bin/bash
# This script starts a extra small service with 512MB heap.
# USE ONLY FOR DEMOS
sudo useradd myuser
sudo groupadd myuser
sudo usermod -a -G myuser myuser
sudo yum update -y
sudo yum install java-1.8.0-openjdk wget -y
sudo wget https://files.mysite.com/downloads/service/whatever.jar -P /opt
sudo /usr/bin/java8 -jar /opt/whatever.jar -b 64 -t /opt/software
sudo chown -R myuser:myuser /opt/software
sudo cp /opt/software/init.d/serviceFile /etc/init.d

# Other SED commands on /etc/init.d/serviceFile which ARE working

sudo chkconfig --add /etc/init.d/serviceFile

# Start service to generate XML config file
sudo service serviceFile start

# Stop service to release file locks
sudo service serviceFile stop

# Lookup IP and do replacement <-- Problem here
sudo sed -i -e "s,<listenaddress address=\",<listenaddress address=\"$(wget -qO- http://instance-data/latest/meta-data/public-ipv4),g" /opt/software/conf/collector.config.xml

# Restart service
sudo service serviceFile start


问:
Peer to Peer Voice chat between via bluetooth or in a local WiFi network in iOS
I want to implement the voice chat between two iOS devices without using WiFi or cellular network within the range of Bluetooth.

I have done the text chat within Bluetooth range using multipeer connectivity framework, But I also want to do voice chat like text chat within the Bluetooth range.

I found that we can implement the voice chat using GameKit but I have not found any reference of tutorial yet, How to Implement voice chat.

UPDATE:
I found that the GameKit VoiceChatService has been deprecated after iOS 7.0.
is There another way to call another iOS device on the same network.

I found that this app https://itunes.apple.com/us/app/ip2pvoicechat-bluetooth-wifi/id908638157?mt=8 work calls the user on the same wifi network.

Thanks in advance.

答:
If you already have a Bluetooth connection, you should just start sending chunks of audio data.

I made a library years ago that can read / play audio stream. See eppz!capture for more. EPPZCapture and EPPZCaptureBufferParser in particular. They provide / consume CMSampleBufferRef together.

I don't support this code, but you can use it as some source of inspiration for your own streaming code.

However, there are countless libraries for that, like https://github.com/tumtumtum/StreamingKit, https://github.com/muhku/FreeStreamer, https://github.com/mattgallagher/AudioStreamer.

Furthermore, I think you can still use GKVoiceChat, classes are there. Docs above don't even show deprecation (while the compiler may show).


问:
Conflict between div scrollbar and browser scrollbar
I have a div and I want to attach a scrollbar to it to keep the menu fixed (Tab1 here).

BODY
{
 font-size:0.8em;
    MARGIN: 0px 0px 0px 10px;
 COLOR: #000;
    FONT-FAMILY: Tahoma, Verdana, Arial, Helvetica, sans-serif;
    BACKGROUND-COLOR: #ffffff;
 background: url(null) fixed #ffffff;
}

H1
{
    MARGIN-TOP: 20px;
    FONT-WEIGHT: bold;
    FONT-SIZE: 16px;
    MARGIN-BOTTOM: 10px;
 COLOR: #A1006B;
    TEXT-ALIGN: left;
    FONT-VARIANT: normal
}

#tabs-1 {
font-size: 14px;}
.ui-widget-header{
background:#ffff;
}

#tabs-2 {
overflow-y:scroll;
height:100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><title>Test</title>

<link rel="stylesheet" type="text/css" href="../style/test.css" />

 <div id="tabs-1">
<ul>
<li>Tab 1</li>
</ul>

<div id="tabs-2">

 <h1>Test</h1>
<p class="Comment"> <div>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</div>
<ul>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
</ul></p>

 <h1>Test</h1>
<p class="Comment"> <div>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</div>
<ul>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
</ul></p>

 <h1>Test</h1>
<p class="Comment"> <div>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</div>
<ul>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
</ul></p>

 <h1>Test</h1>
<p class="Comment"> <div>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</div>
<ul>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
</ul></p>

 <h1>Test</h1>
<p class="Comment"> <div>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</div>
<ul>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
</ul></p>

 <h1>Test</h1>
<p class="Comment"> <div>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</div>
<ul>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
</ul></p>

 <h1>Test</h1>
<p class="Comment"> <div>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</div>
<ul>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
<li>Nunc nec erat nulla. Donec viverra eu quam ac facilisis.</li>
</ul></p>

</div></code>```

Here's my CSS for the div scrollbar :

#tabs-2 { overflow-y:scroll; height:100%; }
```

When i'm using a fixed height value (like 400px), it works but I have a lot of pages with the same div but different height so this value will not works for every div.

I want to get rid of the browser scrollbar and only use a div scrollbar.

Is there any way to make a scrollbar that adapt dynamically for any div height?

答:
Changing css will solve the problem,

```<code>#tabs-2 {
  overflow-y:scroll;
  height:100%;
  width:100%; **Added
  position:absolute; **Added
}
BODY {
  font-size:0.8em;
  MARGIN: 0px 0px 0px 10px;
  COLOR: #000;
  FONT-FAMILY: Tahoma, Verdana, Arial, Helvetica, sans-serif;
  BACKGROUND-COLOR: #ffffff;
  background: url(null) fixed #ffffff;
  overflow:hidden;
}
</code>```

Hope helps,

Body:
I have a div and I want to attach a scrollbar to it to keep the menu fixed (Tab1 here).

BODY
{
 font-size:0.8em;
    MARGIN: 0px 0px 0px 10px;
 COLOR: #000;
    FONT-FAMILY: Tahoma, Verdana, Arial, Helvetica, sans-serif;
    BACKGROUND-COLOR: #ffffff;
 background: url(null) fixed #ffffff;
}

H1
{
    MARGIN-TOP: 20px;
    FONT-WEIGHT: bold;
    FONT-SIZE: 16px;
    MARGIN-BOTTOM: 10px;
 COLOR: #A1006B;
    TEXT-ALIGN: left;
    FONT-VARIANT: normal
}

#tabs-1 {
font-size: 14px;}
.ui-widget-header{
background:#ffff;
}

#tabs-2 {
overflow-y:scroll;
height:100%;
}

<title>Test</title>

<link rel="stylesheet" type="text/css" href="../style/test.css" />

Tab 1

Test

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Test

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Test

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Test

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Test

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Test

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Test

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Nunc nec erat nulla. Donec viverra eu quam ac facilisis.

Here's my CSS for the div scrollbar :

#tabs-2 { overflow-y:scroll; height:100%; }

When i'm using a fixed height value (like 400px), it works but I have a lot of pages with the same div but different height so this value will not works for every div.

I want to get rid of the browser scrollbar and only use a div scrollbar.

Is there any way to make a scrollbar that adapt dynamically for any div height?

Body:
Changing css will solve the problem,

#tabs-2 {
  overflow-y:scroll;
  height:100%;
  width:100%; **Added
  position:absolute; **Added
}
BODY {
  font-size:0.8em;
  MARGIN: 0px 0px 0px 10px;
  COLOR: #000;
  FONT-FAMILY: Tahoma, Verdana, Arial, Helvetica, sans-serif;
  BACKGROUND-COLOR: #ffffff;
  background: url(null) fixed #ffffff;
  overflow:hidden;
}

Hope helps,


问:
Win8.1 will fire unload and load event to the WPF application when we close and reconnect to this machine using RDC from win7 or other OS
This is a strange issue only in Win8.1.

As we all know, if there is a running application in a machine, there should not be any other behavior against the application when we connect/disconnect/reconnect to this machine by Remote Desktop Connection. However, we found that Win8.1 will fire unload and load events to the WPF application when we close and reconnect to the machine using RDC. And this is an unwanted behavior which may cause error.

Here are the stable reproduce steps:

Write a WPF application which contains a button and handles the unload and load events of this button.

Using RDC to connect to a Win8.1 from Win7 for example.

In the remote desktop, run this WPF app.(a load event will be recorded in a.txt).

Close the RDC by clicking the 'x'.

Connect to this Win8.1 again.

You will see the unload and load events have been fired.

If the WPF app runs in Win7 or Win server 2008, those events will not be fired.

So, I think it is a unwanted behavior in Win8.1. Is that a bug in Win8.1 RDP? Or is that a new feature?

答:
This occurs because reconnecting RDP notifies the WPF code that session and screen has changed. WPF needs to rebuild its DirectX resources and probably handle an updated screen size (even though resolution may be the same). This makes sense b/c the RDP client can specify different capabilities such as the graphics level and other properties from the RDP "Experience" tab. WPF does not determine that the parameters are all the same as the last time a connection occurred and it triggers a new render and layout cycle (makes sense since colors and screen resolution may have changed). This leads to controls being re-loaded and a new Loaded event firing.

You can see much of the gory details of this by examining HwndTarget.cs in the .NET source. Search this file for "session" and you'll see a LOT of handling for session disconnect/reconnect.

http://referencesource.microsoft.com/#PresentationCore/Core/CSharp/System/Windows/Interop/HwndTarget.cs,f20f989ef219e391

If you want to find a way to avoid doing extra work in your Loaded/Unloaded code you may have to move it to a function which you make sure you only call once via a flag or null check.

You can witness what's happening by adding a breakpoint on your Loaded event handler and going to Tools > Options, Debugging and un-check "Enable Just My Code",  and check "Enable .NET framework source stepping" and check "Enable Source Server" support.  When you connect RDP, the bkpt will trigger and the call stack will show a resize event among other levels of calls. This was probably due to WPF getting a WM_DISPLAYCHANGE as well and having everything re-layout in case there's more or less resolution with this connection.

ContentLicense: CC BY-SA 4.0


问:
How can you have a Tab Bar Controller and a Table View?
I am trying to make it so that on one of the tabs there is a table view

Any ideas?

Thanks

答:
Use Interface builder to create a Tab Bar Controller and on one of the tabs add a Table View Controller. This is pretty basic and just requires dragging and dropping in Interface Builder and then connecting the outlets in Xcode.

There are plenty of tutorials online for this.

ContentLicense: CC BY-SA 2.5


问:
Using numpy masking in cython
I'm trying to convert some of my Python code to Cython and experience some issues when I try to define a function as cdef.

Most of the issues boil down to masking not working as in Python. I wonder if this is a limitation of cdef (works fine if I leave it as def) or whether there's something I could do.

For instance this method

```<code>cdef func(double[:,:,:,:] arg1):
    mask = arg1 > 0
    ...
</code>```

already fails with a compile error:

```<code>Error compiling Cython file:
------------------------------------------------------------ ...
    func (double[:,:,:,:] arg1):
        mask = arg1 > 0
                   ^
------------------------------------------------------------

cythonfile.pyx:43:20: Invalid types for '>' (double[:, :, :, :], long)
</code>```

答:
The double[:,:,:,:] notation specifies that the argument will be "interpreted" as Typed Memoryview. These support a lot of operations but the vectorized comparisons are not supported.

However it's quite easy to interpret a memory-view as NumPy array inside the function:

```<code>import numpy as np

cdef func(double[:,:,:,:] arg1):
    arg1arr = np.asarray(arg1)
    mask = arg1arr > 0.
</code>```

That doesn't even need a copy so it's basically "free" to do the np.asarray on the memory-view. That allows to combine the advantages of the memory-views with the vectorized operations that are possible on NumPy arrays.

However for vectorized operations you don't need Cython, you could do all the vectorized operations in a pure python function and only use Cython for the heavy-lifting that isn't possible with "normal NumPy" functions.

Title: Using numpy masking in cython

Body:
I'm trying to convert some of my Python code to Cython and experience some issues when I try to define a function as cdef.

Most of the issues boil down to masking not working as in Python. I wonder if this is a limitation of cdef (works fine if I leave it as def) or whether there's something I could do.

For instance this method

cdef func(double[:,:,:,:] arg1):
    mask = arg1 > 0
    ...

already fails with a compile error:

Error compiling Cython file:
------------------------------------------------------------ ...
    func (double[:,:,:,:] arg1):
        mask = arg1 > 0
                   ^
------------------------------------------------------------

cythonfile.pyx:43:20: Invalid types for '>' (double[:, :, :, :], long)

Body:
The double[:,:,:,:] notation specifies that the argument will be "interpreted" as Typed Memoryview. These support a lot of operations but the vectorized comparisons are not supported.

However it's quite easy to interpret a memory-view as NumPy array inside the function:

import numpy as np

cdef func(double[:,:,:,:] arg1):
    arg1arr = np.asarray(arg1)
    mask = arg1arr > 0.

That doesn't even need a copy so it's basically "free" to do the np.asarray on the memory-view. That allows to combine the advantages of the memory-views with the vectorized operations that are possible on NumPy arrays.

However for vectorized operations you don't need Cython, you could do all the vectorized operations in a pure python function and only use Cython for the heavy-lifting that isn't possible with "normal NumPy" functions.


问:
Android fadein activity removes content too early
I'm trying to make transition effect when clicking on listview item to open new activity.
The problem is when list item clicked - activity with list becomes white and content disappear instantly, then i see first part animation and then custom animation from newly created activity.
How can i make this content to disappear slowly?

```<code>v.getContext().startActivity(intent);

((Activity) v.getContext()).overridePendingTransition(R.anim.list_fadein, R.anim.list_fadeout);
</code>```

fadein:

```<code>xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/linear_interpolator">
<alpha
    android:duration="800"
    android:fromAlpha="0.1"
    android:toAlpha="1" />
</code>```

fadeout:

```<code>xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/linear_interpolator">
<alpha
    android:duration="0"
    android:fromAlpha="1"
    android:toAlpha="1" />
</code>```

I have another custom animation in new activity, so i dont care about second part (fadeout)

答:
You have set,

android:duration="0"

Try this,

```<code><?xml version="1.0" encoding="UTF-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<alpha
    android:fromAlpha="1.0"
    android:toAlpha="0.0"
    android:interpolator="@android:anim/accelerate_interpolator"
    android:duration="1500"
    android:repeatCount="0" />
</code>```

Here duration is the time to make it disappear.

Body:
I'm trying to make transition effect when clicking on listview item to open new activity.
The problem is when list item clicked - activity with list becomes white and content disappear instantly, then i see first part animation and then custom animation from newly created activity.
How can i make this content to disappear slowly?

v.getContext().startActivity(intent);

((Activity) v.getContext()).overridePendingTransition(R.anim.list_fadein, R.anim.list_fadeout);

fadein:

xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/linear_interpolator">
<alpha
    android:duration="800"
    android:fromAlpha="0.1"
    android:toAlpha="1" />

fadeout:

xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/linear_interpolator">
<alpha
    android:duration="0"
    android:fromAlpha="1"
    android:toAlpha="1" />

I have another custom animation in new activity, so i dont care about second part (fadeout)

Body:
You have set,

android:duration="0"

Try this,

<?xml version="1.0" encoding="UTF-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<alpha
    android:fromAlpha="1.0"
    android:toAlpha="0.0"
    android:interpolator="@android:anim/accelerate_interpolator"
    android:duration="1500"
    android:repeatCount="0" />

Here duration is the time to make it disappear.


问:
Reloading Express App not working (Angular Frontend)
I'm currently building a Express App with an AngularJS Frontend, and I've come across a rather annoying bug or error in my code, which I can't seem to figure out.

Every Time I try to reload any part of my Page I get the Error (Cannot GET /View1). This is my main Express Route.

```<code>app.get('/', function(req, res) {
     res.sendfile('./public/index.html');
});
</code>```

What I tried:

I've seen other discussions on this topic and they suggest to redirect all routes to Angular, so I tried this:

```<code>app.get('*', function(req, res) {
 res.sendfile('./public/index.html');
});
</code>```

and setting a base url in my index.html.

The Problem now:

This seems to be working but I also built a Express Rest Api and all the sudden I don't get any request parameters in my Api Calls.

```<code>app.get('/api/location', function(req, res) {
var location = req.query;
Events.getEventsbyLocation(location, function (err, event) {
    if(err){
        throw err;
    }
    res.json(event);
})
});
</code>```

req.query will always be undefined even though it was working perfectly before. I think AngularJs redirects all API calls before request parameters can be submitted.

Anybody else come across this Problem?  Any Help would be highly appreciated.

答:
The app.get('/api/location', function(req, res) {...}) in your express server script has to be before the app.get('*', function(req, res) {...}) route, because express takes the route which matches at first.

Additionally the correct route must be app.get('/api/:location', function(req, res) {...}). The : indicates a query parameter. Now you can read the location with var location = req.params.location.

```<code>app.get('/api/:location', function(req, res) {
var location = req.params.location;
Events.getEventsbyLocation(location, function (err, event) {
    if(err){
        throw err;
    }
    res.json(event);
})
});

app.get('*', function(req, res) {
 res.sendfile('./public/index.html');
});
</code>```

For parsing /api/location?lat=42&lng=42 you can use:

```<code>app.get('/api/location', function(req, res) {
var location = { lat: req.query.lat, lng: req.query.lng };
});
</code>```

req.querycontains every query parameter. If you request api/location?lat=42&lng=42&foo=bar you would get this object:

```<code>{
  lat: 42,
  lng: 42,
  foo: bar
}
</code>```

Body:
I'm currently building a Express App with an AngularJS Frontend, and I've come across a rather annoying bug or error in my code, which I can't seem to figure out.

Every Time I try to reload any part of my Page I get the Error (Cannot GET /View1). This is my main Express Route.

app.get('/', function(req, res) {
     res.sendfile('./public/index.html');
});

What I tried:

I've seen other discussions on this topic and they suggest to redirect all routes to Angular, so I tried this:

app.get('*', function(req, res) {
 res.sendfile('./public/index.html');
});

and setting a base url in my index.html.

The Problem now:

This seems to be working but I also built a Express Rest Api and all the sudden I don't get any request parameters in my Api Calls.

app.get('/api/location', function(req, res) {
var location = req.query;
Events.getEventsbyLocation(location, function (err, event) {
    if(err){
        throw err;
    }
    res.json(event);
})
});

req.query will always be undefined even though it was working perfectly before. I think AngularJs redirects all API calls before request parameters can be submitted.

Anybody else come across this Problem?  Any Help would be highly appreciated.

Body:
The app.get('/api/location', function(req, res) {...}) in your express server script has to be before the app.get('*', function(req, res) {...}) route, because express takes the route which matches at first.

Additionally the correct route must be app.get('/api/:location', function(req, res) {...}). The : indicates a query parameter. Now you can read the location with var location = req.params.location.

app.get('/api/:location', function(req, res) {
var location = req.params.location;
Events.getEventsbyLocation(location, function (err, event) {
    if(err){
        throw err;
    }
    res.json(event);
})
});

app.get('*', function(req, res) {
 res.sendfile('./public/index.html');
});

For parsing /api/location?lat=42&lng=42 you can use:

app.get('/api/location', function(req, res) {
var location = { lat: req.query.lat, lng: req.query.lng };
});

req.querycontains every query parameter. If you request api/location?lat=42&lng=42&foo=bar you would get this object:

{
  lat: 42,
  lng: 42,
  foo: bar
}


问:
failed to find target with hash string android-23
When trying to build OpenStreetMapView from git://github.com/osmdroid/osmdroid, I get this error:

```<code>failed to find target with hash string android-23: D:\Users\myusername\AppData\Local\Android
</code>```

How can I fix this? Previous questions similar to this suggest checking that android 23 is not installed, but in my case, it is.

Below is some pertinent info:

ANDROID_HOME is D:\Users\myusername\AppData\Local\Android\sdk

D:\Users\myusername\AppData\Local\Android\sdk\platforms\ contains the directory \android-23\, (as well as android-19, android-21, android-22, android-MNC)

build.gradle

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.1"

    defaultConfig {
        applicationId "org.osmdroid.example"
        minSdkVersion 8
        targetSdkVersion 23
        versionCode 16
        versionName "4.4-SNAPSHOT"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    packagingOptions {
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/NOTICE'

    }
    lintOptions {
        abortOnError false
    }
}

dependencies {
    compile 'android.support:compatibility-v4:23+'
    compile project(':osmdroid-android')
    //compile 'org.osmdroid:osmdroid-third-party:4.4-SNAPSHOT'
}
</code>```

I tried changing targetSdkVersion and compileSdkVersion to 22. This causes the error message to change to "android-22" instead of "android-23".

SDK Manager:

答: Tools > Android > SDK Manager.

Body:
When trying to build OpenStreetMapView from git://github.com/osmdroid/osmdroid, I get this error:

failed to find target with hash string android-23: D:\Users\myusername\AppData\Local\Android

How can I fix this? Previous questions similar to this suggest checking that android 23 is not installed, but in my case, it is.

Below is some pertinent info:

ANDROID_HOME is D:\Users\myusername\AppData\Local\Android\sdk

D:\Users\myusername\AppData\Local\Android\sdk\platforms\ contains the directory \android-23\, (as well as android-19, android-21, android-22, android-MNC)

build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.1"

    defaultConfig {
        applicationId "org.osmdroid.example"
        minSdkVersion 8
        targetSdkVersion 23
        versionCode 16
        versionName "4.4-SNAPSHOT"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    packagingOptions {
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/NOTICE'

    }
    lintOptions {
        abortOnError false
    }
}

dependencies {
    compile 'android.support:compatibility-v4:23+'
    compile project(':osmdroid-android')
    //compile 'org.osmdroid:osmdroid-third-party:4.4-SNAPSHOT'
}

I tried changing targetSdkVersion and compileSdkVersion to 22. This causes the error message to change to "android-22" instead of "android-23".

SDK Manager:

Body: Tools > Android > SDK Manager.


问:
Symfony use wrong domain to generate absolute URL
I'm currently building a Hal Hateoas RESTful API with BazingaHateoasBundle and Symfony 2.7

Here is my config file :

```<code>MyBundle\Entity\MyEntity:
  relations:
    - rel: self
      href:
        route: get_myentity
        parameters:
          id: expr(object.getId())
        absolute: true
</code>```

In local, I have an apache with a virtual host and my responses are correct :

```<code>{
    "id":1,
    "_links": {
        "self": {
            "href": "http://dev.myvhost/api/myentity/1"
        }
}
</code>```

In my dev server, I have something like this:

```<code>{
    "id":1,
    "_links": {
        "self": {
            "href": "http://my-machine-name/api/myentity/1"
        }
}
</code>```

I don't want my-machine-name but my-server-name.com instead.

And my server Apache config look like this :

```<code>ServerName my-server-name.com
Alias "/api" "/var/www/api/web"

<VirtualHost *:80>
    <Directory /var/www/api/web>
        AllowOverride None
        Require all granted
        Allow from All

        <IfModule mod_rewrite.c>
           Options -MultiViews
           RewriteEngine On
           RewriteCond %{REQUEST_FILENAME} !-f
           RewriteRule ^(.*)$ /api/app.php [QSA,L]
        </IfModule>
    </Directory>

    <Directory /var/www/api/web/bundles>
        <IfModule mod_rewrite.c>
            RewriteEngine Off
        </IfModule>
    </Directory>
    ErrorLog /var/log/httpd/api_error.log
    CustomLog /var/log/httpd/api_access.log combined
</VirtualHost>
</code>```

Is there a way to configure Symfony so that I can set directly the host maybe ?

答:
I think you're missing a step here. That is you need to add the my-server-name.com to the hosts file (of the system).

Here's another helpful link on the topic: Symfony 2 on virtual hosts

Body:
I'm currently building a Hal Hateoas RESTful API with BazingaHateoasBundle and Symfony 2.7

Here is my config file :

MyBundle\Entity\MyEntity:
  relations:
    - rel: self
      href:
        route: get_myentity
        parameters:
          id: expr(object.getId())
        absolute: true

In local, I have an apache with a virtual host and my responses are correct :

{
    "id":1,
    "_links": {
        "self": {
            "href": "http://dev.myvhost/api/myentity/1"
        }
}

In my dev server, I have something like this:

{
    "id":1,
    "_links": {
        "self": {
            "href": "http://my-machine-name/api/myentity/1"
        }
}

I don't want my-machine-name but my-server-name.com instead.

And my server Apache config look like this :

ServerName my-server-name.com
Alias "/api" "/var/www/api/web"

<VirtualHost *:80>
    <Directory /var/www/api/web>
        AllowOverride None
        Require all granted
        Allow from All

        <IfModule mod_rewrite.c>
           Options -MultiViews
           RewriteEngine On
           RewriteCond %{REQUEST_FILENAME} !-f
           RewriteRule ^(.*)$ /api/app.php [QSA,L]
        </IfModule>
    </Directory>

    <Directory /var/www/api/web/bundles>
        <IfModule mod_rewrite.c>
            RewriteEngine Off
        </IfModule>
    </Directory>
    ErrorLog /var/log/httpd/api_error.log
    CustomLog /var/log/httpd/api_access.log combined
</VirtualHost>

Is there a way to configure Symfony so that I can set directly the host maybe ?


问:
should this example not alter the memory address rather than the value at that memory address?
In a book I am reading, C++ from scratch, on page 113 the writer creates a char array:

```<code>myString[80];
</code>```

then he uses a function that copies some charectars:

```<code>strcpy(myString,"Hello there");
</code>```

then he creates a pointer to the array:

```<code>*p1 = myString;
</code>```

then he uses an offset and assings a value at that offset:

```<code>p1[4]='c';
</code>```

my question is, p1 is a pointer so it is a memory address, and the offset of 4 gives him the memory address 4 spaces in front, so that means he is assingning the letter 'c' to the memory address rather than at the value stored at that address. Shouldnt it be:

```<code>*(p1[4])='c';
</code>```

basically, how come *(p1 + 4) needs dereferencing but p1[4] does not?

I tried to understand this and the only thing that could make sense to me was if the square brackets act as an asterisk to dereference the pointer. Is this correct or is there another reason why p1[4] does not need to be dereferenced?

答:
p1[4] is treated as *(p1 + 4) which is "value at an offset of 4 from p1".

Also when you declare a char array:

```<code>myString[80]
</code>```

myString is a pointer to the array (It points to the first element). So when you do myString[4] it is also treated as *(myString + 4)

Writing *(p1[4]) would mean *(*(p1 + 4))

Body:
In a book I am reading, C++ from scratch, on page 113 the writer creates a char array:

myString[80];

then he uses a function that copies some charectars:

strcpy(myString,"Hello there");

then he creates a pointer to the array:

*p1 = myString;

then he uses an offset and assings a value at that offset:

p1[4]='c';

my question is, p1 is a pointer so it is a memory address, and the offset of 4 gives him the memory address 4 spaces in front, so that means he is assingning the letter 'c' to the memory address rather than at the value stored at that address. Shouldnt it be:

*(p1[4])='c';

basically, how come *(p1 + 4) needs dereferencing but p1[4] does not?

I tried to understand this and the only thing that could make sense to me was if the square brackets act as an asterisk to dereference the pointer. Is this correct or is there another reason why p1[4] does not need to be dereferenced?

Body:
p1[4] is treated as *(p1 + 4) which is "value at an offset of 4 from p1".

Also when you declare a char array:

myString[80]

myString is a pointer to the array (It points to the first element). So when you do myString[4] it is also treated as *(myString + 4)

Writing *(p1[4]) would mean *(*(p1 + 4))


问:
variables not populated with desired values
I am trying to make a 'cueent weather application'.
For this, in my jQuery code snippet, I use 2 variables by the name of 'latitude' & 'longitude'.
When I populate them with my current location's latitude & longitude respectively, it happens so quite efficiently, as reflected in my alert popup (the one inside the 'if' statement).
However, outside of this 'if' statement, the variables no longer retain their values, as shown in the 2nd alert popup.

```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background-color : black;
}

.jumbotron {
  background-color : black;
  color : white;
}</code>```

Current Weather</hi>

```

Following is my code ..

https://codepen.io/iamrkcheers/pen/KqxyVZ

Any help is appreciated. Thank You.

答:
Your alert is in the wrong scope.

```<code>if(navigator.geolocation){

    //navigator.geolocation.getCurrentPosition is an asynchronous function
    //we do not know when it will be done
    //but we can tell it what do do when it finished.
    //this is why we pass it a function as parameter

    navigator.geolocation.getCurrentPosition(
      //this here is your callback function :
      function(position){
        latitude = position.coords.latitude;
        longitude = position.coords.longitude;
        alert(latitude + " " + longitude); // only here do we know what latitude and longitude are.
      }
    );

    //since we are not going to synchronously wait until the getCurrentPosition finishes
    //any statement at this point gets executed immediately.
    alert("hey!");
}
</code>```

If you were to run this code, the hey alert would probably pop up first, and then the alert with the coordinates.

Body:
I am trying to make a 'cueent weather application'.
For this, in my jQuery code snippet, I use 2 variables by the name of 'latitude' & 'longitude'.
When I populate them with my current location's latitude & longitude respectively, it happens so quite efficiently, as reflected in my alert popup (the one inside the 'if' statement).
However, outside of this 'if' statement, the variables no longer retain their values, as shown in the 2nd alert popup.

body {
  background-color : black;
}

.jumbotron {
  background-color : black;
  color : white;
}

Current Weather</hi>

Following is my code ..

https://codepen.io/iamrkcheers/pen/KqxyVZ

Any help is appreciated. Thank You.

Body:
Your alert is in the wrong scope.

if(navigator.geolocation){

    //navigator.geolocation.getCurrentPosition is an asynchronous function
    //we do not know when it will be done
    //but we can tell it what do do when it finished.
    //this is why we pass it a function as parameter

    navigator.geolocation.getCurrentPosition(
      //this here is your callback function :
      function(position){
        latitude = position.coords.latitude;
        longitude = position.coords.longitude;
        alert(latitude + " " + longitude); // only here do we know what latitude and longitude are.
      }
    );

    //since we are not going to synchronously wait until the getCurrentPosition finishes
    //any statement at this point gets executed immediately.
    alert("hey!");
}

If you were to run this code, the hey alert would probably pop up first, and then the alert with the coordinates.


问:
Move a div below the current textarea (jquery)
I have a form with several textareas. As an editing aid the list div is filled via ajax with suggestions based on the current input and active textarea.

But the thing is I need to move this div below the active textarea.

I've got the current textarea id but can't find a way to move an element in this particular way.

```<code><div id="list"></div>

            <dt><label for="mazas">Mazas:</label>

            <dd><textarea name="mazas" id="mazas" rows="1" cols="150"></textarea></dd>

            <dt><label for="rayos">Rayos:</label>

            <dd><textarea name="rayos" id="rayos" rows="1" cols="150"></textarea></dd>

            <dt><label for="llantas">Llantas:</label>

            <dd><textarea name="llantas" id="llantas" rows="1" cols="150"></textarea></dd>

            <dt><label for="cubiertas">Cubiertas:</label>

            <dd><textarea name="cubiertas" id="cubiertas" rows="1" cols="150"></textarea></dd>
</code>```

答:
To move it after the textarea with id mazas, for example:

```<code>$("#list").detach().insertAfter($("#mazas"));
</code>```

Body:
I have a form with several textareas. As an editing aid the list div is filled via ajax with suggestions based on the current input and active textarea.

But the thing is I need to move this div below the active textarea.

I've got the current textarea id but can't find a way to move an element in this particular way.

Mazas:

<textarea name="mazas" id="mazas" rows="1" cols="150"></textarea>

Rayos:

<textarea name="rayos" id="rayos" rows="1" cols="150"></textarea>

Llantas:

<textarea name="llantas" id="llantas" rows="1" cols="150"></textarea>

Cubiertas:

<textarea name="cubiertas" id="cubiertas" rows="1" cols="150"></textarea>

Body:
To move it after the textarea with id mazas, for example:

$("#list").detach().insertAfter($("#mazas"));


问:
Auto layout constraints not working properly swift 3.0
Kinda new to this whole auto layout constraints part. My app is closing up on a beta and i'm having trouble getting the constraints right. In the picture below i have succesfully managed to add the following constraints to each object

Horizontally in container

All objects has been pinned top - bottom - left - right to there nearest object.

As you can see in the picture this behaviour results in fine layout for Iphone 6 and larger but when running on a Iphone 5 simulator or Iphone 4 preview, the layout is bad.

What can i do to achieve the same layout behaviour on smaller devices, so that my labels and img does not crop??

Thank you, in advance!

答:
All you need to do is to make your labels have same width with you view controller and then make sure text shows up in center, like this

With this, you are making sure that the text can be centered and be as long as possible. If in this case your label still cannot fully show up, you will need to shrink it. Like calling

```<code>yourLabel.adjustsFontSizeToFitWidth = true
</code>```

Body:
All you need to do is to make your labels have same width with you view controller and then make sure text shows up in center, like this

With this, you are making sure that the text can be centered and be as long as possible. If in this case your label still cannot fully show up, you will need to shrink it. Like calling

yourLabel.adjustsFontSizeToFitWidth = true


问:
Sorting A Character Dataframe According to desired way
I have a dataframe k which contains following strings in the same order:

```<code>6 to 12 months
12 to 24 months
36 to 60 months
60 to 96 months
0 to 6 months
24 to 36 months
96 to 120 months
120 months & above.
</code>```

When I apply the sort command it sorts by the integer values For eg. the string 120 months and above is placed before 6-12 months. Can anyone tell me how to sort it like below using some R command:

```<code>0 to 6 months
6 to 12 months
12 to 24 months
24 to 36 months
36 to 60 months
60 to 96 months
96 to 120 months
120 months & above.
</code>```

答:
What about this:

```<code>require(stringr)

k <- c("6 to 12 months",
       "12 to 24 months",
       "36 to 60 months",
       "60 to 96 months",
       "0 to 6 months",
       "24 to 36 months",
       "96 to 120 months",
       "120 months & above")

index <- sapply(seq_along(k), function(x) stringr::str_split(k, pattern = "\\s")[[x]][1])

df <- data.frame(k, index = as.numeric(index))

df[order(index), ]
</code>```

I think you can scale this to a category of any size (as long as the first part of the string follows some order).

Body:
I have a dataframe k which contains following strings in the same order:

6 to 12 months
12 to 24 months
36 to 60 months
60 to 96 months
0 to 6 months
24 to 36 months
96 to 120 months
120 months & above.

When I apply the sort command it sorts by the integer values For eg. the string 120 months and above is placed before 6-12 months. Can anyone tell me how to sort it like below using some R command:

0 to 6 months
6 to 12 months
12 to 24 months
24 to 36 months
36 to 60 months
60 to 96 months
96 to 120 months
120 months & above.

Body:
What about this:

require(stringr)

k <- c("6 to 12 months",
       "12 to 24 months",
       "36 to 60 months",
       "60 to 96 months",
       "0 to 6 months",
       "24 to 36 months",
       "96 to 120 months",
       "120 months & above")

index <- sapply(seq_along(k), function(x) stringr::str_split(k, pattern = "\\s")[[x]][1])

df <- data.frame(k, index = as.numeric(index))

df[order(index), ]

I think you can scale this to a category of any size (as long as the first part of the string follows some order).


问:
ES6 Class - Call method from within event handler
I am trying to write an ES6 class for an interactive calendar on my current project.

The Class looks similar to the below:

```<code>class Calendar {

constructor (s) {

    this.eventButtons = s.eventButtons;
    this.eventButtons.forEach(button => button.addEventListener('click', this.method1);
    this.eventBoxes = s.eventBoxes;

method1 (e) {
    e.preventDefault();
    this.method2(e.target.href);
}

method2 (url) {
    console.log(url);
}

}

export default Calendar;
</code>```

I know that the context of the 'this' keyword has changed from the constructor to the button which has been clicked within the method1 function. However I don't know how to keep the context of the button and the constructor within the same function. I tried changing the button event listener code to the following:

```<code>this.eventButtons.forEach(button => button.addEventListener('click', this.method1).bind(this);
</code>```

But this just switches the context of the 'this' keyword to the constructor rather than the button. I need to use both in my function.

Any ideas? I'm hoping this is quite a common issue?

答:
Try using a lambda expression to set the delegate of your event as well. Something like below:</p>

```<code>button.addEventListener('click', (e) => { e.preventDefault(); this.method2(); });
</code>```

Body:
I am trying to write an ES6 class for an interactive calendar on my current project.

The Class looks similar to the below:

class Calendar {

constructor (s) {

    this.eventButtons = s.eventButtons;
    this.eventButtons.forEach(button => button.addEventListener('click', this.method1);
    this.eventBoxes = s.eventBoxes;

method1 (e) {
    e.preventDefault();
    this.method2(e.target.href);
}

method2 (url) {
    console.log(url);
}

}

export default Calendar;

I know that the context of the 'this' keyword has changed from the constructor to the button which has been clicked within the method1 function. However I don't know how to keep the context of the button and the constructor within the same function. I tried changing the button event listener code to the following:

this.eventButtons.forEach(button => button.addEventListener('click', this.method1).bind(this);

But this just switches the context of the 'this' keyword to the constructor rather than the button. I need to use both in my function.

Any ideas? I'm hoping this is quite a common issue?

Body:
Try using a lambda expression to set the delegate of your event as well. Something like below:

button.addEventListener('click', (e) => { e.preventDefault(); this.method2(); });


问:
Error: reCAPTCHA container is either not found or already contains inner elements
I am trying Phone number authentication using Ionic2/typescript and initialising the recaptcha verifier like this:

.ts file

```<code>    import firebase from 'firebase';

     @IonicPage()
     @Component({
       selector: 'page-login',
       templateUrl: 'login.html',
     })

     export class LoginPage {

    public recaptchaVerifier:firebase.auth.RecaptchaVerifier;
           constructor(afAuth: AngularFireAuth, public authData: AuthProvider, public alertController: AlertController, formBuilder: FormBuilder, public navCtrl: NavController, public navParams: NavParams) {
             this.loginForm = formBuilder.group({
               phone: ['', Validators.compose([Validators.required,
                 Validator.isValidPhone])]
             });
             try {
               this.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container');
             }catch(e){
               console.log("There was a problem in initializing the recapctha verifier: " + e);
             }
             this.authData.recaptchaVerifier = this.recaptchaVerifier;
           }
}
</code>```

.html file

```<code><ion-content padding>
  <div id="recaptcha-container"></div>
  <form [formGroup]="loginForm" (submit)="loginUser()" novalidate>

    <ion-item>
      <ion-label stacked>Phone Number</ion-label>
      <ion-input #phone formControlName="phone" type="phone" placeholder="10 digit mobile number"
        [class.invalid]="!loginForm.controls.phone.valid &&
          loginForm.controls.phone.dirty"></ion-input>
    </ion-item>
    <ion-item class="error-message" *ngIf="!loginForm.controls.phone.valid  &&
      loginForm.controls.phone.dirty">
      <p>Please enter a valid 10 digit mobile number.</p>
    </ion-item>

    <button ion-button block type="submit">
      Next
    </button>

  </form>

</ion-content>
</code>```

However when I run the code I get:

Error: reCAPTCHA container is either not found or already contains inner elements

Exploring the world of ionic and firebase for the first time, I find it difficult to understand the problem. Anyone encountered and solved this problem before? Any insight will be helpful.

答:
I think that the problem is that

```<code><div id="recaptcha-container"></div>
</code>```

has not been added to the DOM yet (in the constructor of your class).
You have to wait for it to do this.

One thing is that Angular 2 expect you to not access/manipulate the DOM directly. You should do this 'the Angular way', either with ElementRef (here is an example, you have to wait for the ngAfterContentInit lifecycle event) or ViewChild.

Body:
I am trying Phone number authentication using Ionic2/typescript and initialising the recaptcha verifier like this:

.ts file

    import firebase from 'firebase';

     @IonicPage()
     @Component({
       selector: 'page-login',
       templateUrl: 'login.html',
     })

     export class LoginPage {

    public recaptchaVerifier:firebase.auth.RecaptchaVerifier;
           constructor(afAuth: AngularFireAuth, public authData: AuthProvider, public alertController: AlertController, formBuilder: FormBuilder, public navCtrl: NavController, public navParams: NavParams) {
             this.loginForm = formBuilder.group({
               phone: ['', Validators.compose([Validators.required,
                 Validator.isValidPhone])]
             });
             try {
               this.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container');
             }catch(e){
               console.log("There was a problem in initializing the recapctha verifier: " + e);
             }
             this.authData.recaptchaVerifier = this.recaptchaVerifier;
           }
}

.html file

<ion-content padding>

  <form [formGroup]="loginForm" (submit)="loginUser()" novalidate>

    <ion-item>
      <ion-label stacked>Phone Number</ion-label>
      <ion-input #phone formControlName="phone" type="phone" placeholder="10 digit mobile number"
        [class.invalid]="!loginForm.controls.phone.valid &&
          loginForm.controls.phone.dirty"></ion-input>
    </ion-item>
    <ion-item class="error-message" *ngIf="!loginForm.controls.phone.valid  &&
      loginForm.controls.phone.dirty">

Please enter a valid 10 digit mobile number.

    </ion-item>

    <button ion-button block type="submit">
      Next
    </button>

  </form>

</ion-content>

However when I run the code I get:

Error: reCAPTCHA container is either not found or already contains inner elements

Exploring the world of ionic and firebase for the first time, I find it difficult to understand the problem. Anyone encountered and solved this problem before? Any insight will be helpful.

Body:
I think that the problem is that

<div id="recaptcha-container"></div>

has not been added to the DOM yet (in the constructor of your class).
You have to wait for it to do this.

One thing is that Angular 2 expect you to not access/manipulate the DOM directly. You should do this 'the Angular way', either with ElementRef (here is an example, you have to wait for the ngAfterContentInit lifecycle event) or ViewChild.


问:
PostgreSQL aggregate function and missing frame rows
I'm trying to define a PostgreSQL aggregate function that is aware of rows asked for in the frame clause but that are missing.  Specifically, let's consider an aggregate function framer whose job is to return an array consisting of the values aggregated through it, with any missing values in the frame returned as null.  So,

```<code>select
    n,
    v,
    framer(v) over (order by v rows between 2 preceding and 2 following) arr
from (values (1, 3200), (2, 2400), (3, 1600), (4, 2900), (5, 8200)) as v (n, v)
order by v
</code>```

should return

```<code>"n" "v" "arr"
3   1600    {null,null,1600,2400,2900}
2   2400    {null,1600,2400,2900,3200}
4   2900    {1600,2400,2900,3200,8200}
1   3200    {2400,2900,3200,8200,null}
5   8200    {2900,3200,8200,null,null}
</code>```

Basically I want to grab a range of values around each value, and it's important to me to know if I'm missing any to the left or to the right (or potentially both).  Seems simple enough.  I expected something like this to work:

```<code>create aggregate framer(anyelement) (
    sfunc = array_append,
    stype = anyarray,
    initcond = '{}'
);
</code>```

but it returns

```<code>"n" "v" "arr"
3   1600    {1600,2400,2900}
2   2400    {1600,2400,2900,3200}
4   2900    {1600,2400,2900,3200,8200}
1   3200    {2400,2900,3200,8200}
5   8200    {2900,3200,8200}
</code>```

So sfunc is really only being called three times when two of the values are missing.

I haven't been able to think of any non-ridiculous way to capture those missing rows.  It seems like there should be a simple solution, like somehow prepending/appending some sentinel nulls to the data before the aggregate runs, or maybe somehow passing in the index (and frame values) as well as the actual value to the function...

I wanted to implement this as an aggregate because it gave the nicest user-facing experience for what I want to do.  Is there any better way?

FWIW, I'm on postgres 9.6.

答:
Ok, this was an interesting one. :)

I created an aggregate framer(anyarray, anyelement, int) so we can define the
array size according to the window size.

First we replace array_append with our own framer_msfunc:

```<code>CREATE OR REPLACE FUNCTION public.framer_msfunc(arr anyarray, val anyelement, size_ integer)
 RETURNS anyarray
 LANGUAGE plpgsql
AS $function$
DECLARE
    result ALIAS FOR $0;
    null_ val%TYPE := NULL; -- NULL of the same type as `val`
BEGIN

    IF COALESCE(array_length(arr, 1), 0) = 0 THEN
        -- create an array of nulls with the size of `size_`
        result := array_fill(null_, ARRAY[size_]);
    ELSE
        result := arr;
    END IF;

    IF result[size_] IS NULL THEN
        -- first run or after `minvfunc`.
        -- a NULL inserted at the end in `minvfunc` so we want to replace that.
        result[size_] := val;
    ELSE
        -- `minvfunc` not yet called so we just append and drop the first.
        result := (array_append(result, val))[2:];
    END IF;

    RETURN result;

END;
$function$
</code>```

Then we create a minvfunc as it is needed for moving aggregates.

```<code>CREATE OR REPLACE FUNCTION public.framer_minvfunc(arr anyarray, val anyelement, size_ integer)
 RETURNS anyarray
 LANGUAGE plpgsql
AS $function$
BEGIN

    -- drop the first in the array and append a null
    RETURN array_append(arr[2:], NULL);

END;
$function$
</code>```

Then we define the aggregate with the moving aggregate arguments:

```<code>create aggregate framer(anyelement, int) (
    sfunc = framer_msfunc,
    stype = anyarray,
    msfunc = framer_msfunc,
    mstype = anyarray,
    minvfunc = framer_minvfunc,
    minitcond = '{}'
);
</code>```

We put the framer_msfunc as sfunc too since sfunc is required,
but it doesn't really work. It could be replaced with a fuction takes
the same arguments but actually just calls array_append inside so it would actually do something useful.

And here's your example but with a couple more input values.

The frame size should be atleast the size of the window. It doesn't really work with smaller sizes.

```<code>select
    n,
    v,
    framer(v, 5) over (order by v rows between 2 preceding and 2 following) arr
from (values (1, 3200), (2, 2400), (3, 1600), (4, 2900), (5, 8200), (6, 2333), (7, 1500)) as v (n, v)
order by v
;
 n |  v   |            arr
---+------+----------------------------
 7 | 1500 | {NULL,NULL,1500,1600,2333}
 3 | 1600 | {NULL,1500,1600,2333,2400}
 6 | 2333 | {1500,1600,2333,2400,2900}
 2 | 2400 | {1600,2333,2400,2900,3200}
 4 | 2900 | {2333,2400,2900,3200,8200}
 1 | 3200 | {2400,2900,3200,8200,NULL}
 5 | 8200 | {2900,3200,8200,NULL,NULL}
(7 rows)
</code>```

It would be nice if the size could be inferred from the window's size,
but I coulnd't find if it could be done.

Body:
I'm trying to define a PostgreSQL aggregate function that is aware of rows asked for in the frame clause but that are missing.  Specifically, let's consider an aggregate function framer whose job is to return an array consisting of the values aggregated through it, with any missing values in the frame returned as null.  So,

select
    n,
    v,
    framer(v) over (order by v rows between 2 preceding and 2 following) arr
from (values (1, 3200), (2, 2400), (3, 1600), (4, 2900), (5, 8200)) as v (n, v)
order by v

should return

"n" "v" "arr"
3   1600    {null,null,1600,2400,2900}
2   2400    {null,1600,2400,2900,3200}
4   2900    {1600,2400,2900,3200,8200}
1   3200    {2400,2900,3200,8200,null}
5   8200    {2900,3200,8200,null,null}

Basically I want to grab a range of values around each value, and it's important to me to know if I'm missing any to the left or to the right (or potentially both).  Seems simple enough.  I expected something like this to work:

create aggregate framer(anyelement) (
    sfunc = array_append,
    stype = anyarray,
    initcond = '{}'
);

but it returns

"n" "v" "arr"
3   1600    {1600,2400,2900}
2   2400    {1600,2400,2900,3200}
4   2900    {1600,2400,2900,3200,8200}
1   3200    {2400,2900,3200,8200}
5   8200    {2900,3200,8200}

So sfunc is really only being called three times when two of the values are missing.

I haven't been able to think of any non-ridiculous way to capture those missing rows.  It seems like there should be a simple solution, like somehow prepending/appending some sentinel nulls to the data before the aggregate runs, or maybe somehow passing in the index (and frame values) as well as the actual value to the function...

I wanted to implement this as an aggregate because it gave the nicest user-facing experience for what I want to do.  Is there any better way?

FWIW, I'm on postgres 9.6.

Body:
Ok, this was an interesting one. :)

I created an aggregate framer(anyarray, anyelement, int) so we can define the
array size according to the window size.

First we replace array_append with our own framer_msfunc:

CREATE OR REPLACE FUNCTION public.framer_msfunc(arr anyarray, val anyelement, size_ integer)
 RETURNS anyarray
 LANGUAGE plpgsql
AS $function$
DECLARE
    result ALIAS FOR $0;
    null_ val%TYPE := NULL; -- NULL of the same type as `val`
BEGIN

    IF COALESCE(array_length(arr, 1), 0) = 0 THEN
        -- create an array of nulls with the size of `size_`
        result := array_fill(null_, ARRAY[size_]);
    ELSE
        result := arr;
    END IF;

    IF result[size_] IS NULL THEN
        -- first run or after `minvfunc`.
        -- a NULL inserted at the end in `minvfunc` so we want to replace that.
        result[size_] := val;
    ELSE
        -- `minvfunc` not yet called so we just append and drop the first.
        result := (array_append(result, val))[2:];
    END IF;

    RETURN result;

END;
$function$

Then we create a minvfunc as it is needed for moving aggregates.

CREATE OR REPLACE FUNCTION public.framer_minvfunc(arr anyarray, val anyelement, size_ integer)
 RETURNS anyarray
 LANGUAGE plpgsql
AS $function$
BEGIN

    -- drop the first in the array and append a null
    RETURN array_append(arr[2:], NULL);

END;
$function$

Then we define the aggregate with the moving aggregate arguments:

create aggregate framer(anyelement, int) (
    sfunc = framer_msfunc,
    stype = anyarray,
    msfunc = framer_msfunc,
    mstype = anyarray,
    minvfunc = framer_minvfunc,
    minitcond = '{}'
);

We put the framer_msfunc as sfunc too since sfunc is required,
but it doesn't really work. It could be replaced with a fuction takes
the same arguments but actually just calls array_append inside so it would actually do something useful.

And here's your example but with a couple more input values.

The frame size should be atleast the size of the window. It doesn't really work with smaller sizes.

select
    n,
    v,
    framer(v, 5) over (order by v rows between 2 preceding and 2 following) arr
from (values (1, 3200), (2, 2400), (3, 1600), (4, 2900), (5, 8200), (6, 2333), (7, 1500)) as v (n, v)
order by v
;
 n |  v   |            arr
---+------+----------------------------
 7 | 1500 | {NULL,NULL,1500,1600,2333}
 3 | 1600 | {NULL,1500,1600,2333,2400}
 6 | 2333 | {1500,1600,2333,2400,2900}
 2 | 2400 | {1600,2333,2400,2900,3200}
 4 | 2900 | {2333,2400,2900,3200,8200}
 1 | 3200 | {2400,2900,3200,8200,NULL}
 5 | 8200 | {2900,3200,8200,NULL,NULL}
(7 rows)

It would be nice if the size could be inferred from the window's size,
but I coulnd't find if it could be done.


答:
You could create a closure that would send the event and the button. The closure would keep the this context and send the button as well </p>

```<code>button => button.addEventListener('click', event => this.method1(event, button))
</code>```

Title: ES6 Class - Call method from within event handler

Body:
You could create a closure that would send the event and the button. The closure would keep the this context and send the button as well

button => button.addEventListener('click', event => this.method1(event, button))


问:
Storing IDs of table rows
sorry to bother some of you again. But I still haven't found a working answer to my problem.

I have a good old fashioned HTML table. Each reach has its unique ID. What I want to achieve with JavaScript is that this ID gets stored in a variable once I cklick a link on each row.

Might sound easy to you, I am new to JS and I can't figure it out to the end. Could someone help me please?

Thanks!

答:
Since the click event bubbles up the DOM, you can do this by hooking the click event of the table, and then figuring out which row was clicked. This is usually called "event delegation." Something like this (live copy):

```<code>// Hook click on the table
document.getElementById('theTable').onclick = function(e) {
  var element;

  // Handle IE vs. standards
  e = e || window.event;

  // Find out what was clicked (more IE vs. standards)
  element = e.target || e.srcElement;

  // Find the row
  while (element && element.tagName !== "TR") {
    element = element.parentNode;
  }

  // Found it?
  if (element) {
    // Yes, remember the ID and show it
    targetVariable = element.id;
    display("You clicked row " + targetVariable);
  }
};
</code>```

Off-topic: This stuff is made a lot easier if you use a library like jQuery, Prototype, YUI, Closure, or any of several others. For instance, the above code using jQuery looks like this:

```<code>$('#theTable').click(function(event) {
    var target = $(event.target).closest('tr');
    if (target.length > 0 ) {
        targetVariable = target[0].id;
        display("You clicked row " + targetVariable);
    }
});
</code>```

Live copy

Or using one of the new features:

```<code>$('#theTable').delegate('tr', 'click', function(event) {
    targetVariable = this.id;
    display("You clicked row " + targetVariable);
});
</code>```

Live copy

Title: Storing IDs of table rows

Body:
Since the click event bubbles up the DOM, you can do this by hooking the click event of the table, and then figuring out which row was clicked. This is usually called "event delegation." Something like this (live copy):

// Hook click on the table
document.getElementById('theTable').onclick = function(e) {
  var element;

  // Handle IE vs. standards
  e = e || window.event;

  // Find out what was clicked (more IE vs. standards)
  element = e.target || e.srcElement;

  // Find the row
  while (element && element.tagName !== "TR") {
    element = element.parentNode;
  }

  // Found it?
  if (element) {
    // Yes, remember the ID and show it
    targetVariable = element.id;
    display("You clicked row " + targetVariable);
  }
};

Off-topic: This stuff is made a lot easier if you use a library like jQuery, Prototype, YUI, Closure, or any of several others. For instance, the above code using jQuery looks like this:

$('#theTable').click(function(event) {
    var target = $(event.target).closest('tr');
    if (target.length > 0 ) {
        targetVariable = target[0].id;
        display("You clicked row " + targetVariable);
    }
});

Live copy

Or using one of the new features:

$('#theTable').delegate('tr', 'click', function(event) {
    targetVariable = this.id;
    display("You clicked row " + targetVariable);
});

Live copy