text:
using System;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Threading;
using ControlzEx.Native;
using MahApps.Metro.Controls;

namespace MahApps.Metro.SimpleChildWindow
{
    ///
    /// A simple child window for MahApps.Metro.
    ///
    [TemplatePart(Name = PART_Overlay, Type = typeof(Grid))]
    [TemplatePart(Name = PART_Window, Type = typeof(Grid))]
    [TemplatePart(Name = PART_Header, Type = typeof(Grid))]
    [TemplatePart(Name = PART_HeaderThumb, Type = typeof(UIElement))]
    [TemplatePart(Name = PART_Icon, Type = typeof(ContentControl))]
    [TemplatePart(Name = PART_CloseButton, Type = typeof(Button))]
    [TemplatePart(Name = PART_Border, Type = typeof(Border))]
    [TemplatePart(Name = PART_Content, Type = typeof(ContentPresenter))]
    [StyleTypedProperty(Property = nameof(CloseButtonStyle), StyleTargetType = typeof(Button))]
    public class ChildWindow : ContentControl
    {
        private const string PART_Overlay = "PART_Overlay";
        private const string HideStoryboard = "HideStoryboard";
        private const string PART_Window = "PART_Window";
        private const string PART_Header = "PART_Header";
        private const string PART_HeaderThumb = "PART_HeaderThumb";
        private const string PART_Icon = "PART_Icon";
        private const string PART_CloseButton = "PART_CloseButton";
        private const string PART_Border = "PART_Border";
        private const string PART_Content = "PART_Content";

        private DispatcherTimer autoCloseTimer;

        /// Identifies the <see cref="AllowMove"/> dependency property.
        public static readonly DependencyProperty AllowMoveProperty
            = DependencyProperty.Register(nameof(AllowMove),
                                          typeof(bool),
                                          typeof(ChildWindow),
                                          new PropertyMetadata(default(bool)));

        ///
        /// Gets or sets a value indicating whether the child window can be moved inside the overlay container.
        ///
        public bool AllowMove
        {
            get => (bool)this.GetValue(AllowMoveProperty);
            set => this.SetValue(AllowMoveProperty, value);
        }

        /// Identifies the <see cref="OffsetX"/> dependency property.
        public static readonly DependencyProperty OffsetXProperty
            = DependencyProperty.Register(nameof(OffsetX),
                                          typeof(double),
                                          typeof(ChildWindow),
                                          new UIPropertyMetadata(0d, OnOffsetXChanged));

        ///
        /// Gets or Sets the current X-Position of the ChildWindow.
        ///
        public double OffsetX
        {
            get => (double)this.GetValue(OffsetXProperty);
            set => this.SetValue(OffsetXProperty, value);
        }

