问:
How to use datatrigger for rectangle in a usercontrol in c# wpf?
I created a UserControl with a complex rectangle in wpf c#, and I want to trigger the animation with a datatrigger which is boud to a property. If I use eventtrigger within the rectangle, it can work as expected, but if I switch to datatrigger, it failed to animate the rectangle...
For the animation, credit @Val who posted WPF moving arrow with direction change

I've tried including the storyboard within < Rectangle.Resource>, and use _storyboard.begin() in code, but failed animate it.

I've tried including the storyboard inside a  which contains a datatrigger that bound to a property named AnimationStart. And also I tried putting the < Style> both inside < UserControl.Resource> and < Rectangle.Resource>, but neither worked.

I also implemented either INotifyPropertyChanged or DependencyProperty for AnimationStart, but still none of them worked.

the DependencyProperty: IndicationPoints, LineBackgroundColor, LineBackColor works properly.

now the xaml is as follows

```<code> <UserControl.Resources>
        <Style x:Key="animationStyle" TargetType="{x:Type Rectangle}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding AnimationStart}" Value="Start">
                    <DataTrigger.EnterActions>
                        <BeginStoryboard x:Name="StartAnimation">
                            <Storyboard>
                                <DoubleAnimation
                                    From="0"
                                    To="10"
                                    RepeatBehavior="Forever"
                                    Storyboard.TargetProperty="(Rectangle.Fill).(VisualBrush.Transform).(TranslateTransform.X)"
                                    Duration="0:0:0.1" />
                            </Storyboard>
                        </BeginStoryboard>
                    </DataTrigger.EnterActions>
                </DataTrigger>
                <DataTrigger Binding="{Binding AnimationStart}" Value="Stop">
                    <DataTrigger.EnterActions>
                        <StopStoryboard x:Name="StopAnimation" BeginStoryboardName="StartAnimation"/>
                    </DataTrigger.EnterActions>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </UserControl.Resources>

    <Rectangle x:Name="rectangleLine" Style="{StaticResource animationStyle}" Width="auto" Height="auto" Margin="0">
        <Rectangle.RenderTransform>
            <RotateTransform Angle="0" />
        </Rectangle.RenderTransform>
        <Rectangle.Fill>
            <VisualBrush TileMode="Tile" Viewport="0,0,10,8" ViewportUnits="Absolute" Viewbox="0,0,8,8" ViewboxUnits="Absolute">
                <VisualBrush.Transform>
                    <TranslateTransform X="0" Y="0" />
                </VisualBrush.Transform>
                <VisualBrush.Visual>
                    <Grid x:Name="gridMoving">
                        <Polygon x:Name="polygonMovingBack" Fill="{Binding LineBackColor}" Points="0,0 8,0 8,8 0,8" />
                        <Polygon x:Name="polygonMoving" Fill="{Binding LineBackgroundColor}" Points="{Binding IndicationShape}" />
                    </Grid>
                </VisualBrush.Visual>
            </VisualBrush>
        </Rectangle.Fill>
        <Rectangle.Resources>
            <Storyboard x:Key="startAnimation">
                <DoubleAnimation
                    From="0"
                    To="10"
                    RepeatBehavior="Forever"
                    Storyboard.TargetProperty="(Rectangle.Fill).(VisualBrush.Transform).(TranslateTransform.X)"
                    Duration="0:0:0.1" />
            </Storyboard>
        </Rectangle.Resources>

        <!--<Rectangle.Triggers>
            <EventTrigger RoutedEvent="Control.Loaded">
                <EventTrigger.Actions>
                    <BeginStoryboard>
                        <Storyboard>
                            <DoubleAnimation
                                From="0"
                                To="10"
                                RepeatBehavior="Forever"
                                Storyboard.TargetProperty="(Rectangle.Fill).(VisualBrush.Transform).(TranslateTransform.X)"
                                Duration="0:0:0.1" />
                        </Storyboard>
                    </BeginStoryboard>
                </EventTrigger.Actions>
            </EventTrigger>
        </Rectangle.Triggers>-->
    </Rectangle>
</code>```

and the code behind

```<code>
        public PointCollection IndicationPoints
        {
            get
            {
                return (PointCollection)GetValue(IndicationPointsProperty);
            }
            set
            {
                SetValue(IndicationPointsProperty, value);
            }
        }
        public SolidColorBrush LineBackgroundColor
        {
            get
            {
                return (SolidColorBrush)GetValue(LineBackgroundColorProperty);
            }
            set
            {
                SetValue(LineBackgroundColorProperty, value);
            }
        }
        public SolidColorBrush LineBackColor
        {
            get
            {
                return (SolidColorBrush)GetValue(LineBackColorProperty);
            }
            set
            {
                SetValue(LineBackColorProperty, value);
            }
        }
        public string AnimationStart {
            get => _animationStart;
            set {
                _animationStart = value;
                NotifyPropertyChanged("AnimationStart");
            } }

        private string _animationStart;

        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged(string info)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(info));
            }
        }

        public static readonly DependencyProperty IndicationPointsProperty
            = DependencyProperty.Register("IndicationPoints", typeof(PointCollection), typeof(UI_MovingLine), new PropertyMetadata(new PointCollection(new List<Point> { new Point(0,0), new Point(4, 0), new Point(8, 4), new Point(4, 8), new Point(0, 8), new Point(4, 4) }), new PropertyChangedCallback(OnIndicationPointsChanged)));

        public static readonly DependencyProperty LineBackgroundColorProperty
            = DependencyProperty.Register("LineBackgroundColor", typeof(SolidColorBrush), typeof(UI_MovingLine), new PropertyMetadata(new SolidColorBrush(Colors.Gray), new PropertyChangedCallback(OnLineBackgroundColorChanged)));

        public static readonly DependencyProperty LineBackColorProperty
            = DependencyProperty.Register("LineBackColor", typeof(SolidColorBrush), typeof(UI_MovingLine), new PropertyMetadata(new SolidColorBrush(Colors.Gray), new PropertyChangedCallback(OnLineBackColorChanged)));

        private static void OnIndicationPointsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var control = d as UI_MovingLine;
            control.OnIndicationPointsChanged(e);
        }

        private void OnIndicationPointsChanged(DependencyPropertyChangedEventArgs e)
        {
            polygonMoving.Points = (PointCollection)e.NewValue;
        }

        private static void OnLineBackgroundColorChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var control = d as UI_MovingLine;
            control.OnLineBackgroundColorChanged(e);
        }

        private void OnLineBackgroundColorChanged(DependencyPropertyChangedEventArgs e)
        {
            polygonMoving.Fill = (SolidColorBrush)e.NewValue;
        }

        private static void OnLineBackColorChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var control = d as UI_MovingLine;
            control.OnLineBackColorChanged(e);
        }

        private void OnLineBackColorChanged(DependencyPropertyChangedEventArgs e)
        {
            polygonMovingBack.Fill = (SolidColorBrush)e.NewValue;
        }

        public UI_MovingLine()
        {
            InitializeComponent();
            gridMoving.DataContext = this;
            polygonMoving.DataContext = this;
            LineMovingToNomal();
        }

        public void LineMovingToNomal()
        {
            try
            {
                _transmitLineStatus = PowerSystem.TransmitLineStatus.TLS_NORMAL;
                IndicationPoints = new PointCollection(new List<Point> { new Point(0, 0), new Point(4, 0), new Point(8, 4), new Point(4, 8), new Point(0, 8), new Point(4, 4) });
                LineBackgroundColor = new SolidColorBrush(Colors.DodgerBlue);
                LineBackColor = new SolidColorBrush(Colors.White);

                AnimationStart = "Start";
            }
            catch
            {
            }
        }
</code>```

答: Bit difficult to help you track this down without an MCVE but try setting your RenderTransform and Fill properties using setters inside the style rather than trying to override them in the Rectangle control itself.</p>

Body:
I created a UserControl with a complex rectangle in wpf c#, and I want to trigger the animation with a datatrigger which is boud to a property. If I use eventtrigger within the rectangle, it can work as expected, but if I switch to datatrigger, it failed to animate the rectangle...
For the animation, credit @Val who posted WPF moving arrow with direction change

I've tried including the storyboard within < Rectangle.Resource>, and use _storyboard.begin() in code, but failed animate it.

I've tried including the storyboard inside a  which contains a datatrigger that bound to a property named AnimationStart. And also I tried putting the < Style> both inside < UserControl.Resource> and < Rectangle.Resource>, but neither worked.

I also implemented either INotifyPropertyChanged or DependencyProperty for AnimationStart, but still none of them worked.

the DependencyProperty: IndicationPoints, LineBackgroundColor, LineBackColor works properly.

now the xaml is as follows

 <UserControl.Resources>

        </Style>
    </UserControl.Resources>

    <Rectangle x:Name="rectangleLine" Style="{StaticResource animationStyle}" Width="auto" Height="auto" Margin="0">
        <Rectangle.RenderTransform>
            <RotateTransform Angle="0" />
        </Rectangle.RenderTransform>
        <Rectangle.Fill>
            <VisualBrush TileMode="Tile" Viewport="0,0,10,8" ViewportUnits="Absolute" Viewbox="0,0,8,8" ViewboxUnits="Absolute">
                <VisualBrush.Transform>
                    <TranslateTransform X="0" Y="0" />
                </VisualBrush.Transform>
                <VisualBrush.Visual>
                    <Grid x:Name="gridMoving">
                        <Polygon x:Name="polygonMovingBack" Fill="{Binding LineBackColor}" Points="0,0 8,0 8,8 0,8" />
                        <Polygon x:Name="polygonMoving" Fill="{Binding LineBackgroundColor}" Points="{Binding IndicationShape}" />
                    </Grid>
                </VisualBrush.Visual>
            </VisualBrush>
        </Rectangle.Fill>
        <Rectangle.Resources>
            <Storyboard x:Key="startAnimation">
                <DoubleAnimation
                    From="0"
                    To="10"
                    RepeatBehavior="Forever"
                    Storyboard.TargetProperty="(Rectangle.Fill).(VisualBrush.Transform).(TranslateTransform.X)"
                    Duration="0:0:0.1" />
            </Storyboard>
        </Rectangle.Resources>

    </Rectangle>