        private static void OnOffsetXChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is ChildWindow childWindow)
            {
                childWindow.moveTransform.SetCurrentValue(TranslateTransform.XProperty, e.NewValue);
            }
        }

        /// Identifies the <see cref="OffsetY"/> dependency property.
        public static readonly DependencyProperty OffsetYProperty
            = DependencyProperty.Register(nameof(OffsetY),
                                          typeof(double),
                                          typeof(ChildWindow),
                                          new UIPropertyMetadata(0d, OnOffsetYChanged));

        ///
        /// Gets or Sets the current Y-Position of the ChildWindow.
        ///
        public double OffsetY
        {
            get => (double)this.GetValue(OffsetYProperty);
            set => this.SetValue(OffsetYProperty, value);
        }

        private static void OnOffsetYChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is ChildWindow childWindow)
            {
                childWindow.moveTransform.SetCurrentValue(TranslateTransform.YProperty, e.NewValue);
            }
        }

        /// Identifies the <see cref="IsModal"/> dependency property.
        public static readonly DependencyProperty IsModalProperty
            = DependencyProperty.Register(nameof(IsModal),
                                          typeof(bool),
                                          typeof(ChildWindow),
                                          new FrameworkPropertyMetadata(true, FrameworkPropertyMetadataOptions.AffectsRender));

        ///
        /// Gets or sets a value indicating whether the child window is modal.
        ///
        public bool IsModal
        {
            get => (bool)this.GetValue(IsModalProperty);
            set => this.SetValue(IsModalProperty, value);
        }

        /// Identifies the <see cref="OverlayBrush"/> dependency property.
        public static readonly DependencyProperty OverlayBrushProperty
            = DependencyProperty.Register(nameof(OverlayBrush),
                                          typeof(Brush),
                                          typeof(ChildWindow),
                                          new FrameworkPropertyMetadata(Brushes.Transparent, FrameworkPropertyMetadataOptions.AffectsRender));

        ///
        /// Gets or sets the overlay brush.
        ///
        public Brush OverlayBrush
        {
            get => (Brush)this.GetValue(OverlayBrushProperty);
            set => this.SetValue(OverlayBrushProperty, value);
        }

        /// Identifies the <see cref="CloseOnOverlay"/> dependency property.
        public static readonly DependencyProperty CloseOnOverlayProperty
            = DependencyProperty.Register(nameof(CloseOnOverlay),
                                          typeof(bool),
                                          typeof(ChildWindow),
                                          new PropertyMetadata(default(bool)));

        ///
        /// Gets or sets a value indicating whether the child window can be closed by clicking the overlay container.
        ///
        public bool CloseOnOverlay
        {
            get => (bool)this.GetValue(CloseOnOverlayProperty);
            set => this.SetValue(CloseOnOverlayProperty, value);
        }

        /// Identifies the <see cref="CloseByEscape"/> dependency property.
        public static readonly DependencyProperty CloseByEscapeProperty
            = DependencyProperty.Register(nameof(CloseByEscape),
                                          typeof(bool),
                                          typeof(ChildWindow),
                                          new PropertyMetadata(true));

        ///
        /// Gets or sets a value indicating whether the child window can be closed by the Escape key.
        ///
        public bool CloseByEscape
        {
            get => (bool)this.GetValue(CloseByEscapeProperty);
            set => this.SetValue(CloseByEscapeProperty, value);
        }

        /// Identifies the <see cref="ShowTitleBar"/> dependency property.
        public static readonly DependencyProperty ShowTitleBarProperty
            = DependencyProperty.Register(nameof(ShowTitleBar),
                                          typeof(bool),
                                          typeof(ChildWindow),
                                          new PropertyMetadata(true));

        ///
        /// Gets or sets whether the title bar is visible or not.
        ///
        public bool ShowTitleBar
        {
            get => (bool)this.GetValue(ShowTitleBarProperty);
            set => this.SetValue(ShowTitleBarProperty, value);
        }

        /// Identifies the <see cref="TitleBarHeight"/> dependency property.
        public static readonly DependencyProperty TitleBarHeightProperty
            = DependencyProperty.Register(nameof(TitleBarHeight),
                                          typeof(int),
                                          typeof(ChildWindow),
                                          new PropertyMetadata(30));

        ///
        /// Gets or sets the height of the title bar.
        ///
        public int TitleBarHeight
        {
            get => (int)this.GetValue(TitleBarHeightProperty);
            set => this.SetValue(TitleBarHeightProperty, value);
        }

        /// Identifies the <see cref="TitleBarBackground"/> dependency property.
        public static readonly DependencyProperty TitleBarBackgroundProperty
            = DependencyProperty.Register(nameof(TitleBarBackground),
                                          typeof(Brush),
                                          typeof(ChildWindow),
                                          new FrameworkPropertyMetadata(Brushes.Transparent, FrameworkPropertyMetadataOptions.AffectsRender));

        ///
        /// Gets or sets the title bar background.
        ///
        public Brush TitleBarBackground
        {
            get => (Brush)this.GetValue(TitleBarBackgroundProperty);
            set => this.SetValue(TitleBarBackgroundProperty, value);
        }

        /// Identifies the <see cref="TitleBarNonActiveBackground"/> dependency property.
        public static readonly DependencyProperty TitleBarNonActiveBackgroundProperty
            = DependencyProperty.Register(nameof(TitleBarNonActiveBackground),
                                          typeof(Brush),
                                          typeof(ChildWindow),
                                          new PropertyMetadata(Brushes.Gray));

        ///
        /// Gets or sets the title bar background for non-active status.
        ///
        public Brush TitleBarNonActiveBackground
        {
            get => (Brush)this.GetValue(TitleBarNonActiveBackgroundProperty);
            set => this.SetValue(TitleBarNonActiveBackgroundProperty, value);
        }

        /// Identifies the <see cref="NonActiveBorderBrush"/> dependency property.
        public static readonly DependencyProperty NonActiveBorderBrushProperty
            = DependencyProperty.Register(nameof(NonActiveBorderBrush),
                                          typeof(Brush),
                                          typeof(ChildWindow),
                                          new PropertyMetadata(Brushes.Gray));

        ///
        /// Gets or sets the border brush for non-active status.
        ///
        public Brush NonActiveBorderBrush
        {
            get => (Brush)this.GetValue(NonActiveBorderBrushProperty);
            set => this.SetValue(NonActiveBorderBrushProperty, value);
        }

        /// Identifies the <see cref="TitleForeground"/> dependency property.
        public static readonly DependencyProperty TitleForegroundProperty
            = DependencyProperty.Register(nameof(TitleForeground),
                                          typeof(Brush),
                                          typeof(ChildWindow),
                                          new FrameworkPropertyMetadata(Brushes.Black, FrameworkPropertyMetadataOptions.AffectsRender));

        ///
        /// Gets or sets the title foreground.
        ///
        public Brush TitleForeground
        {
            get => (Brush)this.GetValue(TitleForegroundProperty);
            set => this.SetValue(TitleForegroundProperty, value);
        }

        /// Identifies the <see cref="Title"/> dependency property.
        public static readonly DependencyProperty TitleProperty
            = DependencyProperty.Register(nameof(Title),
                                          typeof(string),
                                          typeof(ChildWindow),
                                          new PropertyMetadata(default(string)));

        ///
        /// Gets or sets the title.
        ///
        public string Title
        {
            get => (string)this.GetValue(TitleProperty);
            set => this.SetValue(TitleProperty, value);
        }

        /// Identifies the <see cref="TitleCharacterCasing"/> dependency property.
        public static readonly DependencyProperty TitleCharacterCasingProperty
            = DependencyProperty.Register(nameof(TitleCharacterCasing),
                                          typeof(CharacterCasing),
                                          typeof(ChildWindow),
                                          new FrameworkPropertyMetadata(CharacterCasing.Normal, FrameworkPropertyMetadataOptions.Inherits | FrameworkPropertyMetadataOptions.AffectsMeasure),
                                          value => CharacterCasing.Normal <= (CharacterCasing)value && (CharacterCasing)value <= CharacterCasing.Upper);

        ///
        /// Gets or sets the character casing of the title.
        ///
        public CharacterCasing TitleCharacterCasing
        {
            get => (CharacterCasing)this.GetValue(TitleCharacterCasingProperty);
            set => this.SetValue(TitleCharacterCasingProperty, value);
        }

        /// Identifies the <see cref="TitleHorizontalAlignment"/> dependency property.
        public static readonly DependencyProperty TitleHorizontalAlignmentProperty
            = DependencyProperty.Register(nameof(TitleHorizontalAlignment),
                                          typeof(HorizontalAlignment),
                                          typeof(ChildWindow),
                                          new PropertyMetadata(HorizontalAlignment.Stretch));

        ///
        /// Gets or sets the title horizontal alignment.
        ///
        public HorizontalAlignment TitleHorizontalAlignment
        {
            get => (HorizontalAlignment)this.GetValue(TitleHorizontalAlignmentProperty);
            set => this.SetValue(TitleHorizontalAlignmentProperty, value);
        }

        /// Identifies the <see cref="TitleVerticalAlignment"/> dependency property.
        public static readonly DependencyProperty TitleVerticalAlignmentProperty
            = DependencyProperty.Register(nameof(TitleVerticalAlignment),
                                          typeof(VerticalAlignment),
                                          typeof(ChildWindow),
                                          new PropertyMetadata(VerticalAlignment.Center));

        ///
        /// Gets or sets the title vertical alignment.
        ///
        public VerticalAlignment TitleVerticalAlignment
        {
            get => (VerticalAlignment)this.GetValue(TitleVerticalAlignmentProperty);
            set => this.SetValue(TitleVerticalAlignmentProperty, value);
        }

        /// Identifies the <see cref="TitleTemplate"/> dependency property.
        public static readonly DependencyProperty TitleTemplateProperty
            = DependencyProperty.Register(nameof(TitleTemplate),
                                          typeof(DataTemplate),
                                          typeof(ChildWindow),
                                          new PropertyMetadata(null));

        ///
        /// Gets or sets the title content template to show a custom title.
        ///
        public DataTemplate TitleTemplate
        {
            get => (DataTemplate)this.GetValue(TitleTemplateProperty);
            set => this.SetValue(TitleTemplateProperty, value);
        }

        /// Identifies the <see cref="TitleFontSize"/> dependency property.
        public static readonly DependencyProperty TitleFontSizeProperty
            = DependencyProperty.Register(nameof(TitleFontSize),
                                          typeof(double),
                                          typeof(ChildWindow),
                                          new FrameworkPropertyMetadata(SystemFonts.CaptionFontSize, FrameworkPropertyMetadataOptions.Inherits | FrameworkPropertyMetadataOptions.AffectsRender));

        ///
        /// The FontSize property specifies the size of the title.
        ///
        [TypeConverter(typeof(FontSizeConverter))]
        public double TitleFontSize
        {
            get => (double)this.GetValue(TitleFontSizeProperty);
            set => this.SetValue(TitleFontSizeProperty, value);
        }

        /// Identifies the <see cref="TitleFontFamily"/> dependency property.
        public static readonly DependencyProperty TitleFontFamilyProperty
            = DependencyProperty.Register(nameof(TitleFontFamily),
                                          typeof(FontFamily),
                                          typeof(ChildWindow),
                                          new FrameworkPropertyMetadata(SystemFonts.CaptionFontFamily, FrameworkPropertyMetadataOptions.Inherits | FrameworkPropertyMetadataOptions.AffectsRender));

        ///
        /// The FontFamily property specifies the font family of the title.
        ///
        [Bindable(true)]
        public FontFamily TitleFontFamily
        {
            get => (FontFamily)this.GetValue(TitleFontFamilyProperty);
            set => this.SetValue(TitleFontFamilyProperty, value);
        }

        /// Identifies the <see cref="Icon"/> dependency property.
        public static readonly DependencyProperty IconProperty
            = DependencyProperty.Register(nameof(Icon),
                                          typeof(object),
                                          typeof(ChildWindow),
                                          new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsArrange));

        ///
        /// Gets or sets a icon for the title bar.
        ///
        [Bindable(true)]
        public object Icon
        {
            get => this.GetValue(IconProperty);
            set => this.SetValue(IconProperty, value);
        }

        /// Identifies the <see cref="IconTemplate"/> dependency property.
        public static readonly DependencyProperty IconTemplateProperty
            = DependencyProperty.Register(nameof(IconTemplate),
                                          typeof(DataTemplate),
                                          typeof(ChildWindow),
                                          new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsArrange));

        ///
        /// Gets or sets a icon content template for the title bar.
        ///
        [Bindable(true)]
        public DataTemplate IconTemplate
        {
            get => (DataTemplate)this.GetValue(IconTemplateProperty);
            set => this.SetValue(IconTemplateProperty, value);
        }

        /// Identifies the <see cref="ShowCloseButton"/> dependency property.
        public static readonly DependencyProperty ShowCloseButtonProperty
            = DependencyProperty.Register(nameof(ShowCloseButton),
                                          typeof(bool),
                                          typeof(ChildWindow),
                                          new FrameworkPropertyMetadata(default(bool), FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsArrange));

        ///
        /// Gets or sets if the close button is visible.
        ///
        public bool ShowCloseButton
        {
            get => (bool)this.GetValue(ShowCloseButtonProperty);
            set => this.SetValue(ShowCloseButtonProperty, value);
        }

        /// Identifies the <see cref="CloseButtonStyle"/> dependency property.
        public static readonly DependencyProperty CloseButtonStyleProperty
            = DependencyProperty.Register(nameof(CloseButtonStyle),
                                          typeof(Style),
                                          typeof(ChildWindow),
                                          new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsArrange));

        ///
        /// Gets or sets the close button style.
        ///
        [Bindable(true)]
        public Style CloseButtonStyle
        {
            get => (Style)this.GetValue(CloseButtonStyleProperty);
            set => this.SetValue(CloseButtonStyleProperty, value);
        }

        /// Identifies the <see cref="CloseButtonCommand"/> dependency property.
        public static readonly DependencyProperty CloseButtonCommandProperty
            = DependencyProperty.Register(nameof(CloseButtonCommand),
                                          typeof(ICommand),
                                          typeof(ChildWindow),
                                          new PropertyMetadata(default(ICommand)));

        ///
        /// Gets or sets the command that is executed when the Close Button is clicked.
        ///
        public ICommand CloseButtonCommand
        {
            get => (ICommand)this.GetValue(CloseButtonCommandProperty);
            set => this.SetValue(CloseButtonCommandProperty, value);
        }

        /// Identifies the <see cref="CloseButtonCommandParameter"/> dependency property.
        public static readonly DependencyProperty CloseButtonCommandParameterProperty
            = DependencyProperty.Register(nameof(CloseButtonCommandParameter),
                                          typeof(object),
                                          typeof(ChildWindow),
                                          new PropertyMetadata(null));

        ///
        /// Gets or sets the command parameter that is used by the CloseButtonCommand when the Close Button is clicked.
        ///
        public object CloseButtonCommandParameter
        {
            get => this.GetValue(CloseButtonCommandParameterProperty);
            set => this.SetValue(CloseButtonCommandParameterProperty, value);
        }

        /// Identifies the <see cref="IsOpen"/> dependency property.
        public static readonly DependencyProperty IsOpenProperty
            = DependencyProperty.Register(nameof(IsOpen),
                                          typeof(bool),
                                          typeof(ChildWindow),
                                          new FrameworkPropertyMetadata(default(bool), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnIsOpenChanged));

        ///
        /// Gets or sets a value indicating whether this instance is open or closed.
        ///
        public bool IsOpen
        {
            get => (bool)this.GetValue(IsOpenProperty);
            set => this.SetValue(IsOpenProperty, value);
        }

        /// Identifies the <see cref="ChildWindowWidth"/> dependency property.
        public static readonly DependencyProperty ChildWindowWidthProperty
            = DependencyProperty.Register(nameof(ChildWindowWidth),
                                          typeof(double),
                                          typeof(ChildWindow),
                                          new FrameworkPropertyMetadata(Double.NaN, FrameworkPropertyMetadataOptions.AffectsMeasure), IsWidthHeightValid);

        ///
        /// Gets or sets the width of the child window.
        ///
        public double ChildWindowWidth
        {
            get => (double)this.GetValue(ChildWindowWidthProperty);
            set => this.SetValue(ChildWindowWidthProperty, value);
        }

        private static bool IsWidthHeightValid(object value)
        {
            var v = (double)value;
            return (double.IsNaN(v)) || (v >= 0.0d && !double.IsPositiveInfinity(v));
        }

        /// Identifies the <see cref="ChildWindowHeight"/> dependency property.
        public static readonly DependencyProperty ChildWindowHeightProperty
            = DependencyProperty.Register(nameof(ChildWindowHeight),
                                          typeof(double),
                                          typeof(ChildWindow),
                                          new FrameworkPropertyMetadata(Double.NaN, FrameworkPropertyMetadataOptions.AffectsMeasure), IsWidthHeightValid);

        ///
        /// Gets or sets the height of the child window.
        ///
        public double ChildWindowHeight
        {
            get => (double)this.GetValue(ChildWindowHeightProperty);
            set => this.SetValue(ChildWindowHeightProperty, value);
        }

        /// Identifies the <see cref="ChildWindowMinWidth"/> dependency property.
        public static readonly DependencyProperty ChildWindowMinWidthProperty
            = DependencyProperty.Register(nameof(ChildWindowMinWidth),
                                          typeof(double),
                                          typeof(ChildWindow),
                                          new FrameworkPropertyMetadata(Double.NaN, FrameworkPropertyMetadataOptions.AffectsMeasure), IsWidthHeightValid);

        ///
        /// Gets or sets the min width of the child window.
        ///
        public double ChildWindowMinWidth
        {
            get => (double)this.GetValue(ChildWindowMinWidthProperty);
            set => this.SetValue(ChildWindowMinWidthProperty, value);
        }

        /// Identifies the <see cref="ChildWindowMinHeight"/> dependency property.
        public static readonly DependencyProperty ChildWindowMinHeightProperty
            = DependencyProperty.Register(nameof(ChildWindowMinHeight),
                                          typeof(double),
                                          typeof(ChildWindow),
                                          new FrameworkPropertyMetadata(Double.NaN, FrameworkPropertyMetadataOptions.AffectsMeasure), IsWidthHeightValid);

        ///
        /// Gets or sets the min height of the child window.
        ///
        public double ChildWindowMinHeight
        {
            get => (double)this.GetValue(ChildWindowMinHeightProperty);
            set => this.SetValue(ChildWindowMinHeightProperty, value);
        }

        /// Identifies the <see cref="ChildWindowMaxWidth"/> dependency property.
        public static readonly DependencyProperty ChildWindowMaxWidthProperty
            = DependencyProperty.Register(nameof(ChildWindowMaxWidth),
                                          typeof(double),
                                          typeof(ChildWindow),
                                          new FrameworkPropertyMetadata(Double.NaN, FrameworkPropertyMetadataOptions.AffectsMeasure), IsWidthHeightValid);

        ///
        /// Gets or sets the max width of the child window.
        ///
        public double ChildWindowMaxWidth
        {
            get => (double)this.GetValue(ChildWindowMaxWidthProperty);
            set => this.SetValue(ChildWindowMaxWidthProperty, value);
        }

        /// Identifies the <see cref="ChildWindowMaxHeight"/> dependency property.
        public static readonly DependencyProperty ChildWindowMaxHeightProperty
            = DependencyProperty.Register(nameof(ChildWindowMaxHeight),
                                          typeof(double),
                                          typeof(ChildWindow),
                                          new FrameworkPropertyMetadata(Double.NaN, FrameworkPropertyMetadataOptions.AffectsMeasure), IsWidthHeightValid);

        ///
        /// Gets or sets the max height of the child window.
        ///
        public double ChildWindowMaxHeight
        {
            get => (double)this.GetValue(ChildWindowMaxHeightProperty);
            set => this.SetValue(ChildWindowMaxHeightProperty, value);
        }

        /// Identifies the <see cref="ChildWindowImage"/> dependency property.
        public static readonly DependencyProperty ChildWindowImageProperty
            = DependencyProperty.Register(nameof(ChildWindowImage),
                                          typeof(MessageBoxImage),
                                          typeof(ChildWindow),
                                          new FrameworkPropertyMetadata(MessageBoxImage.None, FrameworkPropertyMetadataOptions.AffectsMeasure));

        ///
        /// Gets or sets which image is shown on the left side of the window content.
        ///
        public MessageBoxImage ChildWindowImage
        {
            get => (MessageBoxImage)this.GetValue(ChildWindowImageProperty);
            set => this.SetValue(ChildWindowImageProperty, value);
        }

        /// Identifies the <see cref="EnableDropShadow"/> dependency property.
        public static readonly DependencyProperty EnableDropShadowProperty
            = DependencyProperty.Register(nameof(EnableDropShadow),
                                          typeof(bool),
                                          typeof(ChildWindow),
                                          new FrameworkPropertyMetadata(true, FrameworkPropertyMetadataOptions.AffectsRender));

        ///
        /// Gets or sets a value indicating whether the window has a drop shadow (glow brush).
        ///
        public bool EnableDropShadow
        {
            get => (bool)this.GetValue(EnableDropShadowProperty);
            set => this.SetValue(EnableDropShadowProperty, value);
        }

        /// Identifies the <see cref="AllowFocusElement"/> dependency property.
        public static readonly DependencyProperty AllowFocusElementProperty
            = DependencyProperty.Register(nameof(AllowFocusElement),
                                          typeof(bool),
                                          typeof(ChildWindow),
                                          new PropertyMetadata(true));

        ///
        /// Gets or sets a value indicating whether the child window should try focus an element.
        ///
        public bool AllowFocusElement
        {
            get => (bool)this.GetValue(AllowFocusElementProperty);
            set => this.SetValue(AllowFocusElementProperty, value);
        }

        /// Identifies the <see cref="FocusedElement"/> dependency property.
        public static readonly DependencyProperty FocusedElementProperty
            = DependencyProperty.Register(nameof(FocusedElement),
                                          typeof(FrameworkElement),
                                          typeof(ChildWindow),
                                          new UIPropertyMetadata(null));

        ///
        /// Gets or sets the focused element.
        ///
        public FrameworkElement FocusedElement
        {
            get => (FrameworkElement)this.GetValue(FocusedElementProperty);
            set => this.SetValue(FocusedElementProperty, value);
        }

        /// Identifies the <see cref="GlowBrush"/> dependency property.
        public static readonly DependencyProperty GlowBrushProperty
            = DependencyProperty.Register(nameof(GlowBrush),
                                          typeof(SolidColorBrush),
                                          typeof(ChildWindow),
                                          new FrameworkPropertyMetadata(Brushes.Black, FrameworkPropertyMetadataOptions.AffectsRender));

        ///
        /// Gets or sets the glow brush (drop shadow).
        ///
        public SolidColorBrush GlowBrush
        {
            get => (SolidColorBrush)this.GetValue(GlowBrushProperty);
            set => this.SetValue(GlowBrushProperty, value);
        }

        /// Identifies the <see cref="NonActiveGlowBrush"/> dependency property.
        public static readonly DependencyProperty NonActiveGlowBrushProperty
            = DependencyProperty.Register(nameof(NonActiveGlowBrush),
                                          typeof(SolidColorBrush),
                                          typeof(ChildWindow),
                                          new PropertyMetadata(Brushes.Gray));

        ///
        /// Gets or sets the glow brush (drop shadow) for non-active status.
        ///
        public SolidColorBrush NonActiveGlowBrush
        {
            get => (SolidColorBrush)this.GetValue(NonActiveGlowBrushProperty);
            set => this.SetValue(NonActiveGlowBrushProperty, value);
        }

        /// Identifies the <see cref="IsAutoCloseEnabled"/> dependency property.
        public static readonly DependencyProperty IsAutoCloseEnabledProperty
            = DependencyProperty.Register(nameof(IsAutoCloseEnabled),
                                          typeof(bool),
                                          typeof(ChildWindow),
                                          new FrameworkPropertyMetadata(false, OnIsAutoCloseEnabledChanged));

        ///
        /// Gets or sets a value indicating whether the ChildWindow should auto close after AutoCloseInterval has passed.
        ///
        public bool IsAutoCloseEnabled
        {
            get => (bool)this.GetValue(IsAutoCloseEnabledProperty);
            set => this.SetValue(IsAutoCloseEnabledProperty, value);
        }

        /// Identifies the <see cref="AutoCloseInterval"/> dependency property.
        public static readonly DependencyProperty AutoCloseIntervalProperty
            = DependencyProperty.Register(nameof(AutoCloseInterval),
                                          typeof(long),
                                          typeof(ChildWindow),
                                          new FrameworkPropertyMetadata(5000L, OnAutoCloseIntervalChanged));

        ///
        /// Gets or sets the time in milliseconds when the ChildWindow should auto close.
        ///
        public long AutoCloseInterval
        {
            get => (long)this.GetValue(AutoCloseIntervalProperty);
            set => this.SetValue(AutoCloseIntervalProperty, value);
        }

        /// Identifies the <see cref="IsWindowHostActive"/> dependency property.
        public static readonly DependencyProperty IsWindowHostActiveProperty
            = DependencyProperty.Register(nameof(IsWindowHostActive),
                                          typeof(bool),
                                          typeof(ChildWindow),
                                          new PropertyMetadata(true));

        ///
        /// Gets or sets a value indicating whether the host Window is active or not.
        ///
        public bool IsWindowHostActive
        {
            get => (bool)this.GetValue(IsWindowHostActiveProperty);
            set => this.SetValue(IsWindowHostActiveProperty, value);
        }

        /// Identifies the <see cref="CornerRadius" /> dependency property.
        /// <returns>The identifier for the <see cref="P:System.Windows.Controls.Border.CornerRadius" /> dependency property.</returns>
        public static readonly DependencyProperty CornerRadiusProperty
            = DependencyProperty.Register(nameof(CornerRadius),
                                          typeof(CornerRadius),
                                          typeof(ChildWindow),
                                          new FrameworkPropertyMetadata(new CornerRadius(), FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsRender));

        ///
        /// Gets or sets a value that represents the degree to which the corners of a <see cref="SimpleChildWindow" /> are rounded.
        /// <returns>
        /// The <see cref="T:System.Windows.CornerRadius" /> that describes the degree to which corners are rounded. This property has no default value.
        /// </returns>
        public CornerRadius CornerRadius
        {
            get => (CornerRadius)this.GetValue(Border.CornerRadiusProperty);
            set => this.SetValue(Border.CornerRadiusProperty, (object)value);
        }

        ///
        /// An event that will be raised when <see cref="IsOpen"/> dependency property changes.
        ///
        public static readonly RoutedEvent IsOpenChangedEvent
            = EventManager.RegisterRoutedEvent(nameof(IsOpenChanged),
                                               RoutingStrategy.Bubble,
                                               typeof(RoutedEventHandler),
                                               typeof(ChildWindow));

        ///
        /// An event that will be raised when <see cref="IsOpen"/> dependency property changes.
        ///
        public event RoutedEventHandler IsOpenChanged
        {
            add => this.AddHandler(IsOpenChangedEvent, value);
            remove => this.RemoveHandler(IsOpenChangedEvent, value);
        }

        ///
        /// An event that will be raised when the ChildWindow is closing.
        ///
        public event EventHandler<CancelEventArgs> Closing;

        ///
        /// An event that will be raised when the closing animation has finished.
        ///
        public static readonly RoutedEvent ClosingFinishedEvent
            = EventManager.RegisterRoutedEvent(nameof(ClosingFinished),
                                               RoutingStrategy.Bubble,
                                               typeof(RoutedEventHandler),
                                               typeof(ChildWindow));

        ///
        /// An event that will be raised when the closing animation has finished.
        ///
        public event RoutedEventHandler ClosingFinished
        {
            add => this.AddHandler(ClosingFinishedEvent, value);
            remove => this.RemoveHandler(ClosingFinishedEvent, value);
        }

        protected override void OnPreviewMouseDown(MouseButtonEventArgs e)
        {
            base.OnPreviewMouseDown(e);

            if (!e.Handled)
            {
                var container = this.Parent as Panel;
                var elementOnTop = container?.Children.OfType<UIElement>().OrderBy(c => c.GetValue(Panel.ZIndexProperty)).LastOrDefault();
                if (elementOnTop != null && !Equals(elementOnTop, this))
                {
                    var zIndexOnTop = (int)elementOnTop.GetValue(Panel.ZIndexProperty);
                    elementOnTop.SetCurrentValue(Panel.ZIndexProperty, zIndexOnTop - 1);
                    this.SetCurrentValue(Panel.ZIndexProperty, zIndexOnTop);
                }
            }
        }

        private static void OnIsOpenChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
        {
            if (Equals(e.OldValue, e.NewValue))
            {
                return;
            }

            var childWindow = (ChildWindow)dependencyObject;

            void OpenChangedAction()
            {
                if ((bool)e.NewValue)
                {
                    if (childWindow.hideStoryboard != null)
                    {
                        // don't let the storyboard end it's completed event
                        // otherwise it could be hidden on start
                        childWindow.hideStoryboard.Completed -= childWindow.HideStoryboard_Completed;
                    }

                    var parent = childWindow.Parent as Panel;
                    // Panel.SetZIndex(childWindow, parent?.Children.Count + 1 ?? 99);
                    Panel.SetZIndex(childWindow, parent?.Children.Count ?? 99);

                    childWindow.TryToSetFocusedElement();

                    if (childWindow.IsAutoCloseEnabled)
                    {
                        childWindow.StartAutoCloseTimer();
                    }
                }
                else
                {
                    childWindow.StopAutoCloseTimer();

                    if (childWindow.hideStoryboard != null)
                    {
                        childWindow.hideStoryboard.Completed += childWindow.HideStoryboard_Completed;
                    }
                    else
                    {
                        childWindow.OnClosingFinished();
                    }
                }

                VisualStateManager.GoToState(childWindow, (bool)e.NewValue == false ? "Hide" : "Show", true);

                childWindow.RaiseEvent(new RoutedEventArgs(IsOpenChangedEvent, childWindow));
            }

            childWindow.Dispatcher?.BeginInvoke(DispatcherPriority.Background, (Action)OpenChangedAction);
        }

        private void TryToSetFocusedElement()
        {
            if (this.AllowFocusElement && !DesignerProperties.GetIsInDesignMode(this))
            {
                // first focus itself
                this.Focus();

                var elementToFocus = this.FocusedElement ?? TreeHelper.FindChildren<UIElement>(this).FirstOrDefault(c => c.Focusable);
                if (this.ShowCloseButton && this.closeButton != null && elementToFocus == null)
                {
                    this.closeButton.SetCurrentValue(FocusableProperty, true);
                    elementToFocus = this.closeButton;
                }

                if (elementToFocus != null)
                {
                    void OnIsVisibleChanged(object sender, DependencyPropertyChangedEventArgs args)
                    {
                        elementToFocus.IsVisibleChanged -= OnIsVisibleChanged;
                        if (elementToFocus.Focusable && elementToFocus is HwndHost == false)
                        {
                            elementToFocus.Focus();
                        }
                    }

                    elementToFocus.IsVisibleChanged += OnIsVisibleChanged;
                }
            }
        }

        private void HideStoryboard_Completed(object sender, EventArgs e)
        {
            this.hideStoryboard.Completed -= this.HideStoryboard_Completed;
            this.OnClosingFinished();
        }

        private void OnClosingFinished()
        {
            this.RaiseEvent(new RoutedEventArgs(ClosingFinishedEvent, this));
        }

        ///
        /// Gets the child window result when the dialog will be closed.
        ///
        public object ChildWindowResult { get; protected set; }

        ///
        /// Gets the dialog close reason.
        ///
        public CloseReason ClosedBy { get; private set; } = CloseReason.None;

        private static void OnIsAutoCloseEnabledChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
        {
            var childWindow = (ChildWindow)dependencyObject;

            void AutoCloseEnabledChangedAction()
            {
                if (e.NewValue != e.OldValue)
                {
                    if ((bool)e.NewValue)
                    {
                        if (childWindow.IsOpen)
                        {
                            childWindow.StartAutoCloseTimer();
                        }
                    }
                    else
                    {
                        childWindow.StopAutoCloseTimer();
                    }
                }
            }

            childWindow.Dispatcher?.BeginInvoke(DispatcherPriority.Background, (Action)AutoCloseEnabledChangedAction);
        }

        private static void OnAutoCloseIntervalChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
        {
            var childWindow = (ChildWindow)dependencyObject;

            void AutoCloseIntervalChangedAction()
            {
                if (e.NewValue != e.OldValue)
                {
                    childWindow.InitializeAutoCloseTimer();
                    if (childWindow.IsAutoCloseEnabled && childWindow.IsOpen)
                    {
                        childWindow.StartAutoCloseTimer();
                    }
                }
            }

            childWindow.Dispatcher?.BeginInvoke(DispatcherPriority.Background, (Action)AutoCloseIntervalChangedAction);
        }

        private void InitializeAutoCloseTimer()
        {
            this.StopAutoCloseTimer();

            this.autoCloseTimer = new DispatcherTimer();
            this.autoCloseTimer.Tick += this.AutoCloseTimerCallback;
            this.autoCloseTimer.Interval = TimeSpan.FromMilliseconds(this.AutoCloseInterval);
        }

        private void AutoCloseTimerCallback(object sender, EventArgs e)
        {
            this.StopAutoCloseTimer();

            // if the ChildWindow is open and autoclose is still enabled then close the ChildWindow
            if (this.IsOpen && this.IsAutoCloseEnabled)
            {
                this.Close(CloseReason.AutoClose);
            }
        }

        private void StartAutoCloseTimer()
        {
            // in case it is already running
            this.StopAutoCloseTimer();
            if (!DesignerProperties.GetIsInDesignMode(this))
            {
                this.autoCloseTimer?.Start();
            }
        }

        private void StopAutoCloseTimer()
        {
            if (this.autoCloseTimer is { IsEnabled: true })
            {
                this.autoCloseTimer.Stop();
            }
        }

        private string closeText;

        ///
        /// Gets the close button tool tip.
        ///
        public string CloseButtonToolTip
        {
            get
            {
                if (string.IsNullOrEmpty(this.closeText))
                {
                    this.closeText = this.GetCaption(905);
                }

                return this.closeText;
            }
        }

        private Storyboard hideStoryboard;
        private IMetroThumb headerThumb;
        private Button closeButton;
        private readonly TranslateTransform moveTransform = new TranslateTransform();
        private Grid partWindow;
        private Grid partOverlay;
        private ContentControl icon;

        static ChildWindow()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(ChildWindow), new FrameworkPropertyMetadata(typeof(ChildWindow)));
        }

        public ChildWindow()
        {
            this.InitializeAutoCloseTimer();
        }

        /// <inheritdoc />
        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            // really necessary?
            if (this.Template == null)
            {
                return;
            }

            var isActiveBindingAction = new Action(() =>
                {
                    var window = Window.GetWindow(this);
                    if (window != null)
                    {
                        this.SetBinding(IsWindowHostActiveProperty, new Binding(nameof(Window.IsActive)) { Source = window, Mode = BindingMode.OneWay });
                    }
                });
            if (!this.IsLoaded)
            {
                this.BeginInvoke(isActiveBindingAction, DispatcherPriority.Loaded);
            }
            else
            {
                isActiveBindingAction();
            }

            this.hideStoryboard = this.Template.FindName(HideStoryboard, this) as Storyboard;

            if (this.partOverlay != null)
            {
                this.partOverlay.MouseLeftButtonDown -= this.PartOverlayOnClose;
                this.partOverlay.SizeChanged -= this.PartOverlay_SizeChanged;
            }

            this.partOverlay = this.Template.FindName(PART_Overlay, this) as Grid;
            if (this.partOverlay != null)
            {
                this.partOverlay.MouseLeftButtonDown += this.PartOverlayOnClose;
                this.partOverlay.SizeChanged += this.PartOverlay_SizeChanged;
            }

            this.partWindow = this.Template.FindName(PART_Window, this) as Grid;
            this.partWindow?.SetCurrentValue(RenderTransformProperty, this.moveTransform);

            this.icon = this.Template.FindName(PART_Icon, this) as ContentControl;

            if (this.headerThumb != null)
            {
                this.headerThumb.DragDelta -= this.HeaderThumbDragDelta;
            }

            this.headerThumb = this.Template.FindName(PART_HeaderThumb, this) as IMetroThumb;
            if (this.headerThumb != null && this.partWindow != null)
            {
                this.headerThumb.DragDelta += this.HeaderThumbDragDelta;
            }

            if (this.closeButton != null)
            {
                this.closeButton.Click -= this.OnCloseButtonClick;
            }

            this.closeButton = this.Template.FindName(PART_CloseButton, this) as Button;
            if (this.closeButton != null)
            {
                this.closeButton.Click += this.OnCloseButtonClick;
            }
        }

        private void PartOverlayOnClose(object sender, MouseButtonEventArgs e)
        {
            if (Equals(e.OriginalSource, this.partOverlay) && this.CloseOnOverlay)
            {
                this.Close(CloseReason.Overlay);
            }
        }

        private void PartOverlay_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            this.ProcessMove(0, 0);
        }

        private void HeaderThumbDragDelta(object sender, DragDeltaEventArgs e)
        {
            var allowDragging = this.AllowMove && this.partWindow.HorizontalAlignment != HorizontalAlignment.Stretch && this.partWindow.VerticalAlignment != VerticalAlignment.Stretch;
            // drag only if IsWindowDraggable is set to true
            if (allowDragging && (Math.Abs(e.HorizontalChange) > 2 || Math.Abs(e.VerticalChange) > 2))
            {
                this.ProcessMove(e.HorizontalChange, e.VerticalChange);
            }
        }

        private void ProcessMove(double x, double y)
        {
            var width = this.partOverlay.RenderSize.Width;
            var height = this.partOverlay.RenderSize.Height;

            var offset = VisualTreeHelper.GetOffset(this.partWindow);
            var widthOffset = offset.X;
            var heightOffset = offset.Y;

            var realX = this.moveTransform.X + x + widthOffset;
            var realY = this.moveTransform.Y + y + heightOffset;

            const int extraGap = 5;
            var widthGap = Math.Max(this.icon?.ActualWidth + 5 ?? 30, 30);
            var heightGap = Math.Max(this.TitleBarHeight, 30);
            var changeX = this.moveTransform.X;
            var changeY = this.moveTransform.Y;

            if (realX < (0 + extraGap))
            {
                changeX = -widthOffset + extraGap;
            }
            else if (realX > (width - widthGap - extraGap))
            {
                changeX = width - widthOffset - widthGap - extraGap;
            }
            else
            {
                changeX += x;
            }

            if (realY < (0 + extraGap))
            {
                changeY = -heightOffset + extraGap;
            }
            else if (realY > (height - heightGap - extraGap))
            {
                changeY = height - heightOffset - heightGap - extraGap;
            }
            else
            {
                changeY += y;
            }

            if (!Equals(changeX, this.moveTransform.X) || !Equals(changeY, this.moveTransform.Y))
            {
                this.SetCurrentValue(OffsetXProperty, changeX);
                this.SetCurrentValue(OffsetYProperty, changeY);

                this.InvalidateArrange();
            }
        }

        private void OnCloseButtonClick(object sender, RoutedEventArgs e)
        {
            this.Close(CloseReason.Close);
        }

        ///
        /// This method fires the <see cref="Closing"/> event.
        ///
        /// <param name="e">The EventArgs for the closing step.</param>
        protected virtual void OnClosing(CancelEventArgs e)
        {
            this.Closing?.Invoke(this, e);
        }

        ///
        /// Closes this dialog.
        ///
        /// <param name="childWindowResult">A dialog result (optional).</param>
        public bool Close(object childWindowResult = null)
        {
            return this.Close(CloseReason.Close, childWindowResult);
        }

        ///
        /// Closes this dialog.
        ///
        /// <param name="closedBy">The dialog close reason.</param>
        /// <param name="childWindowResult">A dialog result (optional).</param>
        public bool Close(CloseReason closedBy, object childWindowResult = null)
        {
            this.ClosedBy = closedBy;

            // check if we really want close the dialog
            var e = new CancelEventArgs();
            this.OnClosing(e);

            if (!e.Cancel)
            {
                // now handle the command
                if (this.CloseButtonCommand != null)
                {
                    var parameter = this.CloseButtonCommandParameter ?? this;
                    if (!this.CloseButtonCommand.CanExecute(parameter))
                    {
                        return false;
                    }

                    this.CloseButtonCommand.Execute(parameter);
                }

                this.ChildWindowResult = childWindowResult;
                this.SetCurrentValue(IsOpenProperty, false);
                return true;
            }
            else
            {
                this.ClosedBy = CloseReason.None;
                return false;
            }
        }

        /// <inheritdoc />
        protected override void OnKeyDown(KeyEventArgs e)
        {
            if (this.CloseByEscape && e.Key == Key.Escape)
            {
                e.Handled = this.Close(CloseReason.Escape);
            }

            this.OnPreviewKeyUp(e);
        }

#pragma warning disable 618
        private SafeLibraryHandle user32;
#pragma warning restore 618

#pragma warning disable 618
        private string GetCaption(int id)
        {
            if (this.user32 == null)
            {
                this.user32 = UnsafeNativeMethods.LoadLibrary(Environment.SystemDirectory + "\\User32.dll");
            }

            var sb = new StringBuilder(256);
            UnsafeNativeMethods.LoadString(this.user32, (uint)id, sb, sb.Capacity);
            return sb.ToString().Replace("&", "");
        }
#pragma warning restore 618
    }
}


We understand that the cost of treatment is often the biggest barrier that prevents people from getting the help that they so desperately need. At West Coast Rehab, we aim to make treatment accessible for as many people as possible. During your initial admissions assessment, one of our highly qualified Admissions Coordinators will walk you through your treatment overview, the cost of treatment, and your payment options.
How much is treatment at West Coast Rehab?
The cost of treatment varies on the level of care needed and length of stay. You and your Admissions Counselor will determine all costs associated with your treatmentand they will be fully disclosed upfront.
We partner with a wide variety of insurance companies to ensure that our clients get the most coverage possible. A large portion of your treatment, if not all of your treatment, may be covered by your insurance. We will work directly with your insurance company to determine the amount of coverage available on your plan.
We offer same day insurance verification to all of our potential clients free of charge. Call 800-866-1222 and let us take care of seeing what your insurance will cover.
We also partner with a number of third party financing companies that will cover a large portion of treatment costs for qualified candidates to be paid back at a later date. Ask your Admissions Counselor for more information.
Does your insurance not cover drug or alcohol treatment? Do you not have insurance? Or would you rather privately pay for your treatment? Don't worry, we have you covered. We know that a good treatment facility can be life changing for both the addict and their family, so we provide private pay options for our clients. To learn more about your private pay options, please contact one of our Admissions Counselors at 800.866.1222.