and the code behind

        public PointCollection IndicationPoints
        {
            get
            {
                return (PointCollection)GetValue(IndicationPointsProperty);
            }
            set
            {
                SetValue(IndicationPointsProperty, value);
            }
        }
        public SolidColorBrush LineBackgroundColor
        {
            get
            {
                return (SolidColorBrush)GetValue(LineBackgroundColorProperty);
            }
            set
            {
                SetValue(LineBackgroundColorProperty, value);
            }
        }
        public SolidColorBrush LineBackColor
        {
            get
            {
                return (SolidColorBrush)GetValue(LineBackColorProperty);
            }
            set
            {
                SetValue(LineBackColorProperty, value);
            }
        }
        public string AnimationStart {
            get => _animationStart;
            set {
                _animationStart = value;
                NotifyPropertyChanged("AnimationStart");
            } }

        private string _animationStart;

        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged(string info)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(info));
            }
        }

        public static readonly DependencyProperty IndicationPointsProperty
            = DependencyProperty.Register("IndicationPoints", typeof(PointCollection), typeof(UI_MovingLine), new PropertyMetadata(new PointCollection(new List<Point> { new Point(0,0), new Point(4, 0), new Point(8, 4), new Point(4, 8), new Point(0, 8), new Point(4, 4) }), new PropertyChangedCallback(OnIndicationPointsChanged)));

        public static readonly DependencyProperty LineBackgroundColorProperty
            = DependencyProperty.Register("LineBackgroundColor", typeof(SolidColorBrush), typeof(UI_MovingLine), new PropertyMetadata(new SolidColorBrush(Colors.Gray), new PropertyChangedCallback(OnLineBackgroundColorChanged)));

        public static readonly DependencyProperty LineBackColorProperty
            = DependencyProperty.Register("LineBackColor", typeof(SolidColorBrush), typeof(UI_MovingLine), new PropertyMetadata(new SolidColorBrush(Colors.Gray), new PropertyChangedCallback(OnLineBackColorChanged)));

        private static void OnIndicationPointsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var control = d as UI_MovingLine;
            control.OnIndicationPointsChanged(e);
        }

        private void OnIndicationPointsChanged(DependencyPropertyChangedEventArgs e)
        {
            polygonMoving.Points = (PointCollection)e.NewValue;
        }

        private static void OnLineBackgroundColorChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var control = d as UI_MovingLine;
            control.OnLineBackgroundColorChanged(e);
        }

        private void OnLineBackgroundColorChanged(DependencyPropertyChangedEventArgs e)
        {
            polygonMoving.Fill = (SolidColorBrush)e.NewValue;
        }

        private static void OnLineBackColorChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var control = d as UI_MovingLine;
            control.OnLineBackColorChanged(e);
        }

        private void OnLineBackColorChanged(DependencyPropertyChangedEventArgs e)
        {
            polygonMovingBack.Fill = (SolidColorBrush)e.NewValue;
        }

        public UI_MovingLine()
        {
            InitializeComponent();
            gridMoving.DataContext = this;
            polygonMoving.DataContext = this;
            LineMovingToNomal();
        }

        public void LineMovingToNomal()
        {
            try
            {
                _transmitLineStatus = PowerSystem.TransmitLineStatus.TLS_NORMAL;
                IndicationPoints = new PointCollection(new List<Point> { new Point(0, 0), new Point(4, 0), new Point(8, 4), new Point(4, 8), new Point(0, 8), new Point(4, 4) });
                LineBackgroundColor = new SolidColorBrush(Colors.DodgerBlue);
                LineBackColor = new SolidColorBrush(Colors.White);

                AnimationStart = "Start";
            }
            catch
            {
            }
        }


来源: stackexchange

问:
How can a custom sorting script be prevented from eating header row?
I modified the example code provided here to come up with the script below. While it does the job, I have been unable to find a way to prevent it from deleting the header (first) row of the sheet.

A somewhat tangential aside: the following two lines of code at the end of the cited script were removed to sort the sheet without deleting its contents and replacing them with an unformatted array:

```<code>sheet.clear();
sheet.getRange(1,1,rows,cols).setValues(vf);
</code>```

I tried skipping it in all the ranges but either get errors about mismatches between ranges and data or other problems.

function status_sort(){

  var ss=SpreadsheetApp.getActive();

  var sheet = ss.getSheetByName('current');

  var rows = sheet.getLastRow();

  var cols = sheet.getLastColumn();

  var columnToSortBy = 4;

  var rg = sheet.getRange(2, columnToSortBy, sheet.getLastRow(), 1);

  var v1 = rg.getValues();

  var sortObj = {'black_box':1, 'purple_box':2, 'green_box':3, 'yellow_box':4, 'red_box':5,'blue_box':6};

  var col = [];

  for(var i = 0; i < v1.length; i++){

    col.push([sortObj[v1[i]]]);
  }

  sheet.getRange(2, cols + 1, rows, 1).setValues(col);

 sheet.getDataRange().sort([{column:sheet.getLastColumn(),ascending:true}]);

  var vf = sheet.getDataRange().getValues();

    for(var i = 0; i < vf.length; i++){

      vf[i].splice(vf[i].length,1);

    }

}
```

答:
It looks like v1 contains your data (no headers) and you put keys into col which gets appended as an additional column for sorting purposes only, then you sort the whole thing by the keys.  If I'm reading it right your headers ought to be somewhere in the sorted data, since I don't think getDataRange is smart enough to ignore your headers.

I wonder what would happen if you replaced:

```<code>sheet.getDataRange().sort([{column:sheet.getLastColumn(),ascending:true}]);
</code>```

with:

```<code>sortThis = sheet.getRange(2, 1, rows - 1, cols + 1)
sortThis.sort([{column:sheet.getLastColumn(),ascending:true}]);

// getRange parameters:
// 2        : skip a row for the headers
// 1        : start with the leftmost column
// rows - 1 : get one fewer than the original row count (to exclude the headers)
// cols     : get one more than the original column count (to include the extra)
</code>```

As an aside, I think that the loop at the end grabs everything in the sheet and then removes the last column (which was only injected for sorting purposes), and the code that you removed replaces the sheet with the result.  If you're not going to call setValues(vf) then you may as well omit any other code that reference vf too.

Based on https://stackoverflow.com/a/42224466/1054322 I wonder if you might want to use getDisplayValues() instead.  I didn't see a setDisplayValues() in the API reference, so I'm going to guess that your formatting is getting lost on read, and not write, and further that setValues() will not also clobber your formatting.  Not sure if this will interfere with the sorting though, since the displayValues might wrap the data and therefore sort differently.

ContentLicense: CC BY-SA 4.0

Body:
I modified the example code provided here to come up with the script below. While it does the job, I have been unable to find a way to prevent it from deleting the header (first) row of the sheet.

A somewhat tangential aside: the following two lines of code at the end of the cited script were removed to sort the sheet without deleting its contents and replacing them with an unformatted array:

sheet.clear();
sheet.getRange(1,1,rows,cols).setValues(vf);

I tried skipping it in all the ranges but either get errors about mismatches between ranges and data or other problems.

function status_sort(){

  var ss=SpreadsheetApp.getActive();

  var sheet = ss.getSheetByName('current');

  var rows = sheet.getLastRow();

  var cols = sheet.getLastColumn();

  var columnToSortBy = 4;

  var rg = sheet.getRange(2, columnToSortBy, sheet.getLastRow(), 1);

  var v1 = rg.getValues();

  var sortObj = {'black_box':1, 'purple_box':2, 'green_box':3, 'yellow_box':4, 'red_box':5,'blue_box':6};

  var col = [];

  for(var i = 0; i < v1.length; i++){

    col.push([sortObj[v1[i]]]);
  }

  sheet.getRange(2, cols + 1, rows, 1).setValues(col);

 sheet.getDataRange().sort([{column:sheet.getLastColumn(),ascending:true}]);

  var vf = sheet.getDataRange().getValues();

    for(var i = 0; i < vf.length; i++){

      vf[i].splice(vf[i].length,1);

    }

}

Body:
It looks like v1 contains your data (no headers) and you put keys into col which gets appended as an additional column for sorting purposes only, then you sort the whole thing by the keys.  If I'm reading it right your headers ought to be somewhere in the sorted data, since I don't think getDataRange is smart enough to ignore your headers.

I wonder what would happen if you replaced:

sheet.getDataRange().sort([{column:sheet.getLastColumn(),ascending:true}]);

with:

sortThis = sheet.getRange(2, 1, rows - 1, cols + 1)
sortThis.sort([{column:sheet.getLastColumn(),ascending:true}]);

// getRange parameters:
// 2        : skip a row for the headers
// 1        : start with the leftmost column
// rows - 1 : get one fewer than the original row count (to exclude the headers)
// cols     : get one more than the original column count (to include the extra)

As an aside, I think that the loop at the end grabs everything in the sheet and then removes the last column (which was only injected for sorting purposes), and the code that you removed replaces the sheet with the result.  If you're not going to call setValues(vf) then you may as well omit any other code that reference vf too.

Based on https://stackoverflow.com/a/42224466/1054322 I wonder if you might want to use getDisplayValues() instead.  I didn't see a setDisplayValues() in the API reference, so I'm going to guess that your formatting is getting lost on read, and not write, and further that setValues() will not also clobber your formatting.  Not sure if this will interfere with the sorting though, since the displayValues might wrap the data and therefore sort differently.


问:
Get the amount of days between two given days of the week
I want to find out how many days there are between two given days of the week.

This looks to be a case for a well executed slice method; but I just can't get my head around it.

```<code>const days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']

let today = 'Thursday'
let dispatch = 'Monday'
let remaining = '???'

console.log(`${remaining} Days until the next dispatch`)
</code>```

Monday to Thursday is easy enough :

```<code>let remaining = days.slice(days.indexOf('Monday'), days.indexOf('Thursday')).length + 1
</code>```

But Thursday to Monday (for example) needs some logic that I can't figure out.

答:
You can reverse the array if the order is reversed.

const days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']

let today = 'Thursday';
let dispatch = 'Monday';
let reversed, remaining;
if (days.indexOf(today) > days.indexOf(dispatch)) {
  reversed = days.slice().reverse();
  remaining = reversed.slice(reversed.indexOf(today), reversed.indexOf(dispatch)).length + 1;
} else {
  remaining = days.slice(days.indexOf(today), days.indexOf(dispatch)).length + 1;
}

console.log(`${remaining} Days until the next dispatch`)```

Body:
I want to find out how many days there are between two given days of the week.

This looks to be a case for a well executed slice method; but I just can't get my head around it.

const days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']

let today = 'Thursday'
let dispatch = 'Monday'
let remaining = '???'

console.log(`${remaining} Days until the next dispatch`)

Monday to Thursday is easy enough :

let remaining = days.slice(days.indexOf('Monday'), days.indexOf('Thursday')).length + 1

But Thursday to Monday (for example) needs some logic that I can't figure out.


问:
Sandboxing coreWLAN?
I'm writing an OS X application that depends on the ability to determine wireless signal strength, but I can't figure out what entitlements to use to sandbox it.

Whenever I use

```<code>NSMutableArray *scanResults;
CWInterface *currentInterface = [CWInterface interface];
NSLog(@"currInterface: %@\n", currentInterface);
NSMutableDictionary *signalsDict = [[NSMutableDictionary alloc] init];
    NSError *err = nil;
    scanResults = [NSMutableSet setWithSet:[currentInterface scanForNetworksWithSSID:nil error:&err]];
</code>```

I get the error The operation couldn't be completed. (com.apple.coreWLAN.error error 1.) despite having all entitlements checked in XCode. What entitlement(s) am I missing?

The CoreWLANWirelessManager sample project has the same problem.

答: I think you need to check Outgoing Connections (Client).

ContentLicense: CC BY-SA 3.0

Title: Sandboxing coreWLAN?

Body:
I'm writing an OS X application that depends on the ability to determine wireless signal strength, but I can't figure out what entitlements to use to sandbox it.

Whenever I use

NSMutableArray *scanResults;
CWInterface *currentInterface = [CWInterface interface];
NSLog(@"currInterface: %@\n", currentInterface);
NSMutableDictionary *signalsDict = [[NSMutableDictionary alloc] init];
    NSError *err = nil;
    scanResults = [NSMutableSet setWithSet:[currentInterface scanForNetworksWithSSID:nil error:&err]];

I get the error The operation couldn't be completed. (com.apple.coreWLAN.error error 1.) despite having all entitlements checked in XCode. What entitlement(s) am I missing?

The CoreWLANWirelessManager sample project has the same problem.


问:
Return instance of generic type
I wrote a generic class and want to crate its instance from a static method. The problem is that I can’t create generic instance of the object. I know that it sounds confusing and it is better to show the code.