As reported on the Public Defender Service for the District of Columbia's Criminal Law Blog, on November 13, 2014, the D.C. Court of Appeals remanded a case to the D.C. Superior Court after finding that a Farrelly PC client was improperly convicted of second degree theft. A full copy of the appellate opinion is available here.
On October 1, 2014, a District of Columbia judge found a Farrelly PC client not guilty of Second Degree Theft and Unlawful Entry. The verdict followed a bench trial in the District of Columbia Superior Court presided over by the Honorable Yvonne Williams.
Prior to the commencement of trial, counsel for the United States Attorney's Office disclosed a 911 call made by a witness to the alleged theft. Due to the late disclosure of the evidence, counsel for the accused, Sean Farrelly, was able to keep the 911 call out of the government's case in chief.
Federal magistrate judges nationwide, including right here in the District of Columbia, are thwarting law enforcement attempts to gain access to cell phone and personal data. The judges are denying requests for search warrants for such information as overly broad and in direct conflict with the basic rights afforded all United States citizens under the Constitution.
As reported in the Washington Post, in recent months, Magistrate Judge John M. Facciola of the United States District Court for the District of Columbia has denied access to the Facebook page of alleged Navy Yard shooter Aaron Alexis and the iPhone of the Georgetown University Student accused of making the deadly poison ricin in his dorm room. Magistrate Judge Facciola labeled law enforcement requests for search warrants "repugnant" to the U.S. Constitution.
As reported by the Washington Post and numerous other media outlets, the D.C. City Council voted 11-1 to decriminalize the possession of less than one ounce of marijuana. In lieu of the current criminal penalties of 180 days in jail and/or a $1,000 fine for possessing small amounts of marijuana, possession would be a civil infraction carrying a fine-only punishment, similar to a speeding or parking ticket.
If the legislation is enacted, D.C. would follow the lead of 15 other U.S. states that have already decriminalized possession of marijuana. Although possession of marijuana remains illegal under federal law, the Department of Justice has not taken any action to enforce federal law in those states that have decriminalized possession through state legislation.


"Don't worry. Be happy!" It's easy enough to sing this little song but what happens when you wake up in the middle of the night and worries come swarming into your mind like buzzing bees? Listen to this lesson to understand that God is in control of your life. Since He's already done the greatest thing for us by sending His Son to die for our sins, it's no problem for Him to take care of what we need to eat, what we need to wear, and all the other details of life. See how worry is a sin and a sign that we lack faith in God. Be aware that memorizing God's Word is a great antidote to worry.
The hymnal Dr. Dean mentioned in today's worship service, "Making Melody. Popular Choruses and Hymns that Bless, Endure, and Honor the Lord" is available at Amazon.com.


text:
Ala. Holocaust Commission condemns Rep. Brooks' "Mein Kampf" remarks
The Alabama Holocaust Commission and numerous allies stated today that they "strongly condemn" the March 25 remarks by U.S. Rep. Mo Brooks of Alabama, where he quoted portions of Adolf Hitler's "Mein Kampf" in a speech on the U.S. House floor.
Brooks was speaking about special counsel Robert Mueller's investigation on whether the Trump campaign colluded with Russia during the 2016 presidential election. He said that for two years, "socialist Democrats and their fake news media allies… have perpetrated the biggest political lie, con, scam and fraud in American history," referring to the accusations of collusion as "a Big Lie."
Brooks has continued to use the "Big Lie" theme in subsequent television and radio appearances, and in further remarks on the House floor.
In his March 25 speech, he quoted "from another Socialist who mastered 'big lie' propaganda to maximum, and deadly, effect," reading a passage from "Mein Kampf" that spoke of how the masses more easily fall victim to a big lie than a small one.
He concluded, "America can either learn from history or be doomed to repeat it. When it comes to 'Big Lie' political propaganda in America, as the Mueller report confirms, America's Socialists and their fake news media allies are experts and have no peers," and Americans must reject them "or succumb to the danger that lurks, and horrific damage that results."
In "Mein Kampf," though, Hitler uses the term "big lie" to describe a Jewish "unqualified capacity for falsehood," saying Jews were spreading the "big lie" in wrongly blaming a top German military commander for its World War I loss. He invoked the "big lie" accusation to portray Jews as deceptive traitors to Germany, making persecution, and later extermination, of Jews a matter of national self-defense.
In its response on April 3, the commission said it does not make political statements, but objects to Brooks using "Mein Kampf" and invoking Hitler's name "to condemn those with whom he disagrees."
The statement pointed out the origin of the "big lie" concept, adding that Hitler continued by saying Jews "know only too well how to use a falsehood for the basest of purposes. From time immemorial, however, the Jews have known better than any others how falsehood and calumny can be exploited."
The commission said "facile comparisons" like Brooks' remarks, "used in order to demean opponents and gain political capital, should be actively avoided. Using such rhetoric not only trivializes our past, as well as the victims of this genocide, but also cheapens our current political discourse and maintains a divisive rhetoric all too common at the present time."
The commission's response concluded with the hope that "our political leaders, whatever their party or political persuasion, should refrain from using Hitler, the Nazis, and the tragedy of the Holocaust in an effort to strengthen their public statements. Should such a strategy become the norm, then we as a society have learned nothing from the ills of the past and open the doors to the possibilities of repetition."
The statement was coordinated by the commission's chair, Dan Puckett of Wetumpka, who teaches at Troy University. Commission members and representatives for the Gulf Coast Center for Holocaust and Human Rights Education also signed it, along with a list of rabbis, ministers and the executive director of Faith in Action Alabama. David Meola, director of Jewish and Holocaust Studies at the University of South Alabama, signed it, as did renowned Holocaust scholar Rabbi Steven Jacobs, Aaron Aronov Chair of Judaic Studies at the University of Alabama.
Many others have also condemned Brooks' remarks. The Democratic Jewish Coalition of America tweeted that it was "an egregious and deeply offensive example of anti-Semitism once again rearing its head in Congress… Where is the GOP outrage?"
The Anti-Defamation League tweeted that "It's unconscionable for a member of Congress to demonize an opposing party by claiming it's comparable to Nazism. The vicious Nazi regime was responsible for the murder of 6 million Jews and millions more. This is dangerous and @RepMoBrooks must apologize."
On the House floor on April 2, Brooks continued using the theme, citing "the economic history of Germany's Socialist experiment to confirm that Socialism is the mortal enemy of Free Enterprise and that Socialism inevitably replaces freedom, liberty and economic prosperity with government dictatorship, poverty, and death."
He noted that "Socialist Democrats and their fake news media allies" objected to his March 25 remarks, "to explain what the Big Lie Propaganda Tactic is and how horrific the consequences can be for those seduced by it."
He continued, "Germany's Socialist Party's Big Lie killed tens of millions of people in the Holocaust and World War II, making it the most horrific and deadly Big Lie in history!"
Brooks has referenced "Mein Kampf" before. At a Madison town hall meeting in 2015, during debate on the Iran nuclear deal that was regarded as a major threat to Israel, Brooks compared Iran's "really aggressive statements" to Nazi Germany, then asked "Don't you wish people before World War II had read 'Mein Kampf' and paid attention to it and stopped it from ever happening?"