```<code>public class Parameter<T> : IParameter<T>
{
    public string Name { get; set; }
    public T Value { get; set; }

    public bool IsValid()
    {
        if (String.IsNullOrEmpty(Name))
            return false;

        return (typeof(T) == typeof(String)) ||
               typeof(T) == typeof(bool) ||
               typeof(T) == typeof(int) ||
               typeof(T) == typeof(double);
    }

    public XElement ToXml()
    {
        if (!IsValid())
            throw new InvalidParameterException();

        var xElement = new XElement("Parameter", Value,
                                    new XAttribute("Type", typeof (T)),
                                    new XAttribute("Name", Name));
        return xElement;
    }

    public static Parameter<T> FromXml(XElement xElement)
    {
        var sType = xElement.Attributes()
                    .Where(attribute => attribute.Name == "Type")
                    .Single().Name.ToString();
        var name = xElement.Attributes()
                                .Where(attribute => attribute.Name == "Name")
                                .Single().Name.ToString();
        var sValue = xElement.Value;//need to use this
        var typeVar = Type.GetType(sType);// and this to create proper instance of Parameter<T>

        //I need somehow set T equal to typeVar here and Set
        return new Parameter<T>() {Name = name};//this is wrong.
        //I need return either Parameter<int> or Paramter<double> or Parameter<string> or Parameter<bool>
        //basing on typeVar
    }
}
</code>```

I'm not sure if this possible at all... but looks like it is trivial object design requirement. Any ideas?
Thanks!

UPD: I'm using .NET 4.0. Does it make any difference? :)

UPD2: Looking at the problem now I see that this is a silly question. And it is impossible to return such "generic" objects.

答: This does work for custom classes but it may not work for value types.  Take a look at This Post to see how this work for heap types.</p>

Title: Return instance of generic type

Body:
I wrote a generic class and want to crate its instance from a static method. The problem is that I can’t create generic instance of the object. I know that it sounds confusing and it is better to show the code.

public class Parameter<T> : IParameter<T>
{
    public string Name { get; set; }
    public T Value { get; set; }

    public bool IsValid()
    {
        if (String.IsNullOrEmpty(Name))
            return false;

        return (typeof(T) == typeof(String)) ||
               typeof(T) == typeof(bool) ||
               typeof(T) == typeof(int) ||
               typeof(T) == typeof(double);
    }

    public XElement ToXml()
    {
        if (!IsValid())
            throw new InvalidParameterException();

        var xElement = new XElement("Parameter", Value,
                                    new XAttribute("Type", typeof (T)),
                                    new XAttribute("Name", Name));
        return xElement;
    }

    public static Parameter<T> FromXml(XElement xElement)
    {
        var sType = xElement.Attributes()
                    .Where(attribute => attribute.Name == "Type")
                    .Single().Name.ToString();
        var name = xElement.Attributes()
                                .Where(attribute => attribute.Name == "Name")
                                .Single().Name.ToString();
        var sValue = xElement.Value;//need to use this
        var typeVar = Type.GetType(sType);// and this to create proper instance of Parameter<T>

        //I need somehow set T equal to typeVar here and Set
        return new Parameter<T>() {Name = name};//this is wrong.
        //I need return either Parameter<int> or Paramter<double> or Parameter<string> or Parameter<bool>
        //basing on typeVar
    }
}

I'm not sure if this possible at all... but looks like it is trivial object design requirement. Any ideas?
Thanks!

UPD: I'm using .NET 4.0. Does it make any difference? :)

UPD2: Looking at the problem now I see that this is a silly question. And it is impossible to return such "generic" objects.