redpajama_set_name: RedPajamaCommonCrawl


While you are sleeping, have you experienced having a horrifying dream? Perhaps, you were being hunted by creepy monsters, chased by zombies or tied-up in an abandoned warehouse. If your answer is yes, then you've experienced a nightmare.
Nightmares are terrifying dreams that cause fear, despair, restlessness, and immense panic. This experience tends to occur in the middle of the night and, oftentimes, awakens the sleeper who is likely to remember the content of the dream. The causes of having bad dreams are classified into two groups: physical and psychological reasons.
In line with the physical causes, it can happen due to inappropriate sleeping positions. Some people sleep with their back against the bed. Another cause is having an ailment and sudden adjustment in medications. Moreover, sleeping right after eating can cause bad dreams because from the time when your stomach is digesting food, your body's metabolism increases along with your brain activity.
As for psychological effects, stress is the major reason people experience nightmares. Pressure, anxiety, and fear are also related to stress which turns a good dream into a bad one. The possible reason is that your mind is not at ease and relaxed.
Lady in her own terrible dream.
Sleeping in the best way to recharge our body from an exhausting day. As we lay down on our comfy beds at night, we expect to wake up fully rested and relaxed. Sadly, we sometimes fail to experience this because of frightening dreams. The good news is that nightmares can be prevented.
They believe that a dreamcatcher can change a person's dream. A dreamcatcher is usually hung above the head of a sleeper and serves as a charm to protect people from having nightmares. The night air is filled with dreams. It may bring good or bad ones. Through the use of a dreamcatcher, your dreams will always be sweet and peaceful.
Magical dream catcher can fight nightmare.
The dreamcatcher is decorated with sacred items such as feathers and beads. Dreams will pass through the web or the net, slide down the hanging beads and feathers and filtered down to the dreamer. However, bad dreams would be trapped inside the web. As the first rays of the morning sun hit the dreamcatcher, the bad dream or nightmare will evaporate like the morning dew.
Happy dreams can now be obtained. No more scary dreams of scary monsters, walking dead or being trapped in a dark forest. To make your dream more positive, do not forget to pray to God. He will give you a torch of protection against any nightmare.
Narcolepsy: How Is It Contrasting With Insomnia?


text:
Sweden's Spectacular ICEHOTEL Opens For The 29th Season
The Northern Lights provide a spectacular backdrop to the ICEHOTEL (Credit: Asaf Kliger)
While visiting the North Pole in winter may not be at the top of your bucket list, the ever-changing ICEHOTEL, which opened its doors to visitors on December 14 this year, may change your mind. Located 200 km north of the Arctic Circle in the Swedish village of Jukkasjärvi, the hotel, which is carved entirely from ice, is rebuilt annually, with each iteration getting increasingly beautiful and impressive.
The 29-year-old tradition began accidentally in 1989, after Jukkasjärvi residents organized an art show in a 5.5-square-meter (60 square foot) igloo to try to entice tourists to the remote village during the freezing winter months. The exhibition was a huge success, attracting many day visitors. However, it was not until a group of adventurous souls arrived with reindeer hides and sleeping bags, announcing their intention to spend the night inside the igloo, that the idea of the frozen hotel was born.
ICEHOTEL's main lobby (Credit: Asaf Kliger)
The ICEHOTEL has come a long way since its humble beginnings. Constructed from 1000 tons of ice, and 30,000 tons of "snice," – a mixture of ice and snow – it covers an area of over 5,500 square meters (59,200 square feet). The planning begins months earlier in March when about 5,000 tons of ice are harvested from the river and transferred to cold storage, where they sit till the beginning of winter. Construction begins in earnest in November, when about 100 workers, half of them artists invited to carve the hotel's themed suites and common areas, descend upon the region. By December, the unique frozen accommodation is ready to open for business.
Experience camping at the "Spruce Woods" (Credit: Asaf Kliger)
The 35 rooms, built to accommodate visitors on all kinds of budgets, vary from luxurious suites to basic rooms that are furnished with just an icy bed and a reindeer skin. Among the highlights this year is the "Spruce Woods" suite. Sculpted by Christopher Pascoe and Jennie O'Keefe of Canada, it depicts a camping scene complete with a classic VW microbus, a forest, and even a faux campfire.
The "Living Ocean" suite highlights our beautiful marine life (Credit: Asaf Kliger)
There is also the artfully-carved "Living Ocean" suite, to remind visitors of the importance of saving our oceans. The frosty room is teeming with carved marine life that includes coral and an ominous-looking shark "swimming" right over the ice bed. "The suite is inspired by the climate changes and the overfishing that affects our oceans," says artist Jonathan Paul Green. "I also thought the idea of using frozen water from a river in northern Sweden to create an ocean with shells, fish, and corals is exciting."
The nearby "Haven" suite is a "magical portal of ice" guarded by two large animals. "We are inspired by the meeting between people and want to create an experience that invites curiosity, creativity, and collaboration," says artist Jonas Johansson. "It feels like a dream to get to work with ice that allows our love for light, shine, and reflection to wander free from thought to creation."
The Haven, a magical portal of ice (Credit: Asaf Kliger)
The "Icewoman" suite designed by Sweden's Linda Vagnelind, features a massive sculpture of a swimmer, complete with a swim cap. Those with a sweet tooth will be thrilled with the "Candy" suite which allows visitors to experience a night surrounded by a variety of delectable confectionary. Unfortunately, none of the treats are edible. Cat lovers will enjoy the "Tao of Cat" suite, which has a beautifully ice-chiseled face of a feline, right above the frozen bed.
Regardless of whether visitors select the luxury carved suites or the basic ice rooms, the temperature is always set to a bone-chilling -5°C (23°F)! That is why guests are advised to snuggle up inside thermal sleeping bags and wear gloves and winter hats all night. Not surprisingly, most end up spending just a single night at this unique hotel before moving on to the conventional, and warmer, cabins nearby.
A massive sculpture of a swimmer adorns the "Icewoman" suite (Credit: Asaf Kliger)
In addition to the unique rooms, the hotel also offers guests fun activities like snowshoeing, moose or snowmobile safaris, dog sledding, and, for those brave enough to suffer through the below freezing temperatures – overnight wilderness camping! The hotel's single restaurant serves gourmet food, while the drinks are always chilled to perfection in the world-famous ICEBAR!
Those unable to make it to the spectacular hotel before it melts into a giant puddle in April can visit the equally impressive ICEHOTEL 365 that lies adjacent. Though also built entirely from "snice," the 20-room hotel remains frozen, and open, year-round thanks to a solar panel array, which helps keep the heat out during the summer months when the sun never fully sets.
Resources: Icehotel.com, NewAtlas.com,,Standard.co.uk.
Diane Christiansen. "Sweden's Spectacular ICEHOTEL Opens For The 29th Season." DOGOnews, DOGO Media, Inc., 21 Dec, 2018, www.dogonews.com/2018/12/21/swedens-spectacular-icehotel-opens-for-the-29th-season. Accessed 19 Jan. 2020.
Christiansen, Diane. "Sweden's Spectacular ICEHOTEL Opens For The 29th Season." DOGOnews, DOGO Media, Inc., 21 Dec, 2018, Web. 19 Jan. 2020.
Christiansen, D. (2018, December 21). Sweden's Spectacular ICEHOTEL Opens For The 29th Season. Retrieved 2020, January 19, from https://www.dogonews.com/2018/12/21/swedens-spectacular-icehotel-opens-for-the-29th-season
Christiansen, Diane. "Sweden's Spectacular ICEHOTEL Opens For The 29th Season." DOGOnews. December 21, 2018. Accessed January 19, 2020. https://www.dogonews.com/2018/12/21/swedens-spectacular-icehotel-opens-for-the-29th-season.
accommodationadjacentadventurousbucket listcollaborationconfectionaryconventionaldelectabledepictsedibleenticefauxfelinehighlightshumbleintentioniterationluxuriousmassiveominousreflectionremoteteemingthermalwilderness
bellaMonday, November 11, 2019 at 6:07 am
Sooooooooooooo cool
disneylandThursday, October 31, 2019 at 5:01 pm
This is so cool! I am going sweden today!👍
am-olm1Saturday, October 12, 2019 at 12:10 pm
It is so cold!
I am happy that I have been to an ice hotel before!
I love all cold places!
I am happy that I went to an I've hotel before!🥳
Wow! It looks so cool!
chicken friesThursday, October 3, 2019 at 8:43 am
aww i wanna be there
Riley BrookeTuesday, October 1, 2019 at 4:00 pm
I want to go there so badly!!!!!!!!🙊
hivurity-156508646725Wednesday, September 25, 2019 at 1:37 pm
OH. MY. GOSH! I was born in Canada, so for me, this is a life dream to stay there!
Why does the author think you might change your mind about adding the North Pole to your bucket list?
Where is the ICEHOTEL located?
Did the article convince you to add the ICEHOTEL to your bucket list?...
"The 29-year-old tradition began accidentally in 1989, after Jukkasjärvi residents organized an art show in a 5.5-square-meter (60 square foot) igloo to try to entice tourists to the ...


text:
Q: Not able to deselect option in radio button question/answer by clicking button which disable question and radio option Hi I have created a button to grey out the question and there answer.But after greying out I want to deselect the option.I tried using $(this).prop('checked', false); but either I am not doing in correct way or it is not working for me.So you can see in code I have created one survey using JS/HTML with multiple questions/answer and grey out question is not required with NA button but I want answer also decheck if any one selected radio button before clicking NA button.
The code for Disable button is given below:
    $(".btn-na").click(function() {
    let n = $('.answers.disabled').not($(this).closest('.answers')).length
    if (n >= 3) {
      alert('You can only disable 3');
      return
    }
    $(this).closest('.answers').find("input").attr('disabled', !$(this).closest('.answers').find("input").is(":disabled"));
    $(this).closest('.answers').toggleClass('disabled')
  })

Below is code snipped with JS and HTML:

$(document).ready(function() {
  let ctr = 1;
  $('.answers').each(function(index) {
    let i = index + 1
    let html = `
 <input class="form-check-input" type="radio" name="question${i}" id="gridRadios${ctr}" value="1">  Never

 <input class="form-check-input" type="radio" name="question${i}" id="gridRadios${ctr}" value="2"> Rarely

 <input class="form-check-input" type="radio" name="question${i}" id="gridRadios${ctr}" value="3"> Occasionally

 <input class="form-check-input" type="radio" name="question${i}" id="gridRadios${ctr}" value="4"> Often

 <input class="form-check-input" type="radio" name="question${i}" id="gridRadios${ctr}" value="5"> Always

 <input type="button" name="q${i}Remark" value="Remark" onclick="onButtonClick(${i})" /> <input class="hide" type="text" id="textInput${i}" value="" oninput="updateTextBox()" />
Remaining Characters: 100

 <button name="disable${i}" id="na${i}" class='btn-na'>N/A</button>
`
    $(this).html(html);
    ctr++;
  })
  $(".btn-na").click(function() {
    let n = $('.answers.disabled').not($(this).closest('.answers')).length
    if (n >= 3) {
      alert('You can only disable 3');
      return
    }
    $(this).closest('.answers').find("input").attr('disabled', !$(this).closest('.answers').find("input").is(":disabled"));
    $(this).closest('.answers').toggleClass('disabled')
  })
  $('.btnNextS1').click(function() {
    $("div.row1").each(function() {
      $(this).parent().next(".validation").remove()
      if ($(this).has("input:checked").length > 0) {} else {
        $(this).parent().after("
Please Answer this question
");
      }
    })
    if ($("div.row1").filter(function() {
        return $(this).parent().next().hasClass("validation")
      }).length == 0) {
      //e.stopPropagation();
      console.log('valid');
      $('ul.nav-tabs li.nav-item a.active').closest('li').next('li').find('a').trigger('click');
    }
  });
});

 Section 1:

  <fieldset class="form-group">

        <legend id="q1" class="col-form-label col-sm-8 pt-0">1) Question 1</legend>

  </fieldset>
  <fieldset class="form-group">

      <legend id="q2" class="col-form-label col-sm-8 pt-3">2) Question 2</legend>

  </fieldset>
  <fieldset class="form-group">

      <legend id="q3" class="col-form-label col-sm-8 pt-3">3) Question 3</legend>

  </fieldset>
  <fieldset class="form-group">

      <legend id="q4" class="col-form-label col-sm-8 pt-3">4) Question 4</legend>

  </fieldset>
  <fieldset class="form-group">

A: This works fine for me:
$(this).closest('.answers').find("input").prop('checked', false);

$(".btn-na").click(function() {
    let n = $('.answers.disabled').not($(this).closest('.answers')).length
    if (n >= 3) {
      alert('You can only disable 3');
      return
    }
    $(this).closest('.answers').find("input").attr('disabled', !$(this).closest('.answers').find("input").is(":disabled"));
    $(this).closest('.answers').toggleClass('disabled')
  })
  $(document).ready(function() {
  let ctr = 1;
  $('.answers').each(function(index) {
    let i = index + 1
    let html = `
 <input class="form-check-input" type="radio" name="question${i}" id="gridRadios${ctr}" value="1">  Never

 <input class="form-check-input" type="radio" name="question${i}" id="gridRadios${ctr}" value="2"> Rarely

 <input class="form-check-input" type="radio" name="question${i}" id="gridRadios${ctr}" value="3"> Occasionally

 <input class="form-check-input" type="radio" name="question${i}" id="gridRadios${ctr}" value="4"> Often

 <input class="form-check-input" type="radio" name="question${i}" id="gridRadios${ctr}" value="5"> Always

 <input type="button" name="q${i}Remark" value="Remark" onclick="onButtonClick(${i})" /> <input class="hide" type="text" id="textInput${i}" value="" oninput="updateTextBox()" />
Remaining Characters: 100

 <button name="disable${i}" id="na${i}" class='btn-na'>N/A</button>
`
    $(this).html(html);
    ctr++;
  })
  $(".btn-na").click(function() {
    let n = $('.answers.disabled').not($(this).closest('.answers')).length
    if (n >= 3) {
      alert('You can only disable 3');
      return
    }
    $(this).closest('.answers').find("input").prop('checked', false);
    $(this).closest('.answers').find("input").attr('disabled', !$(this).closest('.answers').find("input").is(":disabled"));
    $(this).closest('.answers').toggleClass('disabled')
  })
  $('.btnNextS1').click(function() {
    $("div.row1").each(function() {
      $(this).parent().next(".validation").remove()
      if ($(this).has("input:checked").length > 0) {} else {
        $(this).parent().after("
Please Answer this question
");
      }
    })
    if ($("div.row1").filter(function() {
        return $(this).parent().next().hasClass("validation")
      }).length == 0) {
      //e.stopPropagation();
      console.log('valid');
      $('ul.nav-tabs li.nav-item a.active').closest('li').next('li').find('a').trigger('click');
    }
  });
});

 Section 1:

  <fieldset class="form-group">

        <legend id="q1" class="col-form-label col-sm-8 pt-0">1) Question 1</legend>

  </fieldset>
  <fieldset class="form-group">

      <legend id="q2" class="col-form-label col-sm-8 pt-3">2) Question 2</legend>

  </fieldset>
  <fieldset class="form-group">

      <legend id="q3" class="col-form-label col-sm-8 pt-3">3) Question 3</legend>

  </fieldset>
  <fieldset class="form-group">

      <legend id="q4" class="col-form-label col-sm-8 pt-3">4) Question 4</legend>

  </fieldset>
  <fieldset class="form-group">

redpajama_set_name: RedPajamaStackExchange


The adage that "location is everything" applies to an entire sovereign power. This determines climate, neighbors, and what natural resources are available (and which are not). The form of government will have little to do with location, however, as anything can exist anywhere.
Despite the latter, creators sometimes allow landscape to influence or characterize a power. If we desire this, then mountainous areas are good for an authoritative state and an impregnable fortress or city. An island nation lends itself to being a seafaring power that raids other lands, but it can be democratic or authoritarian. A desert's foreboding landscape can be good for authoritarian states, but then so can an area heavily forested enough that travelers must struggle through the vegetation.
If none of this seems definitive, that's because we can make a case for anything if we characterize it right. When we desire a desert dictatorship, just claim the harsh landscape inspired it. Imagination gets us whatever we want and helps avoid oversimplified clichés. If we've already decided on our government type, we can consider this, or not, when choosing a region to place it in.
Having a map while inventing a sovereign power is advantageous (mapmaking is covered in Chapter 12). This allows us to place the capital somewhere and know where borders, other settlements, and land features are. If we don't have a map yet, then use a piece of paper to sketch regions as ovals marked with the land feature type, like "forest." We can also draw an arrow off the page and indicate an ocean or a dictatorship lies that way. Colored pencils can help; drawing a jagged coastline isn't much help if we can't remember which side the water is on. Use blue for water, green for forests, yellow for desert, and brown for mountains.
Having a sense of the sovereign power's overall disposition (benevolent vs. domineering) can lend ideas for the land features we might like there. This includes how those land features are characterized. A foreboding forest or mountain range might suit one need while a pleasant, coastal savannah with numerous islands offshore might suggest another use. If you have a map, look at it for possible areas to include within the borders and what features might be contested by neighbors. If you don't have a map, you can sketch it using the same mindset.
Decide on the overall territory and where current borders are. Leave room on a map for other sovereign powers, being aware that the more land this one takes, the less there is for everyone else. This is a greater issue if our map already exists and we don't want to alter it. Country boundaries on Earth make little sense to most of us, suggesting we can do as we please, although major rivers often form boundaries, as is the case in the United States with the Mississippi River.