问:
How to access the range-step value within `toscalar()` statement used within `range()` statement
Am using a Kusto query to create a timechart within Azure AppInsights, to visualize when our webservice is within its SLO (and when it isn't) using one of Google's examples of measuring if a webservice is within its error budget:

```<code>SLI = The proportion of sufficiently fast requests, as measured from the load balancer metrics. “Sufficiently fast” is defined as < 400 ms.
SLO = 90% of requests < 400 ms

Measured as:
count of http_requests with a duration less than or equal to "0.4" seconds
divided by count of all http_requests
</code>```

Assuming 10-minute inspection intervals over a 7-day window, here is my code:

```<code>let fastResponseTimeMaxMs = 400.0;
let errorBudgetThresholdForFastResponseTime = 90.0;
//
let startTime = ago(7days);
let endTime = now();
let timeStep = 10m;
//
let timeRange = range InspectionTime from startTime to endTime step timeStep;
timeRange
    | extend RespTimeMax_ms = fastResponseTimeMaxMs
    | extend ActualCount = toscalar
    (
        requests
            | where timestamp > InspectionTime - timeStep
            | where timestamp <= InspectionTime
            | where success == "True"
            | where duration <= fastResponseTimeMaxMs
            | count
    )
    | extend TotalCount = toscalar
    (
        requests
            | where timestamp > InspectionTime - timeStep
            | where timestamp <= InspectionTime
            | where success == "True"
            | count
    )
    | extend Percentage = round(todecimal(ActualCount * 100) / todecimal(TotalCount), 2)
    | extend ErrorBudgetMinPercent = errorBudgetThresholdForFastResponseTime
    | extend InBudget = case(Percentage >= ErrorBudgetMinPercent, 1, 0)

</code>```

Sample query output of what I wish to achieve:

```<code>InspectionTime [UTC]     RespTimeMax_ms  ActualCount  TotalCount  Percentage  ErrorBudgetMinPercent  InBudget
2019-05-23T21:53:17.894  400             8,098        8,138       99.51       90                     1
2019-05-23T22:03:17.894  400             8,197        9,184       89.14       90                     0
2019-05-23T22:13:17.894  400             8,002        8,555       93.54       90                     1
</code>```

The error I'm getting is:

```<code>'where' operator: Failed to resolve scalar expression named 'InspectionTime'
</code>```

I've tried todatetime(InspectionTime), fails with same error.

Replacing InspectionTime with other objects of type datetime gets this code to execute OK, but not with the datetime values that I want. By example, using this snippet executes OK, when used within my code sample above:

```<code>   | extend ActualCount = toscalar
    (
        requests
            | where timestamp > startTime   // instead of 'InspectionTime - timeStep'
            | where timestamp <= endTime    // instead of 'InspectionTime'
            | where duration <= fastResponseTimeMaxMs
            | count
    )
</code>```

To me it seems that using InspectionTime within toscalar(...) is the crux of this problem, since I'm able to use InspectionTime within similar queries using range(...) that don't nest it within toscalar(...).

Note: I don't want a timechart chart of request.duration, since that doesn't tell me if the count of requests above my threshold (400ms) exceed our error budget according to the formula defined above.

答:
your query is invalid as you can't reference the InspectionTime column in the subquery that you're running in toscalar().

if I understand your desired logic correctly, the following query might work or give you a different direction (if not - you may want to share a sample input dataset using the datatable operator, and specify the desired result that matches it)

```<code>let fastResponseTimeMaxMs = 400.0;
let errorBudgetThresholdForFastResponseTime = 90.0;
//
let startTime = ago(7days);
let endTime = now();
let timeStep = 10m;
//
requests
| where timestamp > startTime and timestamp < endTime
| where success == 'True'
| summarize TotalCount = count(), ActualCount = countif(duration <= fastResponseTimeMaxMs) by bin(timestamp, timeStep)
| extend Percentage = round(todecimal(ActualCount * 100) / todecimal(TotalCount), 2)
| extend ErrorBudgetMinPercent = errorBudgetThresholdForFastResponseTime
| extend InBudget = case(Percentage >= ErrorBudgetMinPercent, 1, 0)
</code>```

Body:
Am using a Kusto query to create a timechart within Azure AppInsights, to visualize when our webservice is within its SLO (and when it isn't) using one of Google's examples of measuring if a webservice is within its error budget:

SLI = The proportion of sufficiently fast requests, as measured from the load balancer metrics. “Sufficiently fast” is defined as < 400 ms.
SLO = 90% of requests < 400 ms

Measured as:
count of http_requests with a duration less than or equal to "0.4" seconds
divided by count of all http_requests

Assuming 10-minute inspection intervals over a 7-day window, here is my code:

let fastResponseTimeMaxMs = 400.0;
let errorBudgetThresholdForFastResponseTime = 90.0;
//
let startTime = ago(7days);
let endTime = now();
let timeStep = 10m;
//
let timeRange = range InspectionTime from startTime to endTime step timeStep;
timeRange
    | extend RespTimeMax_ms = fastResponseTimeMaxMs
    | extend ActualCount = toscalar
    (
        requests
            | where timestamp > InspectionTime - timeStep
            | where timestamp <= InspectionTime
            | where success == "True"
            | where duration <= fastResponseTimeMaxMs
            | count
    )
    | extend TotalCount = toscalar
    (
        requests
            | where timestamp > InspectionTime - timeStep
            | where timestamp <= InspectionTime
            | where success == "True"
            | count
    )
    | extend Percentage = round(todecimal(ActualCount * 100) / todecimal(TotalCount), 2)
    | extend ErrorBudgetMinPercent = errorBudgetThresholdForFastResponseTime
    | extend InBudget = case(Percentage >= ErrorBudgetMinPercent, 1, 0)

Sample query output of what I wish to achieve:

InspectionTime [UTC]     RespTimeMax_ms  ActualCount  TotalCount  Percentage  ErrorBudgetMinPercent  InBudget
2019-05-23T21:53:17.894  400             8,098        8,138       99.51       90                     1
2019-05-23T22:03:17.894  400             8,197        9,184       89.14       90                     0
2019-05-23T22:13:17.894  400             8,002        8,555       93.54       90                     1

The error I'm getting is:

'where' operator: Failed to resolve scalar expression named 'InspectionTime'

I've tried todatetime(InspectionTime), fails with same error.

Replacing InspectionTime with other objects of type datetime gets this code to execute OK, but not with the datetime values that I want. By example, using this snippet executes OK, when used within my code sample above:

   | extend ActualCount = toscalar
    (
        requests
            | where timestamp > startTime   // instead of 'InspectionTime - timeStep'
            | where timestamp <= endTime    // instead of 'InspectionTime'
            | where duration <= fastResponseTimeMaxMs
            | count
    )

To me it seems that using InspectionTime within toscalar(...) is the crux of this problem, since I'm able to use InspectionTime within similar queries using range(...) that don't nest it within toscalar(...).

Note: I don't want a timechart chart of request.duration, since that doesn't tell me if the count of requests above my threshold (400ms) exceed our error budget according to the formula defined above.

Body:
your query is invalid as you can't reference the InspectionTime column in the subquery that you're running in toscalar().

if I understand your desired logic correctly, the following query might work or give you a different direction (if not - you may want to share a sample input dataset using the datatable operator, and specify the desired result that matches it)

let fastResponseTimeMaxMs = 400.0;
let errorBudgetThresholdForFastResponseTime = 90.0;
//
let startTime = ago(7days);
let endTime = now();
let timeStep = 10m;
//
requests
| where timestamp > startTime and timestamp < endTime
| where success == 'True'
| summarize TotalCount = count(), ActualCount = countif(duration <= fastResponseTimeMaxMs) by bin(timestamp, timeStep)
| extend Percentage = round(todecimal(ActualCount * 100) / todecimal(TotalCount), 2)
| extend ErrorBudgetMinPercent = errorBudgetThresholdForFastResponseTime
| extend InBudget = case(Percentage >= ErrorBudgetMinPercent, 1, 0)


问:
In a regular table, is there a way to put an outer border on a table and leave out the table header?
I have a table, and at the top of the table is the table header with some text. I want to be able to only put a border on the table body, and leave the table header untouched, but I don't know how.

I have only tried applying a border to the default class for table body.

    This is some text I want outside of the border

    This is some cell data I want inside the border

```

All I need is for the tbody to be the only bordered thing in the table, and when I try and give it a border, nothing happens.

答:
There are several ways to get this!

First and most straight: add border-collapse to table

```<code>table { border-collapse: collapse }
tbody { border: dashed }
</code>```

2) use outline rather than border

```<code>tbody { outline: dashed }
</code>```

(positive or negative outline-offset: can be used for adjustment)

3) use box-shadow rather than border

```<code>tbody { box-shadow: 0 0 0 1px }
</code>```

Body:
I have a table, and at the top of the table is the table header with some text. I want to be able to only put a border on the table body, and leave the table header untouched, but I don't know how.

I have only tried applying a border to the default class for table body.

    This is some text I want outside of the border

    This is some cell data I want inside the border

All I need is for the tbody to be the only bordered thing in the table, and when I try and give it a border, nothing happens.

Body:
There are several ways to get this!

First and most straight: add border-collapse to table

table { border-collapse: collapse }
tbody { border: dashed }

2) use outline rather than border

tbody { outline: dashed }

(positive or negative outline-offset: can be used for adjustment)

3) use box-shadow rather than border

tbody { box-shadow: 0 0 0 1px }


问:
Oracle How to Map Data Types to CODE/IDs - Dump and dbms_sql.define_column produce data type codes
When using DUMP() or when using dbms_sql.define_column both return the CODE of the Oracle Data type.

Is there a MAP that ties the Oracle Data Types to their Oracle CODEs that are returned by the DUMP() function or the dbms_sql.define_column feature?

I'm looking for this to aid in testing as well as to locate custom data types such as a NESTED TABLE.  A nested table exists in one of my tables and produces a Data Type Code of 109.  How do I lookup the type that is associated with Type Code of 109?  Examples below of dump and dbms_sql.define_column.

I must assume this is available within the database to query due to the fact that when I write a query I define the columns using the 'TEXT' name of the column type and NOT the Code.  So where is the text aka name of my data types  stored whether they are 'built-in' or 'custom'?  It's got to be somewhere.

DUMP

```<code>SELECT
    DUMP(to_date('15-JAN-18'),10,1,1) AS date_type
  , DUMP(123,10,1,1)   AS num_type
  , DUMP('abc',10,1,1) AS var_type
FROM dual
;
</code>```

Dump Output

```<code>/* OUTPUT:
 |
 | "DATE_TYPE"          "NUM_TYPE"          "VAR_TYPE"
 |--------------------|-------------------|------------------
 | "Typ=13 Len=8: 226"  "Typ=2 Len=3: 194"  "Typ=96 Len=3: 97"
*/
</code>```

DBMS_SQL.DEFINE_COLUMN

```<code>... some code above ...

-- Define columns:
FOR i IN 1..n_colcnt
LOOP
    dbms_output.put_line(v_desctab(i).col_name ||': ' || v_desctab(i).col_type);

    IF v_desctab(i).col_type = 2
    THEN dbms_sql.DEFINE_COLUMN(n_curid, i, v_num_var);
    ELSIF v_desctab(i).col_type = 12 THEN
        dbms_sql.define_column(n_curid, i, v_date_var);
    ELSE
        dbms_sql.define_column(n_curid, i, v_name_var, 50);
    END IF;
END LOOP;

... some code below ...
</code>```

DBMS_SQL.DEFINE_COLUMN Output - Outputs column names and their data type CODEs.  I want Text instead.

```<code>QUERY_ID: 2
OTHER_ID: 2
ACTIVE: 1
QUERY_NAME: 1
QUERY_DESC: 1
QUERY_DEF: 112
QUERY_TYPE: 2
CREATED: 12
UPDATED: 12
CREATED_BY: 2
UPDATED_BY: 2
</code>```

One thing I have regarding a mapping of Oracle Data Types to their corresponding IDs is an excel file I continue to reference.  I am hoping there is something I can query within Oracle to give me what I'm looking for rather than referencing an external document.

There is THIS link however this doesn't assist me when I'm looking for Custom Types and it missing documentation for CODE 13.

Here is another very nice Data Type Map somebody put together: Oracle Type Code Mappings

答:
The types are explained here: Oracle Built-in Datatypes.

Type 13 is, I think, how DATEs are represented when they are not part of a table. This is because you are using the to_date function so it only exists as an in-memory structure and I think can vary by architecture. In contrast, values in tables are usually stored in a platform-independent way (I'm pretty sure this is true for numeric types, anyway). Reference.

```<code>create table t1 ( c1 date );
insert into t1 values ( sysdate );
commit;

SELECT
    DUMP(sysdate,10) AS date_type
  , dump(c1, 10) as date_table_type
FROM t1;

Typ=13 Len=8: 227,7,5,30,18,22,0,0
Typ=12 Len=7: 120,119,5,30,19,23,1
</code>```

Body:
When using DUMP() or when using dbms_sql.define_column both return the CODE of the Oracle Data type.

Is there a MAP that ties the Oracle Data Types to their Oracle CODEs that are returned by the DUMP() function or the dbms_sql.define_column feature?

I'm looking for this to aid in testing as well as to locate custom data types such as a NESTED TABLE.  A nested table exists in one of my tables and produces a Data Type Code of 109.  How do I lookup the type that is associated with Type Code of 109?  Examples below of dump and dbms_sql.define_column.

I must assume this is available within the database to query due to the fact that when I write a query I define the columns using the 'TEXT' name of the column type and NOT the Code.  So where is the text aka name of my data types  stored whether they are 'built-in' or 'custom'?  It's got to be somewhere.

DUMP

SELECT
    DUMP(to_date('15-JAN-18'),10,1,1) AS date_type
  , DUMP(123,10,1,1)   AS num_type
  , DUMP('abc',10,1,1) AS var_type
FROM dual
;

Dump Output

/* OUTPUT:
 |
 | "DATE_TYPE"          "NUM_TYPE"          "VAR_TYPE"
 |--------------------|-------------------|------------------
 | "Typ=13 Len=8: 226"  "Typ=2 Len=3: 194"  "Typ=96 Len=3: 97"
*/

DBMS_SQL.DEFINE_COLUMN

... some code above ...

-- Define columns:
FOR i IN 1..n_colcnt
LOOP
    dbms_output.put_line(v_desctab(i).col_name ||': ' || v_desctab(i).col_type);

    IF v_desctab(i).col_type = 2
    THEN dbms_sql.DEFINE_COLUMN(n_curid, i, v_num_var);
    ELSIF v_desctab(i).col_type = 12 THEN
        dbms_sql.define_column(n_curid, i, v_date_var);
    ELSE
        dbms_sql.define_column(n_curid, i, v_name_var, 50);
    END IF;
END LOOP;

... some code below ...

DBMS_SQL.DEFINE_COLUMN Output - Outputs column names and their data type CODEs.  I want Text instead.

QUERY_ID: 2
OTHER_ID: 2
ACTIVE: 1
QUERY_NAME: 1
QUERY_DESC: 1
QUERY_DEF: 112
QUERY_TYPE: 2
CREATED: 12
UPDATED: 12
CREATED_BY: 2
UPDATED_BY: 2

One thing I have regarding a mapping of Oracle Data Types to their corresponding IDs is an excel file I continue to reference.  I am hoping there is something I can query within Oracle to give me what I'm looking for rather than referencing an external document.

There is THIS link however this doesn't assist me when I'm looking for Custom Types and it missing documentation for CODE 13.

Here is another very nice Data Type Map somebody put together: Oracle Type Code Mappings

Body:
The types are explained here: Oracle Built-in Datatypes.

Type 13 is, I think, how DATEs are represented when they are not part of a table. This is because you are using the to_date function so it only exists as an in-memory structure and I think can vary by architecture. In contrast, values in tables are usually stored in a platform-independent way (I'm pretty sure this is true for numeric types, anyway). Reference.

create table t1 ( c1 date );
insert into t1 values ( sysdate );
commit;

SELECT
    DUMP(sysdate,10) AS date_type
  , dump(c1, 10) as date_table_type
FROM t1;

Typ=13 Len=8: 227,7,5,30,18,22,0,0
Typ=12 Len=7: 120,119,5,30,19,23,1


问:
Calculate height of div based off width & maintain proportion
I am looking for a pure CSS solution to what I have here done using jQuery to help.

Basically I have 3 divs that spread evenly in width in a container. They maintain a 3/4 ration with the height being calculated off of the width. Furthermore, each div has a background image that stays proportional and some text that is centered horizontally and vertically.

$(document).ready(function() {
  function setw() {
    var footdivwidth = $('footer div').width();
    var footdivheight = footdivwidth * .75;
    $('footer div').css({
      'height': footdivheight + 'px'
    });
    $('footer div span').html('w: ' + footdivwidth + '
h: ' + footdivheight);
  }
  setw();
  $(window).resize(function() {
    setw();
  })
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>FOOTER {
  max-width: 1000px;
  margin: 0 auto;
  background-color: rgba(0, 0, 0, 0.171);
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

FOOTER DIV {
  background-image: url('https://learnwebdesign.online/img/bg.jpg');
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
  flex: 1;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
}

FOOTER DIV SPAN {
  display: inline-block;
  text-align: center;
  background-color: rgba(165, 165, 165, 0.282);
  padding: 7px 15px;
  border-radius: 3px;
  color: #FFFFFF;
  text-transform: uppercase;
  font-weight: bold;
  letter-spacing: 2px;
  font-size: 21px;
}</code>```

left photo

center photo

right photo and more text

```
</div>
</div>
</p>

<p>Here is a pen showing what I have.
https://codepen.io/nom3d/pen/arGpBV</p>

<p>Here is a gif showing the effect when resized. Note the background image staying proportional and text staying centered.
<img src="https://i.stack.imgur.com/OyB78.gif" alt="3 box resize with proportions kept"></p>

<p>Also wondering if it's not possible with just CSS, how to do this with <strong>plain javascript</strong>, would I need to add id's to my divs?</p>

<p>Update: here is a plain javaScript function to handle this task</p>

```function setHeight(el,val){
    var box = document.querySelectorAll(el);
    var i;
    for(i = 0;i < box.length;i++){
        var width = box[i].offsetWidth;
        var height = width * val;
        box[i].style.height = height + 'px';
    }
}
// set your element to target and the ratio value
setHeight('footer div',.75);
window.onresize = function(event) {
    setHeight('footer div',.75);
};
```

答:
Maintaining specific height:width ratios in CSS is usually done by exploiting the fact that padding percentage is always calculated based on the element's width.

For example, let's say you had an element with width: 500px, height: 300px and padding: 10%. Now you might expect the top and bottom paddings to be 10% of height, and the left and right paddings to be 10% of width. However this would give unequal vertical and horizontal paddings which is counter-intuitive to what is intended - equal paddings of 10%. To make sense of this we need to base the padding percentage on the save dimension, and that dimension has been chosen to be the width.

Thus to have an element with height:width ratio of 3:4 at all times we can set the height to 0 and the bottom (or top) padding to 3/4 of the width.

In your example each item is given a width of 33% by Flex. For a ratio of 3:4 the bottom padding should be 33% * 3 / 4, or 24.74%. Your CSS might look like:

```<code>width: 33%;
height: 0;
padding-bottom: 24.75%;
</code>```

Note that since the height is 0, the element will need to be relatively positioned with an absolutely positioned wrapper inside it. If you attempt to put content directly in the div, it will break the ratio. Your code above could be modified thus:

footer {
  max-width: 1000px;
  margin: 0 auto;
  background-color: rgba(0, 0, 0, 0.171);
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}
footer div {
  background-image: url('https://learnwebdesign.online/img/bg.jpg');
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
  position: relative;
  width: 33%;
  height: 0;
  padding-bottom: 24.75%;
}
footer div span {
  /* Used as content wrapper, with flex to centre content */
  position: absolute;
  top: 0; bottom: 0;
  left: 0; right: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
  background-color: rgba(165, 165, 165, 0.282);
  padding: 7px 15px;
  border-radius: 3px;
  color: #FFFFFF;
  text-transform: uppercase;
  font-weight: bold;
  letter-spacing: 2px;
  font-size: 21px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><footer>
  <div><span>left photo</span></div>
  <div><span>center photo</span></div>
  <div><span>right photo and more text</span></div>
</footer></code>```

Body:
I am looking for a pure CSS solution to what I have here done using jQuery to help.

Basically I have 3 divs that spread evenly in width in a container. They maintain a 3/4 ration with the height being calculated off of the width. Furthermore, each div has a background image that stays proportional and some text that is centered horizontally and vertically.

$(document).ready(function() {
  function setw() {
    var footdivwidth = $('footer div').width();
    var footdivheight = footdivwidth * .75;
    $('footer div').css({
      'height': footdivheight + 'px'
    });
    $('footer div span').html('w: ' + footdivwidth + '
h: ' + footdivheight);
  }
  setw();
  $(window).resize(function() {
    setw();
  })
});

FOOTER {
  max-width: 1000px;
  margin: 0 auto;
  background-color: rgba(0, 0, 0, 0.171);
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

FOOTER DIV {
  background-image: url('https://learnwebdesign.online/img/bg.jpg');
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
  flex: 1;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
}

FOOTER DIV SPAN {
  display: inline-block;
  text-align: center;
  background-color: rgba(165, 165, 165, 0.282);
  padding: 7px 15px;
  border-radius: 3px;
  color: #FFFFFF;
  text-transform: uppercase;
  font-weight: bold;
  letter-spacing: 2px;
  font-size: 21px;
}

left photo

center photo

right photo and more text

Here is a pen showing what I have.
https://codepen.io/nom3d/pen/arGpBV

Here is a gif showing the effect when resized. Note the background image staying proportional and text staying centered.

Also wondering if it's not possible with just CSS, how to do this with plain javascript, would I need to add id's to my divs?

Update: here is a plain javaScript function to handle this task

function setHeight(el,val){
    var box = document.querySelectorAll(el);
    var i;
    for(i = 0;i < box.length;i++){
        var width = box[i].offsetWidth;
        var height = width * val;
        box[i].style.height = height + 'px';
    }
}
// set your element to target and the ratio value
setHeight('footer div',.75);
window.onresize = function(event) {
    setHeight('footer div',.75);
};

Body:
Maintaining specific height:width ratios in CSS is usually done by exploiting the fact that padding percentage is always calculated based on the element's width.

For example, let's say you had an element with width: 500px, height: 300px and padding: 10%. Now you might expect the top and bottom paddings to be 10% of height, and the left and right paddings to be 10% of width. However this would give unequal vertical and horizontal paddings which is counter-intuitive to what is intended - equal paddings of 10%. To make sense of this we need to base the padding percentage on the save dimension, and that dimension has been chosen to be the width.

Thus to have an element with height:width ratio of 3:4 at all times we can set the height to 0 and the bottom (or top) padding to 3/4 of the width.

In your example each item is given a width of 33% by Flex. For a ratio of 3:4 the bottom padding should be 33% * 3 / 4, or 24.74%. Your CSS might look like:

width: 33%;
height: 0;
padding-bottom: 24.75%;

Note that since the height is 0, the element will need to be relatively positioned with an absolutely positioned wrapper inside it. If you attempt to put content directly in the div, it will break the ratio. Your code above could be modified thus:

footer {
  max-width: 1000px;
  margin: 0 auto;
  background-color: rgba(0, 0, 0, 0.171);
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}
footer div {
  background-image: url('https://learnwebdesign.online/img/bg.jpg');
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
  position: relative;
  width: 33%;
  height: 0;
  padding-bottom: 24.75%;
}
footer div span {
  /* Used as content wrapper, with flex to centre content */
  position: absolute;
  top: 0; bottom: 0;
  left: 0; right: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
  background-color: rgba(165, 165, 165, 0.282);
  padding: 7px 15px;
  border-radius: 3px;
  color: #FFFFFF;
  text-transform: uppercase;
  font-weight: bold;
  letter-spacing: 2px;
  font-size: 21px;
}

<footer>
  <div><span>left photo</span></div>
  <div><span>center photo</span></div>
  <div><span>right photo and more text</span></div>
</footer>


问:
Linq method syntax to flatten xml nodes
I've got the working code below to flatten xml nodes:

```<code>var xml = XDocument.Parse(input);

var headerSection = xml.Descendants("Header");
var subHeaderSection = xml.Descendants("SubHeader");

var body = xml.Descendants("Body");
var activity = body.Descendants("Activity");
var position = body.Descendants("Position");
var positionAmouts = position.Descendants("PositionAmounts").Elements("PositionAmount");

var results = from h in headerSection
              from sh in subHeaderSection
              from a in activity
              from po in position
              from pa in positionAmouts
              select new List<string>
              {
                  h.Element("Id").Value,
                  h.Element("OtherId").Value,
                  h.Element("SomeValue").Value,
                  sh.Element("SomeValue2").Value,
                  sh.Element("SomeValue3").Value,
                  a.Element("ActivityId").Value,
                  a.Element("ActivityValue").Value,
                  po.Element("PositionId").Value,
                  pa.Element("Amount1").Value,
                  pa.Element("Amount2").Value,
              }
</code>```

This code works fine. But the actual list of froms is longer than shown. And the List initiator becomes a big long list of values.

I believe if I can convert the many froms to linq method syntax, I should be able to produce the same List results in a method where I can do something better than listing all the desired values? (like a loop through some pre defined element names)

Edit: sample xml as requested:

```<code><Root>
  <Header>
    <Id>123</Id>
    <OtherId>456</OtherId>
    <SomeValue>abc</SomeValue>
  </Header>
  <SubHeader>
    <SomeValue2>dfg</SomeValue2>
    <SomeValue3>fghj</SomeValue3>
  </SubHeader>
  <Body>
    <Activity>
      <ActivityId>321</ActivityId>
      <ActivityValue>hjk</ActivityValue>
    </Activity>
    <Position>
      <PositionId>654</PositionId>
      <PositionAmounts>
        <PositionAmount>
          <Amount1>10.01</Amount1>
          <Amount2>12.63</Amount2>
        </PositionAmount>
        <PositionAmount>
          <Amount1>15.11</Amount1>
        </PositionAmount>
      </PositionAmounts>
    </Position>
  </Body>
</Root>
</code>```

答:
Try this way:

```<code>const string splitterElementName = "PositionAmount";

var doc = XDocument.Parse(input);

var result = doc.Descendants()
    // Take just the deepest descendants.
    .Where(v => !v.HasElements)
    .Select(v => v.AncestorsAndSelf())
    // Group by key, where key contains names of all ancestors exclude the deepest element.
    .GroupBy(k =>
        {
            var isSplitter = false;

            var key = string.Join("-", k
                .Skip(1)
                .Select(v =>
                {
                    if (v.Name.LocalName != splitterElementName)
                    {
                        return v.Name.LocalName;
                    }

                    isSplitter = true;

                    // Define the unique id for each splitting element.
                    return $"{v.Name.LocalName}:{string.Join(":", v.AncestorsAndSelf().Select(a => a.ElementsBeforeSelf().Count()))}";
                }));

            return (key, isSplitter);
        },
        e => e.First().Value)
    // Merge all groups to one list.
    .GroupBy(k => 0, e => e, (key, element) => element.ToArray())
    // Extract all splitters.
    .SelectMany(groups => groups
        .Where(group => group.Key.isSplitter)
        .Select(splittingGroup => (splittingKey: splittingGroup.Key, groups)))
    // Prepare result.
    .Select(v => v.groups
        .Where(group => !group.Key.isSplitter || group.Key == v.splittingKey)
        .SelectMany(a => a)
        .ToArray())
    .ToList();

    /* result:
    [0]: {string[10]}
    [1]: {string[9]}
result[0]
{string[10]}
    [0]: "123"
    [1]: "456"
    [2]: "abc"
    [3]: "dfg"
    [4]: "fghj"
    [5]: "321"
    [6]: "hjk"
    [7]: "654"
    [8]: "10.01"
    [9]: "12.63"
result[1]
{string[9]}
    [0]: "123"
    [1]: "456"
    [2]: "abc"
    [3]: "dfg"
    [4]: "fghj"
    [5]: "321"
    [6]: "hjk"
    [7]: "654"
    [8]: "15.11"
     */
</code>```

The test xml:

```<code>var input = @"<Root>
  <Header>
    <Id>123</Id>
    <OtherId>456</OtherId>
    <SomeValue>abc</SomeValue>
  </Header>
  <SubHeader>
    <SomeValue2>dfg</SomeValue2>
    <SomeValue3>fghj</SomeValue3>
  </SubHeader>
  <Body>
    <Activity>
      <ActivityId>321</ActivityId>
      <ActivityValue>hjk</ActivityValue>
    </Activity>
    <Position>
      <PositionId>654</PositionId>
      <PositionAmounts>
        <PositionAmount>
          <Amount1>10.01</Amount1>
          <Amount2>12.63</Amount2>
        </PositionAmount>
        <PositionAmount>
          <Amount1>15.11</Amount1>
        </PositionAmount>
      </PositionAmounts>
    </Position>
  </Body>
</Root>";
</code>```

Title: Linq method syntax to flatten xml nodes

Body:
I've got the working code below to flatten xml nodes:

var xml = XDocument.Parse(input);

var headerSection = xml.Descendants("Header");
var subHeaderSection = xml.Descendants("SubHeader");

var body = xml.Descendants("Body");
var activity = body.Descendants("Activity");
var position = body.Descendants("Position");
var positionAmouts = position.Descendants("PositionAmounts").Elements("PositionAmount");

var results = from h in headerSection
              from sh in subHeaderSection
              from a in activity
              from po in position
              from pa in positionAmouts
              select new List<string>
              {
                  h.Element("Id").Value,
                  h.Element("OtherId").Value,
                  h.Element("SomeValue").Value,
                  sh.Element("SomeValue2").Value,
                  sh.Element("SomeValue3").Value,
                  a.Element("ActivityId").Value,
                  a.Element("ActivityValue").Value,
                  po.Element("PositionId").Value,
                  pa.Element("Amount1").Value,
                  pa.Element("Amount2").Value,
              }

This code works fine. But the actual list of froms is longer than shown. And the List initiator becomes a big long list of values.

I believe if I can convert the many froms to linq method syntax, I should be able to produce the same List results in a method where I can do something better than listing all the desired values? (like a loop through some pre defined element names)

Edit: sample xml as requested:

<Root>

    <Id>123</Id>
    <OtherId>456</OtherId>
    <SomeValue>abc</SomeValue>

  <SubHeader>
    <SomeValue2>dfg</SomeValue2>
    <SomeValue3>fghj</SomeValue3>
  </SubHeader>

    <Activity>
      <ActivityId>321</ActivityId>
      <ActivityValue>hjk</ActivityValue>
    </Activity>
    <Position>
      <PositionId>654</PositionId>
      <PositionAmounts>
        <PositionAmount>
          <Amount1>10.01</Amount1>
          <Amount2>12.63</Amount2>
        </PositionAmount>
        <PositionAmount>
          <Amount1>15.11</Amount1>
        </PositionAmount>
      </PositionAmounts>
    </Position>

</Root>

Body:
Try this way:

const string splitterElementName = "PositionAmount";

var doc = XDocument.Parse(input);

var result = doc.Descendants()
    // Take just the deepest descendants.
    .Where(v => !v.HasElements)
    .Select(v => v.AncestorsAndSelf())
    // Group by key, where key contains names of all ancestors exclude the deepest element.
    .GroupBy(k =>
        {
            var isSplitter = false;

            var key = string.Join("-", k
                .Skip(1)
                .Select(v =>
                {
                    if (v.Name.LocalName != splitterElementName)
                    {
                        return v.Name.LocalName;
                    }

                    isSplitter = true;

                    // Define the unique id for each splitting element.
                    return $"{v.Name.LocalName}:{string.Join(":", v.AncestorsAndSelf().Select(a => a.ElementsBeforeSelf().Count()))}";
                }));

            return (key, isSplitter);
        },
        e => e.First().Value)
    // Merge all groups to one list.
    .GroupBy(k => 0, e => e, (key, element) => element.ToArray())
    // Extract all splitters.
    .SelectMany(groups => groups
        .Where(group => group.Key.isSplitter)
        .Select(splittingGroup => (splittingKey: splittingGroup.Key, groups)))
    // Prepare result.
    .Select(v => v.groups
        .Where(group => !group.Key.isSplitter || group.Key == v.splittingKey)
        .SelectMany(a => a)
        .ToArray())
    .ToList();

    /* result:
    [0]: {string[10]}
    [1]: {string[9]}
result[0]
{string[10]}
    [0]: "123"
    [1]: "456"
    [2]: "abc"
    [3]: "dfg"
    [4]: "fghj"
    [5]: "321"
    [6]: "hjk"
    [7]: "654"
    [8]: "10.01"
    [9]: "12.63"
result[1]
{string[9]}
    [0]: "123"
    [1]: "456"
    [2]: "abc"
    [3]: "dfg"
    [4]: "fghj"
    [5]: "321"
    [6]: "hjk"
    [7]: "654"
    [8]: "15.11"
     */

The test xml:

var input = @"<Root>
  <Header>
    <Id>123</Id>
    <OtherId>456</OtherId>
    <SomeValue>abc</SomeValue>
  </Header>
  <SubHeader>
    <SomeValue2>dfg</SomeValue2>
    <SomeValue3>fghj</SomeValue3>
  </SubHeader>
  <Body>
    <Activity>
      <ActivityId>321</ActivityId>
      <ActivityValue>hjk</ActivityValue>
    </Activity>
    <Position>
      <PositionId>654</PositionId>
      <PositionAmounts>
        <PositionAmount>
          <Amount1>10.01</Amount1>
          <Amount2>12.63</Amount2>
        </PositionAmount>
        <PositionAmount>
          <Amount1>15.11</Amount1>
        </PositionAmount>
      </PositionAmounts>
    </Position>
  </Body>
</Root>";


问:
How do I use Multipart::from_request with a tiny_http::Request?
I'm trying to use the tiny_http integration in the multipart crate:

```<code>extern crate multipart;
extern crate tiny_http;

use multipart::server::tiny_http as tiny_http_trait;
use multipart::server::Multipart;
use tiny_http::*;

fn main() {
    let server = Server::http("0.0.0.0:8080").unwrap();
    loop {
        match server.recv() {
            Ok(request) => {
                let mult = Multipart::from_request(request).unwrap();
            }
            Err(s) => eprintln!("{:#?}", s),
        };
    }
}
</code>```

I'm getting the following error when trying to extract multipart form data from the request:

error[E0277]: the trait bound `tiny_http::Request: multipart::server::HttpRequest` is not satisfied
  --> src/main.rs:13:28
   |
13 |                 let mult = Multipart::from_request(request).unwrap();
   |                            ^^^^^^^^^^^^^^^^^^^^^^^ the trait `multipart::server::HttpRequest` is not implemented for `tiny_http::Request`
   |
   = help: the following implementations were found:
             <&'r mut tiny_http::Request as multipart::server::HttpRequest>
   = note: required by `multipart::server::Multipart::<()>::from_request`
```

<p>That trait implementation does exist, and I'm able to use it directly with <code>HttpRequest</code> functions:</p>

```let boundary = <&mut Request as HttpRequest>::multipart_boundary(&&mut request);
```

<p>I cannot seem to use that same syntax to use <code>tiny_http::Request</code> as a <code>multipart::server::HttpRequest</code> in <code>multipart::server::Multipart::from_request(...)</code></p>

<p>Here is my <code>Cargo.toml</code>:</p>

```[package]
name = "db_interface"
version = "0.1.0"
authors = [""]
edition = "2018"

[dependencies]
tiny_http = "0.6.2"

[dependencies.multipart]
version = "0.16.1"
features = ["tiny_http"]
```

答:
As the compiler tells you, you need a mutable reference:

<&'r mut tiny_http::Request as multipart::server::HttpRequest>
```

<p>Declare the request as mutable and then take a reference to it:</p>

```match server.recv() {
    Ok(mut request) => {
        let mult = Multipart::from_request(&mut request).unwrap();
    }
    Err(s) => eprintln!("{:#?}", s),
};
```

Body:
I'm trying to use the tiny_http integration in the multipart crate:

extern crate multipart;
extern crate tiny_http;

use multipart::server::tiny_http as tiny_http_trait;
use multipart::server::Multipart;
use tiny_http::*;

fn main() {
    let server = Server::http("0.0.0.0:8080").unwrap();
    loop {
        match server.recv() {
            Ok(request) => {
                let mult = Multipart::from_request(request).unwrap();
            }
            Err(s) => eprintln!("{:#?}", s),
        };
    }
}

I'm getting the following error when trying to extract multipart form data from the request:

error[E0277]: the trait bound `tiny_http::Request: multipart::server::HttpRequest` is not satisfied
  --> src/main.rs:13:28
   |
13 |                 let mult = Multipart::from_request(request).unwrap();
   |                            ^^^^^^^^^^^^^^^^^^^^^^^ the trait `multipart::server::HttpRequest` is not implemented for `tiny_http::Request`
   |
   = help: the following implementations were found:
             <&'r mut tiny_http::Request as multipart::server::HttpRequest>
   = note: required by `multipart::server::Multipart::<()>::from_request`

That trait implementation does exist, and I'm able to use it directly with HttpRequest functions:

let boundary = <&mut Request as HttpRequest>::multipart_boundary(&&mut request);

I cannot seem to use that same syntax to use tiny_http::Request as a multipart::server::HttpRequest in multipart::server::Multipart::from_request(...)

Here is my Cargo.toml:

[package]
name = "db_interface"
version = "0.1.0"
authors = [""]
edition = "2018"

[dependencies]
tiny_http = "0.6.2"

[dependencies.multipart]
version = "0.16.1"
features = ["tiny_http"]

Body:
As the compiler tells you, you need a mutable reference:

<&'r mut tiny_http::Request as multipart::server::HttpRequest>

Declare the request as mutable and then take a reference to it:

match server.recv() {
    Ok(mut request) => {
        let mult = Multipart::from_request(&mut request).unwrap();
    }
    Err(s) => eprintln!("{:#?}", s),
};


问:
Using dynamic data with tabs
this sounds so easy - but I just can't figure out the syntax.

I have a tab with multiple sortable lists.

But focusing on the tabs. When a tab is clicked I would like to perform various actions. This can be achieved as below.

```<code>$( '#tabs' ).tabs({
   selected: '<?php echo 'tabs-'.$iTabSelected ?>',
   select: function( event, ui ) {
    // actions performed
   }
});
</code>```

What's holding me back is, how do I get the id of the li element which makes up my tab:

```<code><div id="tabs">
    <div>
        <div class="tabs">
        <ul id="pui-tabs">

        <?php foreach( $aTabListData as $iKey => $aTabList ) { ?>

            <li id="tab-<?php echo $aTabList['tab'] ?>">

                    <a href="#tabs-<?php echo $aTabList['tab'] ?>"><?php echo $aTabList['name'] ?></a>
            </li>
</code>```

I'm trying to get the following id when a tab is selected.

```<code><li id="tab-<?php echo $aTabList['tab'] ?>">
</code>```

Can I use ui.tab to get the li id?

Thanks in advance.

答:
The select method actually takes two arguments:</p>

```<code>$( '#tabs' ).tabs({
   selected: '<?php echo 'tabs-'.$iTabSelected ?>',
   select: function(event, ui) {
      // Objects available in the function context:
      ui.tab     // anchor element of the selected (clicked) tab
      ui.panel   // element, that contains the selected/clicked tab contents
      ui.index   // zero-based index of the selected (clicked) tab
   }
});
</code>```

Title: Using dynamic data with tabs

Body:
this sounds so easy - but I just can't figure out the syntax.

I have a tab with multiple sortable lists.

But focusing on the tabs. When a tab is clicked I would like to perform various actions. This can be achieved as below.

$( '#tabs' ).tabs({
   selected: '<?php echo 'tabs-'.$iTabSelected ?>',
   select: function( event, ui ) {
    // actions performed
   }
});

What's holding me back is, how do I get the id of the li element which makes up my tab:

        <?php foreach( $aTabListData as $iKey => $aTabList ) { ?>

            <li id="tab-<?php echo $aTabList['tab'] ?>">

                    <a href="#tabs-<?php echo $aTabList['tab'] ?>"><?php echo $aTabList['name'] ?>

I'm trying to get the following id when a tab is selected.

<li id="tab-<?php echo $aTabList['tab'] ?>">

Can I use ui.tab to get the li id?

Thanks in advance.

Body:
The select method actually takes two arguments:

$( '#tabs' ).tabs({
   selected: '<?php echo 'tabs-'.$iTabSelected ?>',
   select: function(event, ui) {
      // Objects available in the function context:
      ui.tab     // anchor element of the selected (clicked) tab
      ui.panel   // element, that contains the selected/clicked tab contents
      ui.index   // zero-based index of the selected (clicked) tab
   }
});


问:
How to stop all time labels showing in ggplot2?
I'm having problems trying to get the x-axis on my ggplot to only show specific values. The X axis is a range of times, however there are so many at the moment it is currently unreadable (see image), ideally I'd like one tick every hour or so but I just cant work out how to.

Any suggestions would be incredibly appreciated.

I've tried suggestions for similar problems and haven't had any luck (please see below for most of the codes I have tried and the errors)

This is my graph code;

```<code>ggplot(data, aes(x=time, y=binary)) +
geom_bar(stat='identity') +
facet_wrap(~id,scales="free_x",  ncol=1,strip.position = "right")
</code>```

and here are most of the things I have tried to fix the problem;

```<code>scale_x_continuous(breaks=c(seq(16:00,17:00,18:00)))
</code>```

```<code>>Error in seq.default(16:0, 17:0, 18:0,  :
      'from' must be of length 1
In addition: Warning message:
In seq.default(16:0, 17:0, 18:0,) :
extra arguments  will be disregarded
</code>```

```<code>scale_x_continuous(breaks=c(seq("16:00","17:00","18:00")))
</code>```

```<code>> Error in seq.default("16:00", "17:00", "18:00") :
      'from' must be a finite number
    In addition: Warning message:
    In seq.default("16:00", "17:00", "18:00") : NAs
</code>```

introduced by coercion

```<code>data$time <- gsub('\"', "", as.character(data$time), fixed=TRUE)
data$time <- as.Date(data$time, "%H-%M-%S")
</code>```

```<code>>    Warning messages:
    1: In min(x) : no non-missing arguments to min; returning Inf
    2: In max(x) : no non-missing arguments to max; returning -Inf
    3: In min(diff(sort(x))) : no non-missing arguments to min; returning Inf
    4: Removed 7290 rows containing missing values (position_stack).
</code>```

```<code>x=data$time
as.numeric(gsub(",","",x,fixed=TRUE))
</code>```

```<code>>    Warning message:
    NAs introduced by coercion
</code>```

```<code>scale_x_datetime(breaks = date_breaks("1 hour"), labels = date_format("%H:%M:%S"))

<ScaleContinuousDatetime>
 Range:
 Limits:    0 --    1
</code>```

Here is a sample of the original data set (as it's huge), apologies for not posting this originally.
Thanks so much for the help!

```<code>> data
   time  id binary
1 15:49 267      2
2 13:58 269      0
3 15:51 231      0
4 16:00 263      1
5 15:51 237      2
6 15:53 236      2
7 16:00 235      2

> dput(data)

structure(list(time = structure(c(2L, 1L, 3L, 5L, 3L, 4L, 5L), .Label = c("13:58",
"15:49", "15:51", "15:53", "16:00"), class = "factor"), id = c(267L,
269L, 231L, 263L, 237L, 236L, 235L), binary = c(2L, 0L, 0L, 1L,
2L, 2L, 2L)), .Names = c("time", "id", "binary"), class = "data.frame", row.names = c(NA,
-7L))

> str(data)

'data.frame':   7 obs. of  3 variables:
 $ time  : Factor w/ 5 levels "13:58","15:49",..: 2 1 3 5 3 4 5
 $ id    : int  267 269 231 263 237 236 235
 $ binary: int  2 0 0 1 2 2 2
</code>```

答:
Ok so without having the data to run, I can see a few problems which will hopefully help:

```<code>scale_x_continuous(breaks=c(seq(16:00,17:00,18:00)))
</code>```

is throwing the same error both times as seq needs three parameters seq(initial value, final value, step), whereas you currently have it as seq(time 1, time 2, time 3).

Looking at the other ggplot call:

```<code>scale_x_datetime(breaks = date_breaks("1 hour"), labels = date_format("%H:%M:%S"))
</code>```

Should read

```<code>scale_x_datetime(date_breaks="1 hour", date_labels("%H:%M:%S"))
</code>```

The latter option is preferable given that you are dealing with a time/date variable.

The key then, is to make sure the variable is in the correct format. This is where we would need to see an example of that column to advise on that! It may be okay already - ggplot does that with date formats I have found, so that may be an indicator it is in the right format already.

If you add an example of the data in the column (following @joran 's comment) then we could progress.

Body:
I'm having problems trying to get the x-axis on my ggplot to only show specific values. The X axis is a range of times, however there are so many at the moment it is currently unreadable (see image), ideally I'd like one tick every hour or so but I just cant work out how to.

Any suggestions would be incredibly appreciated.

I've tried suggestions for similar problems and haven't had any luck (please see below for most of the codes I have tried and the errors)

This is my graph code;

ggplot(data, aes(x=time, y=binary)) +
geom_bar(stat='identity') +
facet_wrap(~id,scales="free_x",  ncol=1,strip.position = "right")

and here are most of the things I have tried to fix the problem;

scale_x_continuous(breaks=c(seq(16:00,17:00,18:00)))

>Error in seq.default(16:0, 17:0, 18:0,  :
      'from' must be of length 1
In addition: Warning message:
In seq.default(16:0, 17:0, 18:0,) :
extra arguments  will be disregarded

scale_x_continuous(breaks=c(seq("16:00","17:00","18:00")))

> Error in seq.default("16:00", "17:00", "18:00") :
      'from' must be a finite number
    In addition: Warning message:
    In seq.default("16:00", "17:00", "18:00") : NAs

introduced by coercion

data$time <- gsub('\"', "", as.character(data$time), fixed=TRUE)
data$time <- as.Date(data$time, "%H-%M-%S")

>    Warning messages:
    1: In min(x) : no non-missing arguments to min; returning Inf
    2: In max(x) : no non-missing arguments to max; returning -Inf
    3: In min(diff(sort(x))) : no non-missing arguments to min; returning Inf
    4: Removed 7290 rows containing missing values (position_stack).

x=data$time
as.numeric(gsub(",","",x,fixed=TRUE))

>    Warning message:
    NAs introduced by coercion

scale_x_datetime(breaks = date_breaks("1 hour"), labels = date_format("%H:%M:%S"))

<ScaleContinuousDatetime>
 Range:
 Limits:    0 --    1

Here is a sample of the original data set (as it's huge), apologies for not posting this originally.
Thanks so much for the help!

> data
   time  id binary
1 15:49 267      2
2 13:58 269      0
3 15:51 231      0
4 16:00 263      1
5 15:51 237      2
6 15:53 236      2
7 16:00 235      2

> dput(data)

structure(list(time = structure(c(2L, 1L, 3L, 5L, 3L, 4L, 5L), .Label = c("13:58",
"15:49", "15:51", "15:53", "16:00"), class = "factor"), id = c(267L,
269L, 231L, 263L, 237L, 236L, 235L), binary = c(2L, 0L, 0L, 1L,
2L, 2L, 2L)), .Names = c("time", "id", "binary"), class = "data.frame", row.names = c(NA,
-7L))

> str(data)

'data.frame':   7 obs. of  3 variables:
 $ time  : Factor w/ 5 levels "13:58","15:49",..: 2 1 3 5 3 4 5
 $ id    : int  267 269 231 263 237 236 235
 $ binary: int  2 0 0 1 2 2 2

Body:
Ok so without having the data to run, I can see a few problems which will hopefully help:

scale_x_continuous(breaks=c(seq(16:00,17:00,18:00)))

is throwing the same error both times as seq needs three parameters seq(initial value, final value, step), whereas you currently have it as seq(time 1, time 2, time 3).

Looking at the other ggplot call:

scale_x_datetime(breaks = date_breaks("1 hour"), labels = date_format("%H:%M:%S"))

Should read

scale_x_datetime(date_breaks="1 hour", date_labels("%H:%M:%S"))

The latter option is preferable given that you are dealing with a time/date variable.

The key then, is to make sure the variable is in the correct format. This is where we would need to see an example of that column to advise on that! It may be okay already - ggplot does that with date formats I have found, so that may be an indicator it is in the right format already.

If you add an example of the data in the column (following @joran 's comment) then we could progress.


问:
Why is Python reference equality not working?
I have a class with an array called self.sheets. I have a function, find_sheet which will do a comparison on the titles if a string is passed, or do a reference comparison if a Worksheet is passed. Here's a minimal reproducible example:

```<code>class Worksheet:
    pass

class Spread:
    @property
    def sheets(self):
        return [Worksheet() for i in range(5)]

    def find_sheet(self, sheet):
        for ix, obj in enumerate(self.sheets):
            print("comparing {} is {}".format(id(obj), id(sheet)))
            if obj is sheet:
                print("found you")

s = Spread()
s.find_sheet(s.sheets[0])
</code>```

This outputs comparing 140134415396760 is 140134393512344

答:
I figured out my problem. When I refer to s.sheets, it's calling the property function and generating a new list each time. So when I pass s.sheets[0], it's actually a different object than the first object when iterating through self.sheets.

Lesson here is... be careful when using properties, they behave differently than variables.

Body:
I have a class with an array called self.sheets. I have a function, find_sheet which will do a comparison on the titles if a string is passed, or do a reference comparison if a Worksheet is passed. Here's a minimal reproducible example:

class Worksheet:
    pass

class Spread:
    @property
    def sheets(self):
        return [Worksheet() for i in range(5)]

    def find_sheet(self, sheet):
        for ix, obj in enumerate(self.sheets):
            print("comparing {} is {}".format(id(obj), id(sheet)))
            if obj is sheet:
                print("found you")

s = Spread()
s.find_sheet(s.sheets[0])

This outputs comparing 140134415396760 is 140134393512344


问:
iTunes Lookup API response is different for different clients
Right now it looks like a mystery. Please help me in solving it.

I use iTunes public API to fetch an album: "Metallica" by Metallica (see it in browser: US region, MV region). I construct the following URLs to fetch it via API:

US region https://itunes.apple.com/lookup?id=579372950&country=US&entity=album - works

MV region https://itunes.apple.com/lookup?id=579372950&country=MV&entity=album - doesn't work

Here's the actual behaviour I observe:

If I query GET https://itunes.apple.com/lookup?id=579372950&country=MV&entity=album in a Spring app (using RestTemplate + Jackson HttpMessageConverter) I get an empty response:

```<code>{
 "resultCount":0,
 "results": []
}
</code>```

If I navigate to https://itunes.apple.com/lookup?id=579372950&country=MV&entity=album in a browser I get a file download prompt. The file contains an empty response:

```<code>{
 "resultCount":0,
 "results": []
}
</code>```

If I query API using HttpPie http get https://itunes.apple.com/lookup?id=579372950&country=MV&entity=album I get a non-empty response !!!

```<code>{
    "resultCount": 1,
    "results": [
        {
            "amgArtistId": 4906,
            "artistId": 3996865,
            "artistName": "Metallica",
            "artistViewUrl": "https://music.apple.com/us/artist/metallica/3996865?uo=4",
            "artworkUrl100": "https://is1-ssl.mzstatic.com/image/thumb/Music/v4/0b/9c/d2/0b9cd2e7-6e76-8912-0357-14780cc2616a/source/100x100bb.jpg",
            "artworkUrl60": "https://is1-ssl.mzstatic.com/image/thumb/Music/v4/0b/9c/d2/0b9cd2e7-6e76-8912-0357-14780cc2616a/source/60x60bb.jpg",
            "collectionCensoredName": "Metallica",
            "collectionExplicitness": "notExplicit",
            "collectionId": 579372950,
            "collectionName": "Metallica",
            "collectionPrice": 9.99,
            "collectionType": "Album",
            "collectionViewUrl": "https://music.apple.com/us/album/metallica/579372950?uo=4",
            "copyright": "℗ 1991 Blackened Recordings",
            "country": "USA",
            "currency": "USD",
            "primaryGenreName": "Metal",
            "releaseDate": "1991-08-12T07:00:00Z",
            "trackCount": 13,
            "wrapperType": "collection"
        }
    ]
}
</code>```

I tried it multiple times and the results seem to be consistent. I compared the requests and they seem to be identical.

Why does iTunes respond differently to different clients? I can't understand. What important detail am I missing?

Similar questions:

Spring RestTemplate getForObject URL not working for Apple iTunes - there's another problem (double encoding of the whitespace character).

This problem happens to the following regions (it's a complete list):

LI https://itunes.apple.com/lookup?id=579372950&country=LI&entity=album

MV https://itunes.apple.com/lookup?id=579372950&country=MV&entity=album

MM https://itunes.apple.com/lookup?id=579372950&country=MM&entity=album

ET https://itunes.apple.com/lookup?id=579372950&country=ET&entity=album

RS https://itunes.apple.com/lookup?id=579372950&country=RS&entity=album

答:
I spotted a difference:

http get 'https://itunes.apple.com/lookup?id=579372950&country=MV&entity=album' -> empty response

curl 'https://itunes.apple.com/lookup?id=579372950&country=MV&entity=album' -> empty response

http get https://itunes.apple.com/lookup?id=579372950&country=MV&entity=album -> 1 album in response

curl https://itunes.apple.com/lookup?id=579372950&country=MV&entity=album -> 1 album in response

if I don't use quotes around URL, the request is interpreted as GET https://itunes.apple.com/lookup?id=579372950. the default country is US and therefore I see 1 US album in response.

Body:
Right now it looks like a mystery. Please help me in solving it.

I use iTunes public API to fetch an album: "Metallica" by Metallica (see it in browser: US region, MV region). I construct the following URLs to fetch it via API:

US region https://itunes.apple.com/lookup?id=579372950&country=US&entity=album - works

MV region https://itunes.apple.com/lookup?id=579372950&country=MV&entity=album - doesn't work

Here's the actual behaviour I observe:

If I query GET https://itunes.apple.com/lookup?id=579372950&country=MV&entity=album in a Spring app (using RestTemplate + Jackson HttpMessageConverter) I get an empty response:

{
 "resultCount":0,
 "results": []
}

If I navigate to https://itunes.apple.com/lookup?id=579372950&country=MV&entity=album in a browser I get a file download prompt. The file contains an empty response:

{
 "resultCount":0,
 "results": []
}

If I query API using HttpPie http get https://itunes.apple.com/lookup?id=579372950&country=MV&entity=album I get a non-empty response !!!

{
    "resultCount": 1,
    "results": [
        {
            "amgArtistId": 4906,
            "artistId": 3996865,
            "artistName": "Metallica",
            "artistViewUrl": "https://music.apple.com/us/artist/metallica/3996865?uo=4",
            "artworkUrl100": "https://is1-ssl.mzstatic.com/image/thumb/Music/v4/0b/9c/d2/0b9cd2e7-6e76-8912-0357-14780cc2616a/source/100x100bb.jpg",
            "artworkUrl60": "https://is1-ssl.mzstatic.com/image/thumb/Music/v4/0b/9c/d2/0b9cd2e7-6e76-8912-0357-14780cc2616a/source/60x60bb.jpg",
            "collectionCensoredName": "Metallica",
            "collectionExplicitness": "notExplicit",
            "collectionId": 579372950,
            "collectionName": "Metallica",
            "collectionPrice": 9.99,
            "collectionType": "Album",
            "collectionViewUrl": "https://music.apple.com/us/album/metallica/579372950?uo=4",
            "copyright": "℗ 1991 Blackened Recordings",
            "country": "USA",
            "currency": "USD",
            "primaryGenreName": "Metal",
            "releaseDate": "1991-08-12T07:00:00Z",
            "trackCount": 13,
            "wrapperType": "collection"
        }
    ]
}

I tried it multiple times and the results seem to be consistent. I compared the requests and they seem to be identical.

Why does iTunes respond differently to different clients? I can't understand. What important detail am I missing?

Similar questions:

Spring RestTemplate getForObject URL not working for Apple iTunes - there's another problem (double encoding of the whitespace character).

This problem happens to the following regions (it's a complete list):

LI https://itunes.apple.com/lookup?id=579372950&country=LI&entity=album

MV https://itunes.apple.com/lookup?id=579372950&country=MV&entity=album

MM https://itunes.apple.com/lookup?id=579372950&country=MM&entity=album

ET https://itunes.apple.com/lookup?id=579372950&country=ET&entity=album

RS https://itunes.apple.com/lookup?id=579372950&country=RS&entity=album


问:
Tab completion in Python's raw_input()
i know i can do this to get the effect of tab completion in python sure.

```<code>import readline
COMMANDS = ['extra', 'extension', 'stuff', 'errors',
            'email', 'foobar', 'foo']

def complete(text, state):
    for cmd in COMMANDS:
        if cmd.startswith(text):
            if not state:
                return cmd
            else:
                state -= 1

readline.parse_and_bind("tab: complete")
readline.set_completer(complete)
raw_input('Enter section name: ')
</code>```

I am now interested in doing tab completion with directories. (/home/user/doc >tab)

How would i go about doing such a task?

答:
Here is a quick example of how to perform incremental completion of file system paths. I've modified your example, organizing it into a class where methods named complete_[name] indicate top-level commands.

I've switched the completion function to use the internal readline buffer to determine the state of the overall completion, which makes the state logic a bit simpler.  The path completion is in the _complete_path(path) method, and I've hooked up the extra command to perform path completions on its arguments.

I'm sure the code could be further simplified but it should provide you a decent starting point:

```<code>import os
import re
import readline

COMMANDS = ['extra', 'extension', 'stuff', 'errors',
            'email', 'foobar', 'foo']
RE_SPACE = re.compile('.*\s+$', re.M)

class Completer(object):

    def _listdir(self, root):
        "List directory 'root' appending the path separator to subdirs."
        res = []
        for name in os.listdir(root):
            path = os.path.join(root, name)
            if os.path.isdir(path):
                name += os.sep
            res.append(name)
        return res

    def _complete_path(self, path=None):
        "Perform completion of filesystem path."
        if not path:
            return self._listdir('.')
        dirname, rest = os.path.split(path)
        tmp = dirname if dirname else '.'
        res = [os.path.join(dirname, p)
                for p in self._listdir(tmp) if p.startswith(rest)]
        # more than one match, or single match which does not exist (typo)
        if len(res) > 1 or not os.path.exists(path):
            return res
        # resolved to a single directory, so return list of files below it
        if os.path.isdir(path):
            return [os.path.join(path, p) for p in self._listdir(path)]
        # exact file match terminates this completion
        return [path + ' ']

    def complete_extra(self, args):
        "Completions for the 'extra' command."
        if not args:
            return self._complete_path('.')
        # treat the last arg as a path and complete it
        return self._complete_path(args[-1])

    def complete(self, text, state):
        "Generic readline completion entry point."
        buffer = readline.get_line_buffer()
        line = readline.get_line_buffer().split()
        # show all commands
        if not line:
            return [c + ' ' for c in COMMANDS][state]
        # account for last argument ending in a space
        if RE_SPACE.match(buffer):
            line.append('')
        # resolve command to the implementation function
        cmd = line[0].strip()
        if cmd in COMMANDS:
            impl = getattr(self, 'complete_%s' % cmd)
            args = line[1:]
            if args:
                return (impl(args) + [None])[state]
            return [cmd + ' '][state]
        results = [c + ' ' for c in COMMANDS if c.startswith(cmd)] + [None]
        return results[state]

comp = Completer()
# we want to treat '/' as part of a word, so override the delimiters
readline.set_completer_delims(' \t\n;')
readline.parse_and_bind("tab: complete")
readline.set_completer(comp.complete)
raw_input('Enter section name: ')
</code>```

Usage:

```<code>% python complete.py
Enter section name: ext<tab>
extension extra
Enter section name: extra foo<tab>
foo.py foo.txt foo/
Enter section name: extra foo/<tab>
foo/bar.txt foo/baz.txt
Enter section name: extra foo/bar.txt
</code>```

Update It will complete paths from the root if the user types /:

```<code>% python complete.py
Enter section name: extra /Use<tab>
/Users/.localized  /Users/Shared/  /Users/user1 /Users/user2
Enter section name: extra /Users/use<tab>
/Users/user1  /Users/user2
</code>```

Title: Tab completion in Python's raw_input()

Body:
i know i can do this to get the effect of tab completion in python sure.

import readline
COMMANDS = ['extra', 'extension', 'stuff', 'errors',
            'email', 'foobar', 'foo']

def complete(text, state):
    for cmd in COMMANDS:
        if cmd.startswith(text):
            if not state:
                return cmd
            else:
                state -= 1

readline.parse_and_bind("tab: complete")
readline.set_completer(complete)
raw_input('Enter section name: ')

I am now interested in doing tab completion with directories. (/home/user/doc >tab)

How would i go about doing such a task?

Body:
Here is a quick example of how to perform incremental completion of file system paths. I've modified your example, organizing it into a class where methods named complete_[name] indicate top-level commands.

I've switched the completion function to use the internal readline buffer to determine the state of the overall completion, which makes the state logic a bit simpler.  The path completion is in the _complete_path(path) method, and I've hooked up the extra command to perform path completions on its arguments.

I'm sure the code could be further simplified but it should provide you a decent starting point:

import os
import re
import readline

COMMANDS = ['extra', 'extension', 'stuff', 'errors',
            'email', 'foobar', 'foo']
RE_SPACE = re.compile('.*\s+$', re.M)

class Completer(object):

    def _listdir(self, root):
        "List directory 'root' appending the path separator to subdirs."
        res = []
        for name in os.listdir(root):
            path = os.path.join(root, name)
            if os.path.isdir(path):
                name += os.sep
            res.append(name)
        return res

    def _complete_path(self, path=None):
        "Perform completion of filesystem path."
        if not path:
            return self._listdir('.')
        dirname, rest = os.path.split(path)
        tmp = dirname if dirname else '.'
        res = [os.path.join(dirname, p)
                for p in self._listdir(tmp) if p.startswith(rest)]
        # more than one match, or single match which does not exist (typo)
        if len(res) > 1 or not os.path.exists(path):
            return res
        # resolved to a single directory, so return list of files below it
        if os.path.isdir(path):
            return [os.path.join(path, p) for p in self._listdir(path)]
        # exact file match terminates this completion
        return [path + ' ']

    def complete_extra(self, args):
        "Completions for the 'extra' command."
        if not args:
            return self._complete_path('.')
        # treat the last arg as a path and complete it
        return self._complete_path(args[-1])

    def complete(self, text, state):
        "Generic readline completion entry point."
        buffer = readline.get_line_buffer()
        line = readline.get_line_buffer().split()
        # show all commands
        if not line:
            return [c + ' ' for c in COMMANDS][state]
        # account for last argument ending in a space
        if RE_SPACE.match(buffer):
            line.append('')
        # resolve command to the implementation function
        cmd = line[0].strip()
        if cmd in COMMANDS:
            impl = getattr(self, 'complete_%s' % cmd)
            args = line[1:]
            if args:
                return (impl(args) + [None])[state]
            return [cmd + ' '][state]
        results = [c + ' ' for c in COMMANDS if c.startswith(cmd)] + [None]
        return results[state]

comp = Completer()
# we want to treat '/' as part of a word, so override the delimiters
readline.set_completer_delims(' \t\n;')
readline.parse_and_bind("tab: complete")
readline.set_completer(comp.complete)
raw_input('Enter section name: ')

Usage:

% python complete.py
Enter section name: ext<tab>
extension extra
Enter section name: extra foo<tab>
foo.py foo.txt foo/
Enter section name: extra foo/<tab>
foo/bar.txt foo/baz.txt
Enter section name: extra foo/bar.txt

Update It will complete paths from the root if the user types /:

% python complete.py
Enter section name: extra /Use<tab>
/Users/.localized  /Users/Shared/  /Users/user1 /Users/user2
Enter section name: extra /Users/use<tab>
/Users/user1  /Users/user2