text:
Cookies enable us to provide the best experience possible and help us understand how visitors use our website. By browsing Materials Today, you agree to our use of cookies.
Okay, I understand Learn more
MT PLUS
Computation CHANGE TOPIC
Amorphous materials
Computation and theory
Electronic properties
Optical materials
Polymers and soft materials
Reinforced Plastics
Composite industry
Composite parts
Composite processing
Metal Powder Report
Hardmetals and ceramics
Molding and pressing
Powder applications
Home » Computation and theory » Podcasts » Metamaterials and analog computing
Metamaterials and analog computing
14 April 2014 | Nader Engheta
Interview with: Nader Engheta from the University of Pennsylvania about metamaterials and analog computing.
Stewart Bland:
Please start by introducing yourself and your group, and tell us about your background.
Nader Engheta:
Very good, thank you very much, Stewart, and thank you for your interest in my work, and I appreciate your interest, and it's great to be part of your podcast programme. My name is Nader Engheta, and I'm a professor at the University of Pennsylvania in Philadelphia, and my areas of research interest are on optics, electrodynamics, metamaterials, optical materials, light- matter interaction, in general, physics and engineering of waves. In my group, we are conducting research in a variety of topics related to these fields.
I started actually, my education, in electrical engineering. I did my Batchelor's degree at the University of Tehran in Iran, and I was born in Iran. I grew up there, and went to my college there. I got my Batchelor's degree there, and then I came to the United States for my graduate study, so I went to Cal Tech, and I did my Master's and PhD there, in the area of electrodynamics and electromagnetics. Then, after I got my PhD, I spent one year as a post doc at Cal Tech, and then I started working in a research company, and in those days we were interested in electromagnetic pulses, and the effect of the electromagnetic pulse on materials, and then, after four years in that company, I came to the University of Pennsylvania as the faculty, and since then I've been here, having my group interested in the area of optics and optical materials and metamaterials.
Now, at the beginning, when I started my group at the University of Pennsylvania, we were interested in wave interaction with chiral materials. Inspired by what's going on in the optics of chiral structures, we wanted to see how that would play a role in microwaves, and that got me interested in the fields of wave- matter interactions, and then, over the years, we went to the shorter and shorter wavelengths, and now we're interested in the various aspects of nanophotonics, optics and metamaterial.
By the way, I have another area of research interest, and that is the optical imaging based, or inspired by the biological visual system of eyes of some of the animal species, particularly with regard to polarisation vision.
So that's, in a nutshell, about me, and part of the interest that I have in materials.
Fantastic, thank you. Now, you've recently demonstrated that metamaterials can be designed to perform a kind of analogue computing. So to begin, can you remind us, what is a metamaterial?
Sure, I'd be happy to. Meta, the prefix meta in Greek means beyond, and metamaterials are structures that have unusual, beyond the ordinary effect on waves. We need materials to control and manipulate waves around us. We have light around us, we have waves from radio stations around us. You have waves in your microwave oven. All of these are examples of electromagnetic waves, and we need materials to manipulate them, to interact with them. Of course, in nature there are naturally-available materials, that we all are familiar with that, and usually, if you look at ordinary materials, these materials are made of atoms and molecules, and, for example, if you look at a piece of gold or a piece of silver, these materials consist of gold atoms arranged in a specific pattern. This pattern, and these atoms, of course, give the electromagnetic properties of that particular material.
In metamaterials, however, we're going beyond this natural arrangement, and we're going to another level of organisation, such that we consider collections of tiny structures, or we call it inclusions, which consist of multiple materials, such that these collections of these inclusions together would make the structure behave with the waves in a very different and unusual way. So that's why, you know, when you actually can manipulate and control waves with materials, particularly materials that you can engineer to give you properties that you like to have, that necessarily you might not be able to find in nature, then that makes it interesting to see what we can do with this type of manipulation of waves.
So what is analogue computing, and how does it differ from the digital variety we're more used to?
A good question. So let me start by saying, what are analogue signals and what are digital signals? If you look at the analogue signal, the analogue signal is a signal that changes continuously as a physical quantity. For example, if you consider a continuously varying electric current, or a continuously varying electric voltage, for example, that's an analogue signal. Now a digital signal is a series of discrete values, which in the terminology of electrical engineering, we like to call them zeroes and ones, if you will. These zeroes and ones, in a digital system, can relate only to two values, for example, two values of electric current, or two values of electric voltage. Now, an analogue computer is a computer that works with analogue signals. In other words, there, the quantity that's changing, let's say for example the electric current or electric voltage, changes continuously with time. However, digital computers, the computers that we are all using every day, those work based on the digital signal, based on these zeroes and ones values. So these are basically like two categories of computers, one can think of.
So how do these metamaterials actually perform calculations?
So imagine that you have a block of metamaterial that you designed, in the following way. As the wave enters into this block of metamaterial, let's say with a certain profile, so the wave enters into this structure with a certain profile, as the wave goes through this structure that you designed specifically, by the time the wave comes out, you would like that exiting wave to have a specific profile, such that that profile would be related to the profile of the input wave that's coming through a certain mathematical operation. For example, let's say you have an incoming wave coming at the entrance of your block of metamaterial with a certain profile shape, and you would like, by the time the wave comes out, it would have a shape such that it would be like a derivative of the shape, of the incoming signal to that, or it could be integral of that, or it could be a convolution of that. So that means we need to design materials such that when the wave interacts with these materials, the wave evolves as it goes through it, such that it will give us the profile at the end, which would be based on the mathematical operation we would like that block to do. So essentially it's becoming like a kind of wave-based analogue computing, because remember, as I mentioned, analogue computers are computers that work with the signals that are analogue, in a sense. Here, our idea is that these signals would be waves, would be optical or microwave, depending whatever wavelength you would like to design your metamaterial that would act on that, so it becomes entirely a wave-based type of analogue computing. One might wonder, by the way, one can say what are the advantages and disadvantages of analogue computers versus digital computers. So if you think about, for example, a digital computer, the computer that we use every day, this sort of computers, for example, because of just using zeroes and ones, digital signal, it's more immune to noise. Also, a digital computer is an all-purpose computer – you can programme them. The analogue computer, on the other hand, works with the analogue signal, but they're a specific-purpose computer. They do specific functionality that you design them for. For example, just like what I've mentioned, if you design a set of metamaterials that would give you a specific mathematical operation, like differentiation integration, that falls into the category of analogue computers.
I see, thank you. So what are the potential applications?
calculation, clearly you can see that there would be a variety of applications to consider. One thing that comes to mind is basically, kind of like a very short-term application for this, would be in pattern recognition, would be in image processing. So imagine that, for example, you design these layers of materials, and you would actually send an image at the input of these layers, and you would like, by the time the wave goes through the system and comes out, it will actually give you certain information about that image. For example, something like edge detection, so let's say you have an image, and you would like, by the time it comes out, you'll recognise the edges of the object in that image. That would be quite important from the point of view of pattern recognition, from the point of view of image analysis and image processing. Here, in that case, analogue computers could be more advantageous, because these operations would be able to be done on the entire image basically, at the same time, rather than doing it sequentially, in the sense of scanning. Such a structure will allow us to actually have this type of image analysis all at the same time, as the wave of the image going through it.
So that's one set of applications we are considering, but more of the longer term applications we are considering is the possibility of solving equations using waves in the future. So if, as I mentioned, if one can design a metamaterial slab such that it can do, for example, differentiation on the profile of the wave that's going through. You can think about, okay, if one can do differentiation, or one can do integration, what would be the next step to actually solve the differential equation, or solve an integral equation? So that requires actually connecting this type of structure with some form of optical system, in order that the wave, as it goes through it, it will actually give out the solution to that equation. This could be quite interesting, that just using waves, in the future we'll be able to solve equations. That could be quite important, the variety of different areas of engineering and science.
That's fantastic, thank you. So what's the next step in the project?
Well, the next step is, as you have seen from our paper, by the way, so we introduced the concept, we introduced the ideas, we looked at some of the methods of how to design that, and using our simulation, we showed that this is indeed possible, and has a promising direction. So the next step is to, we are working right now on planning and designing experiments to show the proof of the concept, of such wave-based analogue computing. So in our team, right now we are considering three different scenarios for the proof of the concept experimentation. We are looking at different wavelength regimes. As a possible proof of the concept, we are planning and designing experiments in the microwave, as well as in the optical domain. So this will be our next step, to show the proof of the concept, and then we'll see what are the constraints and what are the design parameters that one needs to take into account, in order to go to the next step of this idea.
Fantastic. So finally, I'd like to finish by asking, as always, in your opinion, what are the other hot topics in materials science right now?
Well, as somebody who is working in the area of metamaterials, and particularly a different frequency regimes of metamaterials, I'm always interested to see what are the various aspects of exciting material properties can be actually linked to metamaterials. One thing, of course, is the area of graphene. As you know, this has been a very, very exciting area. Many groups are interested in aspects of graphene, both from the point of view of electronics, as well as from the photonics aspect of that. So one of the things my group has been interested in is to see, to merge, the concept of metamaterial with the concept of graphene, to consider the possibility of one atom thick metamaterials, and that can open up quite fascinating directions as to how we'll have some of the functionalities that metamaterials currently ... I mean basically, suggesting the possible roadmap, could those possibilities be implemented on the one atom thick structures?
Another hot area, by the way, in materials science, is the topological insulators, as you know, so those provide fascinating possibilities for an electronic system, but also one of the things that we are exploring, and looking at, is to see, is there an interesting connection between topological insulators, and the possibility of bringing that into the field of metamaterials.
Share this podcast
Keystroke dynamics enabled authentication and identification using triboelectric nanogenerator array
Volume 21, Issue 3, Pages 216–222Changsheng Wu, Wenbo Ding, Ruiyuan Liu, Jiyu Wang, Aurelia C.Wang, JieWang, Shengming Li, Yunlong Zi, Zhong Lin Wang
Metal-free metamaterial changes at flick of a switch
Researchers have developed a novel metal-free metamaterial whose optical properties can be changed at the flick of a switch.
Novel 3D printing process goes from nanoscale to macroscale
A new 3D printing process can produce lightweight, strong and super-elastic metallic nanostructured materials with unprecedented scalability.
About Materials Today
Materials Today is a community dedicated to the creation and sharing of materials science knowledge and experience. Supported by Elsevier, we publish high impact peer-reviewed journals, organize academic conferences, broadcast educational webinars and so much more.
We want to hear from you. We're here to support the creation and sharing of information: if there's something we aren't doing, or something we could do better, let us know. We grow through your comments and ideas.
Website designed by Intuitiv