问:
C# ,How to I make bindable string picker?
I'm pretty new to C#, I'm trying to make an app with Xamarin forms. I want a picker, what can choose from ($,£,etc) values. Keep in mind that I'm using SQLite.net. Soo, for learning how to make an app I'm using an example from github. There is a long code for bindablepicker:

```<code>    using System;
using System.Collections;
using System.Collections.Specialized;
using System.Reflection;
using Xamarin.Forms;

namespace TodoScheduler.Controls
{
    public class BindablePicker : Picker
    {
        bool _disableNestedCalls;

        public static readonly BindableProperty PickerTitleProperty =
            BindableProperty.Create("PickerTitle", typeof(string), typeof(BindablePicker),
                null);

        public static readonly BindableProperty ItemsSourceProperty =
            BindableProperty.Create("ItemsSource", typeof(IEnumerable), typeof(BindablePicker),
                null, propertyChanged: OnItemsSourceChanged);

        public static readonly BindableProperty SelectedItemProperty =
            BindableProperty.Create("SelectedItem", typeof(Object), typeof(BindablePicker),
                null, BindingMode.TwoWay, propertyChanged: OnSelectedItemChanged);

        public static readonly BindableProperty SelectedValueProperty =
            BindableProperty.Create("SelectedValue", typeof(Object), typeof(BindablePicker),
                null, BindingMode.TwoWay, propertyChanged: OnSelectedValueChanged);

        public String DisplayMemberPath { get; set; }

        public string PickerTitle
        {
            get { return (string)GetValue(PickerTitleProperty); }
            set { SetValue(PickerTitleProperty, value); }
        }

        public IEnumerable ItemsSource
        {
            get { return (IEnumerable)GetValue(ItemsSourceProperty); }
            set { SetValue(ItemsSourceProperty, value); }
        }

        public object SelectedItem
        {
            get { return GetValue(SelectedItemProperty); }
            set
            {
                if (this.SelectedItem != value)
                {
                    SetValue(SelectedItemProperty, value);
                    InternalSelectedItemChanged();
                }
            }
        }

        public object SelectedValue
        {
            get { return GetValue(SelectedValueProperty); }
            set
            {
                SetValue(SelectedValueProperty, value);
                InternalSelectedValueChanged();
            }
        }

        public string SelectedValuePath { get; set; }

        public BindablePicker()
        {
            this.SelectedIndexChanged += OnSelectedIndexChanged;
        }

        public event EventHandler<SelectedItemChangedEventArgs> ItemSelected;

        void InstanceOnItemsSourceChanged(Object oldValue, Object newValue)
        {
            _disableNestedCalls = true;

            this.Items.Clear();
            var oldCollectionINotifyCollectionChanged = oldValue as INotifyCollectionChanged;
            if (oldCollectionINotifyCollectionChanged != null)
            {
                oldCollectionINotifyCollectionChanged.CollectionChanged -= ItemsSource_CollectionChanged;
            }
            var newCollectionINotifyCollectionChanged = newValue as INotifyCollectionChanged;
            if (newCollectionINotifyCollectionChanged != null)
            {
                newCollectionINotifyCollectionChanged.CollectionChanged += ItemsSource_CollectionChanged;
            }
            if (!Equals(newValue, null))
            {
                var hasDisplayMemberPath = !String.IsNullOrWhiteSpace(this.DisplayMemberPath);
                foreach (var item in (IEnumerable)newValue)
                {
                    if (hasDisplayMemberPath)
                    {
                        var type = item.GetType();
                        var prop = type.GetRuntimeProperty(this.DisplayMemberPath);
                        this.Items.Add(prop.GetValue(item).ToString());
                    }
                    else
                    {
                        this.Items.Add(item.ToString());
                    }
                }

                this.SelectedIndex = -1;  // select first item by default
                this._disableNestedCalls = false;

                if (this.SelectedItem != null)
                {
                    this.InternalSelectedItemChanged();
                }
                else if (hasDisplayMemberPath && this.SelectedValue != null)
                {
                    this.InternalSelectedValueChanged();
                }
            }
            else
            {
                _disableNestedCalls = true;
                this.SelectedIndex = -1;
                this.SelectedItem = null;
                this.SelectedValue = null;
                _disableNestedCalls = false;
            }
        }

        void InternalSelectedItemChanged()
        {
            if (_disableNestedCalls)
            {
                return;
            }

            var selectedIndex = -1;
            Object selectedValue = null;

            if (this.ItemsSource != null)
            {
                var index = 0;

                var hasSelectedValuePath = !String.IsNullOrWhiteSpace(this.SelectedValuePath);

                foreach (var item in ItemsSource)
                {
                    if (item != null && item.Equals(this.SelectedItem))
                    {
                        selectedIndex = index;
                        if (hasSelectedValuePath)
                        {
                            var type = item.GetType();
                            var prop = type.GetRuntimeProperty(this.SelectedValuePath);
                            selectedValue = prop.GetValue(item);
                        }
                        break;
                    }
                    index++;
                }
            }
            _disableNestedCalls = true;
            this.SelectedValue = selectedValue;
            this.SelectedIndex = selectedIndex;
            _disableNestedCalls = false;
        }

        void InternalSelectedValueChanged()
        {
            if (_disableNestedCalls)
            {
                return;
            }

            if (String.IsNullOrWhiteSpace(this.SelectedValuePath))
            {
                return;
            }

            var selectedIndex = -1;

            Object selectedItem = null;

            var hasSelectedValuePath = !String.IsNullOrWhiteSpace(this.SelectedValuePath);

            if (this.ItemsSource != null && hasSelectedValuePath)
            {
                var index = 0;

                foreach (var item in ItemsSource)
                {
                    if (item != null)
                    {
                        var type = item.GetType();
                        var prop = type.GetRuntimeProperty(this.SelectedValuePath);
                        if (Object.Equals(prop.GetValue(item), this.SelectedValue))
                        {
                            selectedIndex = index;
                            selectedItem = item;
                            break;
                        }
                    }
                    index++;
                }
            }
            _disableNestedCalls = true;
            this.SelectedItem = selectedItem;
            this.SelectedIndex = selectedIndex;
            _disableNestedCalls = false;
        }

        void ItemsSource_CollectionChanged(Object sender, NotifyCollectionChangedEventArgs e)
        {
            var hasDisplayMemberPath = !String.IsNullOrWhiteSpace(this.DisplayMemberPath);
            if (e.Action == NotifyCollectionChangedAction.Add)
            {
                foreach (var item in e.NewItems)
                {
                    if (hasDisplayMemberPath)
                    {
                        var type = item.GetType();
                        var prop = type.GetRuntimeProperty(this.DisplayMemberPath);
                        this.Items.Add(prop.GetValue(item).ToString());
                    }
                    else
                    {
                        this.Items.Add(item.ToString());
                    }
                }
            }
            else if (e.Action == NotifyCollectionChangedAction.Remove)
            {
                foreach (var item in e.NewItems)
                {
                    if (hasDisplayMemberPath)
                    {
                        var type = item.GetType();
                        var prop = type.GetRuntimeProperty(this.DisplayMemberPath);
                        this.Items.Remove(prop.GetValue(item).ToString());
                    }
                    else
                    {
                        this.Items.Remove(item.ToString());
                    }
                }
            }
            else if (e.Action == NotifyCollectionChangedAction.Replace)
            {
                foreach (var item in e.NewItems)
                {
                    if (hasDisplayMemberPath)
                    {
                        var type = item.GetType();
                        var prop = type.GetRuntimeProperty(this.DisplayMemberPath);
                        this.Items.Remove(prop.GetValue(item).ToString());
                    }
                    else
                    {
                        var index = this.Items.IndexOf(item.ToString());
                        if (index > -1)
                        {
                            this.Items[index] = item.ToString();
                        }
                    }
                }
            }
            else if (e.Action == NotifyCollectionChangedAction.Reset)
            {
                this.Items.Clear();

                if (e.NewItems != null)
                {
                    foreach (var item in e.NewItems)
                    {
                        if (hasDisplayMemberPath)
                        {
                            var type = item.GetType();
                            var prop = type.GetRuntimeProperty(this.DisplayMemberPath);
                            this.Items.Remove(prop.GetValue(item).ToString());
                        }
                        else
                        {
                            var index = this.Items.IndexOf(item.ToString());
                            if (index > -1)
                            {
                                this.Items[index] = item.ToString();
                            }
                        }
                    }
                }
                else
                {
                    _disableNestedCalls = true;
                    this.SelectedItem = null;
                    this.SelectedIndex = -1;
                    this.SelectedValue = null;
                    _disableNestedCalls = false;

                }
            }
        }

        static void OnItemsSourceChanged(BindableObject bindable, Object oldValue, Object newValue)
        {
            if (Equals(newValue, null) && Equals(oldValue, null))
            {
                return;
            }

            var picker = (BindablePicker)bindable;
            picker.InstanceOnItemsSourceChanged(oldValue, newValue);
        }

        void OnSelectedIndexChanged(Object sender, EventArgs e)
        {
            if (_disableNestedCalls)
            {
                return;
            }

            if (this.SelectedIndex < 0 || this.ItemsSource == null || !this.ItemsSource.GetEnumerator().MoveNext())
            {
                _disableNestedCalls = true;

                if (this.SelectedIndex != -1)
                {
                    //this.SelectedIndex = -1;
                    this.SelectedIndex = 0;
                }

                this.SelectedItem = null;
                this.SelectedValue = null;
                _disableNestedCalls = false;
                return;
            }

            _disableNestedCalls = true;

            var index = 0;
            var hasSelectedValuePath = !String.IsNullOrWhiteSpace(this.SelectedValuePath);

            foreach (var item in ItemsSource)
            {
                if (index == this.SelectedIndex)
                {
                    this.SelectedItem = item;

                    if (hasSelectedValuePath)
                    {
                        var type = item.GetType();
                        var prop = type.GetRuntimeProperty(this.SelectedValuePath);
                        this.SelectedValue = prop.GetValue(item);
                    }

                    break;
                }
                index++;
            }

            _disableNestedCalls = false;
        }

        static void OnSelectedItemChanged(BindableObject bindable, Object oldValue, Object newValue)
        {
            var boundPicker = (BindablePicker)bindable;
            boundPicker.ItemSelected?.Invoke(boundPicker, new SelectedItemChangedEventArgs(newValue));
            boundPicker.InternalSelectedItemChanged();
        }

        static void OnSelectedValueChanged(BindableObject bindable, Object oldValue, Object newValue)
        {
            var boundPicker = (BindablePicker)bindable;
            boundPicker.InternalSelectedValueChanged();
        }
    }
}
</code>```

The form code:

```<code>            <controls:BindablePicker Margin="20,5"
                                                                      ItemsSource="{Binding PriorityList}"
                                 SelectedItem="{Binding Priority, Mode=TwoWay}"
                                 DisplayMemberPath="Title"
                                 Title="Choose"
                                 VerticalOptions="EndAndExpand"/>
</code>```

Model:

```<code>TodoPriority _priority = TodoPriority.Low;
    [NotNull] public TodoPriority Priority {
        get { return _priority; }
        set { SetProperty(ref _priority, value); }
    }
</code>```

ViewModel:

```<code>   TodoPriority _priority = TodoPriority.Low;
    public TodoPriority Priority
    {
        get { return _priority; }
        set { SetProperty(ref _priority, value); }
    }

    IEnumerable<TodoPriority> _priorityList = Enum.GetValues(typeof(TodoPriority)).Cast<TodoPriority>();
    public IEnumerable<TodoPriority> PriorityList
    {
        get { return _priorityList; }
        set { SetProperty(ref _priorityList, value); }
    }
</code>```

TodoPriority:

```<code>    namespace TodoScheduler.Enums
{
    public enum TodoPriority
    {
        Low = 0,
        Normal,
        High
    }
}
</code>```

At the moment I can choose from picker (low,normal,high), but how can I change this? I know I cant change those values from Todopriority to currency token, because its enum. I tried to make them all strings, but then I caught on a problem that how I can make these values. I know its a bit dumb question, but I've search alot and cant figute it out.

答:
You could try to create a class to represent each picker item

```<code>class PriorityPickerValue {

    public string Title { get; set; }
    public TodoPriority Priority { get; set; }

}
</code>```

That way you can specify how your values look in the picker and still have access to the TodoPriority property

Body:
I'm pretty new to C#, I'm trying to make an app with Xamarin forms. I want a picker, what can choose from ($,£,etc) values. Keep in mind that I'm using SQLite.net. Soo, for learning how to make an app I'm using an example from github. There is a long code for bindablepicker:

    using System;
using System.Collections;
using System.Collections.Specialized;
using System.Reflection;
using Xamarin.Forms;

namespace TodoScheduler.Controls
{
    public class BindablePicker : Picker
    {
        bool _disableNestedCalls;

        public static readonly BindableProperty PickerTitleProperty =
            BindableProperty.Create("PickerTitle", typeof(string), typeof(BindablePicker),
                null);

        public static readonly BindableProperty ItemsSourceProperty =
            BindableProperty.Create("ItemsSource", typeof(IEnumerable), typeof(BindablePicker),
                null, propertyChanged: OnItemsSourceChanged);

        public static readonly BindableProperty SelectedItemProperty =
            BindableProperty.Create("SelectedItem", typeof(Object), typeof(BindablePicker),
                null, BindingMode.TwoWay, propertyChanged: OnSelectedItemChanged);

        public static readonly BindableProperty SelectedValueProperty =
            BindableProperty.Create("SelectedValue", typeof(Object), typeof(BindablePicker),
                null, BindingMode.TwoWay, propertyChanged: OnSelectedValueChanged);

        public String DisplayMemberPath { get; set; }

        public string PickerTitle
        {
            get { return (string)GetValue(PickerTitleProperty); }
            set { SetValue(PickerTitleProperty, value); }
        }

        public IEnumerable ItemsSource
        {
            get { return (IEnumerable)GetValue(ItemsSourceProperty); }
            set { SetValue(ItemsSourceProperty, value); }
        }

        public object SelectedItem
        {
            get { return GetValue(SelectedItemProperty); }
            set
            {
                if (this.SelectedItem != value)
                {
                    SetValue(SelectedItemProperty, value);
                    InternalSelectedItemChanged();
                }
            }
        }

        public object SelectedValue
        {
            get { return GetValue(SelectedValueProperty); }
            set
            {
                SetValue(SelectedValueProperty, value);
                InternalSelectedValueChanged();
            }
        }

        public string SelectedValuePath { get; set; }

        public BindablePicker()
        {
            this.SelectedIndexChanged += OnSelectedIndexChanged;
        }

        public event EventHandler<SelectedItemChangedEventArgs> ItemSelected;

        void InstanceOnItemsSourceChanged(Object oldValue, Object newValue)
        {
            _disableNestedCalls = true;

            this.Items.Clear();
            var oldCollectionINotifyCollectionChanged = oldValue as INotifyCollectionChanged;
            if (oldCollectionINotifyCollectionChanged != null)
            {
                oldCollectionINotifyCollectionChanged.CollectionChanged -= ItemsSource_CollectionChanged;
            }
            var newCollectionINotifyCollectionChanged = newValue as INotifyCollectionChanged;
            if (newCollectionINotifyCollectionChanged != null)
            {
                newCollectionINotifyCollectionChanged.CollectionChanged += ItemsSource_CollectionChanged;
            }
            if (!Equals(newValue, null))
            {
                var hasDisplayMemberPath = !String.IsNullOrWhiteSpace(this.DisplayMemberPath);
                foreach (var item in (IEnumerable)newValue)
                {
                    if (hasDisplayMemberPath)
                    {
                        var type = item.GetType();
                        var prop = type.GetRuntimeProperty(this.DisplayMemberPath);
                        this.Items.Add(prop.GetValue(item).ToString());
                    }
                    else
                    {
                        this.Items.Add(item.ToString());
                    }
                }

                this.SelectedIndex = -1;  // select first item by default
                this._disableNestedCalls = false;

                if (this.SelectedItem != null)
                {
                    this.InternalSelectedItemChanged();
                }
                else if (hasDisplayMemberPath && this.SelectedValue != null)
                {
                    this.InternalSelectedValueChanged();
                }
            }
            else
            {
                _disableNestedCalls = true;
                this.SelectedIndex = -1;
                this.SelectedItem = null;
                this.SelectedValue = null;
                _disableNestedCalls = false;
            }
        }

        void InternalSelectedItemChanged()
        {
            if (_disableNestedCalls)
            {
                return;
            }

            var selectedIndex = -1;
            Object selectedValue = null;

            if (this.ItemsSource != null)
            {
                var index = 0;

                var hasSelectedValuePath = !String.IsNullOrWhiteSpace(this.SelectedValuePath);

                foreach (var item in ItemsSource)
                {
                    if (item != null && item.Equals(this.SelectedItem))
                    {
                        selectedIndex = index;
                        if (hasSelectedValuePath)
                        {
                            var type = item.GetType();
                            var prop = type.GetRuntimeProperty(this.SelectedValuePath);
                            selectedValue = prop.GetValue(item);
                        }
                        break;
                    }
                    index++;
                }
            }
            _disableNestedCalls = true;
            this.SelectedValue = selectedValue;
            this.SelectedIndex = selectedIndex;
            _disableNestedCalls = false;
        }

        void InternalSelectedValueChanged()
        {
            if (_disableNestedCalls)
            {
                return;
            }

            if (String.IsNullOrWhiteSpace(this.SelectedValuePath))
            {
                return;
            }

            var selectedIndex = -1;

            Object selectedItem = null;

            var hasSelectedValuePath = !String.IsNullOrWhiteSpace(this.SelectedValuePath);

            if (this.ItemsSource != null && hasSelectedValuePath)
            {
                var index = 0;

                foreach (var item in ItemsSource)
                {
                    if (item != null)
                    {
                        var type = item.GetType();
                        var prop = type.GetRuntimeProperty(this.SelectedValuePath);
                        if (Object.Equals(prop.GetValue(item), this.SelectedValue))
                        {
                            selectedIndex = index;
                            selectedItem = item;
                            break;
                        }
                    }
                    index++;
                }
            }
            _disableNestedCalls = true;
            this.SelectedItem = selectedItem;
            this.SelectedIndex = selectedIndex;
            _disableNestedCalls = false;
        }

        void ItemsSource_CollectionChanged(Object sender, NotifyCollectionChangedEventArgs e)
        {
            var hasDisplayMemberPath = !String.IsNullOrWhiteSpace(this.DisplayMemberPath);
            if (e.Action == NotifyCollectionChangedAction.Add)
            {
                foreach (var item in e.NewItems)
                {
                    if (hasDisplayMemberPath)
                    {
                        var type = item.GetType();
                        var prop = type.GetRuntimeProperty(this.DisplayMemberPath);
                        this.Items.Add(prop.GetValue(item).ToString());
                    }
                    else
                    {
                        this.Items.Add(item.ToString());
                    }
                }
            }
            else if (e.Action == NotifyCollectionChangedAction.Remove)
            {
                foreach (var item in e.NewItems)
                {
                    if (hasDisplayMemberPath)
                    {
                        var type = item.GetType();
                        var prop = type.GetRuntimeProperty(this.DisplayMemberPath);
                        this.Items.Remove(prop.GetValue(item).ToString());
                    }
                    else
                    {
                        this.Items.Remove(item.ToString());
                    }
                }
            }
            else if (e.Action == NotifyCollectionChangedAction.Replace)
            {
                foreach (var item in e.NewItems)
                {
                    if (hasDisplayMemberPath)
                    {
                        var type = item.GetType();
                        var prop = type.GetRuntimeProperty(this.DisplayMemberPath);
                        this.Items.Remove(prop.GetValue(item).ToString());
                    }
                    else
                    {
                        var index = this.Items.IndexOf(item.ToString());
                        if (index > -1)
                        {
                            this.Items[index] = item.ToString();
                        }
                    }
                }
            }
            else if (e.Action == NotifyCollectionChangedAction.Reset)
            {
                this.Items.Clear();

                if (e.NewItems != null)
                {
                    foreach (var item in e.NewItems)
                    {
                        if (hasDisplayMemberPath)
                        {
                            var type = item.GetType();
                            var prop = type.GetRuntimeProperty(this.DisplayMemberPath);
                            this.Items.Remove(prop.GetValue(item).ToString());
                        }
                        else
                        {
                            var index = this.Items.IndexOf(item.ToString());
                            if (index > -1)
                            {
                                this.Items[index] = item.ToString();
                            }
                        }
                    }
                }
                else
                {
                    _disableNestedCalls = true;
                    this.SelectedItem = null;
                    this.SelectedIndex = -1;
                    this.SelectedValue = null;
                    _disableNestedCalls = false;

                }
            }
        }

        static void OnItemsSourceChanged(BindableObject bindable, Object oldValue, Object newValue)
        {
            if (Equals(newValue, null) && Equals(oldValue, null))
            {
                return;
            }

            var picker = (BindablePicker)bindable;
            picker.InstanceOnItemsSourceChanged(oldValue, newValue);
        }

        void OnSelectedIndexChanged(Object sender, EventArgs e)
        {
            if (_disableNestedCalls)
            {
                return;
            }

            if (this.SelectedIndex < 0 || this.ItemsSource == null || !this.ItemsSource.GetEnumerator().MoveNext())
            {
                _disableNestedCalls = true;

                if (this.SelectedIndex != -1)
                {
                    //this.SelectedIndex = -1;
                    this.SelectedIndex = 0;
                }

                this.SelectedItem = null;
                this.SelectedValue = null;
                _disableNestedCalls = false;
                return;
            }

            _disableNestedCalls = true;

            var index = 0;
            var hasSelectedValuePath = !String.IsNullOrWhiteSpace(this.SelectedValuePath);

            foreach (var item in ItemsSource)
            {
                if (index == this.SelectedIndex)
                {
                    this.SelectedItem = item;

                    if (hasSelectedValuePath)
                    {
                        var type = item.GetType();
                        var prop = type.GetRuntimeProperty(this.SelectedValuePath);
                        this.SelectedValue = prop.GetValue(item);
                    }

                    break;
                }
                index++;
            }

            _disableNestedCalls = false;
        }

        static void OnSelectedItemChanged(BindableObject bindable, Object oldValue, Object newValue)
        {
            var boundPicker = (BindablePicker)bindable;
            boundPicker.ItemSelected?.Invoke(boundPicker, new SelectedItemChangedEventArgs(newValue));
            boundPicker.InternalSelectedItemChanged();
        }

        static void OnSelectedValueChanged(BindableObject bindable, Object oldValue, Object newValue)
        {
            var boundPicker = (BindablePicker)bindable;
            boundPicker.InternalSelectedValueChanged();
        }
    }
}

The form code:

            <controls:BindablePicker Margin="20,5"
                                                                      ItemsSource="{Binding PriorityList}"
                                 SelectedItem="{Binding Priority, Mode=TwoWay}"
                                 DisplayMemberPath="Title"
                                 Title="Choose"
                                 VerticalOptions="EndAndExpand"/>

Model:

TodoPriority _priority = TodoPriority.Low;
    [NotNull] public TodoPriority Priority {
        get { return _priority; }
        set { SetProperty(ref _priority, value); }
    }

ViewModel:

   TodoPriority _priority = TodoPriority.Low;
    public TodoPriority Priority
    {
        get { return _priority; }
        set { SetProperty(ref _priority, value); }
    }

    IEnumerable<TodoPriority> _priorityList = Enum.GetValues(typeof(TodoPriority)).Cast<TodoPriority>();
    public IEnumerable<TodoPriority> PriorityList
    {
        get { return _priorityList; }
        set { SetProperty(ref _priorityList, value); }
    }

TodoPriority:

    namespace TodoScheduler.Enums
{
    public enum TodoPriority
    {
        Low = 0,
        Normal,
        High
    }
}

At the moment I can choose from picker (low,normal,high), but how can I change this? I know I cant change those values from Todopriority to currency token, because its enum. I tried to make them all strings, but then I caught on a problem that how I can make these values. I know its a bit dumb question, but I've search alot and cant figute it out.

Body:
You could try to create a class to represent each picker item

class PriorityPickerValue {

    public string Title { get; set; }
    public TodoPriority Priority { get; set; }

}

That way you can specify how your values look in the picker and still have access to the TodoPriority property


来源: stackexchange

问:
How to validate inserted items in AJAX Combobox against database?
I wonder how to validate if a inserted item in a Combobox exists in a database during postback? If the item.text exists, a errormessage should notify the user that the item already exists in the database. If the item does not exists in the database a inserting should be done.

Should i use the customvalidator and create a servervalidationfunction that searches my databasetable for the item name?

Should i validate inside one of the two ComboBox control events, ItemInserting and ItemInserted?

After validating the existence i would like to validate if the inserting to the database was successfull.

答: So you're going to hit your database to check whether an item already exists and then if it doesn't, deem the item valid, and then hit your database again to insert the new item? I suggest you simply try to insert the item via say a stored procedure and have the stored procedure check whether the item already exists in your table. Your stored procedure can then return a result which your web application can digest (i.e. whether the item already existed versus successful/failed insertion). This way you only hit the database once.</p>

ContentLicense: CC BY-SA 2.5


问:
How to manage fragments in backstack?
I am trying to manage fragments in a very simple way. I have created a utility class that's adding fragments to the backstack and when we press the back button, the previous fragment shows up. I am OK with that. But, when I am trying to clear out all the fragments, and show up the root fragment, I am not able to do so properly. Following is my utility class:

```<code>public class FragmentUtil {
private FragmentUtil() {
}

public static void animatedReplace(FragmentActivity activity, int containerId, Fragment fragment, Bundle args, boolean addToBackStack){
    FragmentTransaction transaction=activity.getSupportFragmentManager().beginTransaction();
    fragment.setArguments(args);
    if(addToBackStack){
        transaction.addToBackStack(fragment.getClass().getName());
    }
    transaction.setCustomAnimations(R.anim.slide_from_right, R.anim.slide_to_left,R.anim.slide_from_left,R.anim.slide_to_right);
    transaction.replace(containerId,fragment);
    transaction.commit();
}

public static void clearBackStackToHome(FragmentActivity activity){
    FragmentManager manager = activity.getSupportFragmentManager();
    manager.popBackStack(DashboardFragment.class.getName(),FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
}
</code>```

When I want to another fragment I just pass "true" for addToStack in animatedReplace method. When I want to clear the backstack I pass "false" and call the clearBackStackToHome method. Can anybody help me what I am doing wrong?

答: make a condition where check backStack is empty or not. when all fragments are removed from backStack then show your root fragment </p>

ContentLicense: CC BY-SA 3.0

Title: How to manage fragments in backstack?

Body:
I am trying to manage fragments in a very simple way. I have created a utility class that's adding fragments to the backstack and when we press the back button, the previous fragment shows up. I am OK with that. But, when I am trying to clear out all the fragments, and show up the root fragment, I am not able to do so properly. Following is my utility class:

public class FragmentUtil {
private FragmentUtil() {
}

public static void animatedReplace(FragmentActivity activity, int containerId, Fragment fragment, Bundle args, boolean addToBackStack){
    FragmentTransaction transaction=activity.getSupportFragmentManager().beginTransaction();
    fragment.setArguments(args);
    if(addToBackStack){
        transaction.addToBackStack(fragment.getClass().getName());
    }
    transaction.setCustomAnimations(R.anim.slide_from_right, R.anim.slide_to_left,R.anim.slide_from_left,R.anim.slide_to_right);
    transaction.replace(containerId,fragment);
    transaction.commit();
}

public static void clearBackStackToHome(FragmentActivity activity){
    FragmentManager manager = activity.getSupportFragmentManager();
    manager.popBackStack(DashboardFragment.class.getName(),FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
}

When I want to another fragment I just pass "true" for addToStack in animatedReplace method. When I want to clear the backstack I pass "false" and call the clearBackStackToHome method. Can anybody help me what I am doing wrong?


问:
Python TypeError in list
I'm making anagram in python
but when I call 'list'function, it doesn't work. please help.
I'm tring to change 'str' to 'list'
but it doesn't work. I really don't know why

```<code>def generate_anagram(s):
    a=s[0:len(s)-1]
    b=s[len(s)-1]
    if len(a)==1:
        return make(a,b)
    else:
        return make(generate_anagram(a),b)

def make(s1,s2):
    list=[]
    l=len(s1)
    q=list(s1)
    w=list(s2)
    ss=""
    for i in range(l):
        if(len(q)>l):
            q.remove(w)
        q.insert(i,w)
        list+=q

    for i in range(len(list)):
        ss+=list[i]
    return ss

if __name__ == "__main__":

    print(generate_anagram("anagram"))
</code>```

答:
The code

```<code>list=[]
l=len(s1)
q=list(s1)
w=list(s2)
</code>```

is problematic because the first line will "hide" the standard function list by creating a local variable named list. This means the last two lines are not calling the list function of Python.

Title: Python TypeError in list

Body:
I'm making anagram in python
but when I call 'list'function, it doesn't work. please help.
I'm tring to change 'str' to 'list'
but it doesn't work. I really don't know why

def generate_anagram(s):
    a=s[0:len(s)-1]
    b=s[len(s)-1]
    if len(a)==1:
        return make(a,b)
    else:
        return make(generate_anagram(a),b)

def make(s1,s2):
    list=[]
    l=len(s1)
    q=list(s1)
    w=list(s2)
    ss=""
    for i in range(l):
        if(len(q)>l):
            q.remove(w)
        q.insert(i,w)
        list+=q

    for i in range(len(list)):
        ss+=list[i]
    return ss

if __name__ == "__main__":

    print(generate_anagram("anagram"))

Body:
The code

list=[]
l=len(s1)
q=list(s1)
w=list(s2)

is problematic because the first line will "hide" the standard function list by creating a local variable named list. This means the last two lines are not calling the list function of Python.


问:
Setting maxlag for ADF test with python statsmodels not working?
I've tried setting the maxlag with the ADF test in statsmodels but the number of lags being used by the test is not what I set it as. It is almost always less. Here's a small example of what I mean.

```<code>import numpy as np
import statsmodels.tsa.stattools as ts

x = np.array([1,2,3,4,3,4,2,3])
result = ts.adfuller(x, 1) # maxlag is now set to 1

>>> result
(-2.6825663173365015, 0.077103947319183241, 0, 7, {'5%': -3.4775828571428571, '1%': -4.9386902332361515, '10%': -2.8438679591836733}, 15.971188911270618)
</code>```

The maxlag is set to one, but in the result it says the max lags used is 0 corresponding to the third entry in result.

Can anyone explain why this is happening and possibly how to fix this?

答:
The maxlag parameter is the maximum parameter adfuller will try, but not necessarily use. If none is specified it determines the maxpar by computing [ceil(12*(n/100)^(1/4))], so that for longer data sets it assumes that higher order lags could be present (n is amount of observations here).

It then uses an information criterion to decide which lag gives the best model. An information criterion tries the balance the goodness of fit while minimizing the complexity of the model. You can specify which algorithm should be used to determine which model is the best by using the autolag parameter of the adfuller function. The default is Akaike information criterion.

If you would want to force the model to use the specified 'maxlag', you should turn off the determination of the best model by using autolag=None. Are you sure you want to do this?

Body:
I've tried setting the maxlag with the ADF test in statsmodels but the number of lags being used by the test is not what I set it as. It is almost always less. Here's a small example of what I mean.

import numpy as np
import statsmodels.tsa.stattools as ts

x = np.array([1,2,3,4,3,4,2,3])
result = ts.adfuller(x, 1) # maxlag is now set to 1

>>> result
(-2.6825663173365015, 0.077103947319183241, 0, 7, {'5%': -3.4775828571428571, '1%': -4.9386902332361515, '10%': -2.8438679591836733}, 15.971188911270618)

The maxlag is set to one, but in the result it says the max lags used is 0 corresponding to the third entry in result.

Can anyone explain why this is happening and possibly how to fix this?


问:
HTTP request doesn't fire off
I am new to Angluar and was following a video tutorial to make HTTP Request and getting the response data. For some reason the code I used doesn't fire off the http.get.</p>

```<code>import { Component, Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

@Injectable()
export class AppComponent {

  constructor( private http: Http ){
    console.log('Until here works');
    this.http.get('https://jsonplaceholder.typicode.com/posts').map(data => {
      console.log('Finished');
      console.log( data );
    });
  }

}
</code>```

答:
You have to make use of Services instead of Directly using it in Components as Services are meant to be Reusable using Angular Dependency Injection.
If you are new i would suggest you to go through services once as these are integral part of an angular application.

I have a Repo that deals with Some Basic Angular Concepts and Services are one of them Please check it out hope it helps , i have a life example too for the same in gh-pages.

https://github.com/rahulrsingh09/AngularConcepts

https://rahulrsingh09.github.io/AngularConcepts

Title: HTTP request doesn't fire off

Body:
I am new to Angluar and was following a video tutorial to make HTTP Request and getting the response data. For some reason the code I used doesn't fire off the http.get.

import { Component, Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

@Injectable()
export class AppComponent {

  constructor( private http: Http ){
    console.log('Until here works');
    this.http.get('https://jsonplaceholder.typicode.com/posts').map(data => {
      console.log('Finished');
      console.log( data );
    });
  }

}


问:
How to dynamically change the color of a country on d3 map

var COLOR = 'blue';
var map = new Datamap({
  element: document.getElementById('map'),
  responsive: false,
});

function changeColor(countryCode) {
  map.updateChoropleth({
    countryCode: COLOR
  });
}

setInterval(function() {
  changeColor('USA');
}, 2000);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/topojson/1.6.9/topojson.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/datamaps/0.5.8/datamaps.world.min.js"></script>
<div id="map"></div></code>```

I have the following javascript which renders a world map on HTML.

```<code>var map = new Datamap({
  element: document.getElementById('map'),
  responsive: true,
});

function changeColor(countryCode) {
  map.updateChoropleth({
    countryCode: 'blue'
  });
  console.log(countryCode + '--> colorChange');
}

setInterval(function() {
  changeColor('USA');
}, 2000);
</code>```

I want to update the color of a particular country after a 2s. When I run the above code, the function changeColor is called after every 2s, but the function map.updateChoropleth does not seem to have any effect. In case, I change the following snippet:

```<code>function changeColor(countryCode) {
  map.updateChoropleth({
    countryCode: 'blue'
  });
  console.log(countryCode + '--> colorChange');
}
</code>```

to

```<code>function changeColor(countryCode) {
  map.updateChoropleth({
    "USA": 'blue'
  });
  console.log(countryCode + '--> colorChange');
}
</code>```

the function works as expected. Why does this not work?

答:
The updateChoropleth function is looking for a property key literally named countryCode.

A solution is populating an object and passing it to the function:

var COLOR = 'blue';
var map = new Datamap({
  element: document.getElementById('map'),
  responsive: false,
});

function changeColor(countryCode) {
  var obj = {};
  obj[countryCode] = COLOR;
  map.updateChoropleth(obj);
}

setInterval(function() {
  changeColor('USA');
}, 2000);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/topojson/1.6.9/topojson.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/datamaps/0.5.8/datamaps.world.min.js"></script>
<div id="map"></div></code>```

Body:
var COLOR = 'blue';
var map = new Datamap({
  element: document.getElementById('map'),
  responsive: false,
});

function changeColor(countryCode) {
  map.updateChoropleth({
    countryCode: COLOR
  });
}

setInterval(function() {
  changeColor('USA');
}, 2000);

I have the following javascript which renders a world map on HTML.

var map = new Datamap({
  element: document.getElementById('map'),
  responsive: true,
});

function changeColor(countryCode) {
  map.updateChoropleth({
    countryCode: 'blue'
  });
  console.log(countryCode + '--> colorChange');
}

setInterval(function() {
  changeColor('USA');
}, 2000);

I want to update the color of a particular country after a 2s. When I run the above code, the function changeColor is called after every 2s, but the function map.updateChoropleth does not seem to have any effect. In case, I change the following snippet:

function changeColor(countryCode) {
  map.updateChoropleth({
    countryCode: 'blue'
  });
  console.log(countryCode + '--> colorChange');
}

to

function changeColor(countryCode) {
  map.updateChoropleth({
    "USA": 'blue'
  });
  console.log(countryCode + '--> colorChange');
}

the function works as expected. Why does this not work?

Body:
The updateChoropleth function is looking for a property key literally named countryCode.

A solution is populating an object and passing it to the function:

var COLOR = 'blue';
var map = new Datamap({
  element: document.getElementById('map'),
  responsive: false,
});

function changeColor(countryCode) {
  var obj = {};
  obj[countryCode] = COLOR;
  map.updateChoropleth(obj);
}

setInterval(function() {
  changeColor('USA');
}, 2000);

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/topojson/1.6.9/topojson.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/datamaps/0.5.8/datamaps.world.min.js"></script>
<div id="map"></div>


问:
How to remove a null value from NSDictionary
I have a JSON Feed:

```<code>{
    "count1" = 2;
    "count2" = 2;
    idval = 40;
    level = "<null>";
    "logo_url" = "/assets/logos/default_logo_medium.png";
    name = "Golf Club";
    "role_in_club" = Admin;
}
</code>```

The problem is the "<null>". I cannot figure out how to remove it from the NSDictionary before saving it to NSUserDefaults.

答:
the following code is ok when the result is in array or dictionary , you can change the result returned to  nil or empty string by editing the code

the function is recursive  , so can parse array in dictionary .

```<code>-(id)changeNull:(id)sender{

    id newObj;

    if ([sender isKindOfClass:[NSArray class]]){

        NSMutableArray *newArray = [[NSMutableArray alloc] init];

        for (id item in sender){

            [newArray addObject:[self changeNull:item]];

        }

        newObj = newArray;
    }

    else if ([sender isKindOfClass:[NSDictionary class]]){

        NSMutableDictionary *newDict = [[NSMutableDictionary alloc] init];

        for (NSString *key in sender){

            NSDictionary *oldDict = (NSDictionary*)sender;

            id item = oldDict[key];

            if (![item isKindOfClass:[NSDictionary class]] && ![item isKindOfClass:[NSArray class]]){

                if ([item isEqual:[NSNull null]]){
                    item = @"";

                }

                [newDict setValue:item forKey:key];

            }
            else{

                [newDict setValue:[self changeNull:item] forKey:key];

            }
        }
        newObj = newDict;
    }

    return newObj;
}
</code>```

resulting in:

```<code>jsonresult (
    {
        Description = "<null>";
        Id = 1;
        Name = High;
    },
        {
        Description = "<null>";
        Id = 2;
        Name = Medium;
    },
        {
        Description = "<null>";
        Id = 3;
        Name = Low;
    }
)

change null (
    {
        Description = "";
        Id = 1;
        Name = High;
    },
        {
        Description = "";
        Id = 2;
        Name = Medium;
    },
        {
        Description = "";
        Id = 3;
        Name = Low;
    }
)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a JSON Feed:

{
    "count1" = 2;
    "count2" = 2;
    idval = 40;
    level = "<null>";
    "logo_url" = "/assets/logos/default_logo_medium.png";
    name = "Golf Club";
    "role_in_club" = Admin;
}

The problem is the "<null>". I cannot figure out how to remove it from the NSDictionary before saving it to NSUserDefaults.

Body:
the following code is ok when the result is in array or dictionary , you can change the result returned to  nil or empty string by editing the code

the function is recursive  , so can parse array in dictionary .

-(id)changeNull:(id)sender{

    id newObj;

    if ([sender isKindOfClass:[NSArray class]]){

        NSMutableArray *newArray = [[NSMutableArray alloc] init];

        for (id item in sender){

            [newArray addObject:[self changeNull:item]];

        }

        newObj = newArray;
    }

    else if ([sender isKindOfClass:[NSDictionary class]]){

        NSMutableDictionary *newDict = [[NSMutableDictionary alloc] init];

        for (NSString *key in sender){

            NSDictionary *oldDict = (NSDictionary*)sender;

            id item = oldDict[key];

            if (![item isKindOfClass:[NSDictionary class]] && ![item isKindOfClass:[NSArray class]]){

                if ([item isEqual:[NSNull null]]){
                    item = @"";

                }

                [newDict setValue:item forKey:key];

            }
            else{

                [newDict setValue:[self changeNull:item] forKey:key];

            }
        }
        newObj = newDict;
    }

    return newObj;
}

resulting in:

jsonresult (
    {
        Description = "<null>";
        Id = 1;
        Name = High;
    },
        {
        Description = "<null>";
        Id = 2;
        Name = Medium;
    },
        {
        Description = "<null>";
        Id = 3;
        Name = Low;
    }
)

change null (
    {
        Description = "";
        Id = 1;
        Name = High;
    },
        {
        Description = "";
        Id = 2;
        Name = Medium;
    },
        {
        Description = "";
        Id = 3;
        Name = Low;
    }
)


问:
How to find out encapsulated protocol inside IEEE802.11 Frame?
I'm developing a IEEE802.11 frame parser program using libpcap inside Linux with raw C. I can parse RadioTap and IEEE802.11 headers easily but I can't find out the protocol name which is encapsulated inside the IEEE802.11 MPDU. Unfortunatly there isn't any field in IEEE802.11 header indicating the encapsulated protocol (like protocol field in Ethernet header).

Any solution?

答:
Data of IEEE802.11 data packets is encapsulated in a LLC header (See here):

An 802.11 frame should contain an LLC header if, and only if, it's a
  Data frame. The frame type and subtype are part of the Frame Control
  field in the MAC header; Data is one of the frame type values (the
  others are Control and Management). The subtype doesn't matter - all
  Data frames should contain an LLC header, and no other frames should.

There are two kinds of LLC header: 3 bytes, 8 bytes . IEEE 802.11 uses the second one (See here). In that one, the two last bytes of LLC header is equivalent to Ether Type field in Ethernet protocol. So 0x800 for this field means IPv4 for example.


问:
jQuery - Issues with combining selectors in a single event handler
This is regarding Patrick DW's comment on my answer to this question.

Multiple selectors: identify the triggering one?

My Answer:

Using $(this) will get you the element that was clicked..  and using is() can help you determine what was clicked.

```<code>$('a.button, span.xyz, a.another').click(function(e) {
   if ($(this).is("a.button")) {
     alert("a.button was clicked");
   } else if ($(this).is("span.xyz")) {
     alert("span.xyz was clicked");
   } else if($(this).is("a.another")) {
     alert("a.another was clicked);
   }
});
</code>```

Patrick's Comments

Trouble with this is that it is effectively combining the inefficiency that .delegate() suffers (testing against a selector) with the inefficiency of assigning multiple redundant handlers. So you get the worst of both worlds.

@John - Yes, it would make more sense to break them up into separate handlers, and place any common functionality they share into a named function that can be called from within the handlers. This eliminates the need to run the .is() tests at every event occurrence, which can be costly. It can sometimes be beneficial to test for the element that was clicked. This is what .delegate() does. You suffer the expense of the test, but gain from the reduced number of handlers being assigned

Could someone explain (in detail) the inefficiencies that Patrick is talking about? Why is .is() costly in this scenario? Can you give an example as well using .delegate()

答:
Using jQuery's .delegate() method suffers a performance hit because every time the event occurs inside the element with the delegate handler, a similar test needs to take place to determine which element received the event.

This is often worthwhile because by using .delegate() you are (presumably) avoiding the need to assign individual handlers to every element.

With the code above, you have the overhead of assigning multiple handlers, and you are still running the code that needs to test to see which received the event.

Hard to say if .delegate() is the appropriate choice for the question you referenced, but it would be much better to assign individual handlers, and avoid the if( $(this).is('something') ) tests.

If the purpose of the original OP's code was to have individual functionality for each element type, but still have them share some subset of common functionality, it would be better to roll that common functionality into its own named function and call it. This is a much more efficient approach.

EDIT:

Take this example. Let's say the span.target and p.anothertaget elements are to get handlers. As you can see, there are a number of elements in the container.

Using selectors to assign a .click(), you end up with several separate event handlers.

```<code>$('span.target').click(function() { /* do something with span */ });
$('p.anothertarget').click(function() { /* do something with p */ });
</code>```

html

```<code><div id='container'>
    <span class='target'>click me</span>             <!-- i get a handler -->
    <div>i don't do anything</div>
    <p class='anothertarget'>i get a click too</p>   <!-- i get a handler -->
    <span class='target'>click me</span>             <!-- i get a handler -->
    <div>i don't do anything</div>
    <p class='anothertarget'>i get a click too</p>   <!-- i get a handler -->
    <span class='target'>click me</span>             <!-- i get a handler -->
    <div>i don't do anything</div>
    <p class='anothertarget'>i get a click too</p>   <!-- i get a handler -->
    <span class='target'>click me</span>             <!-- i get a handler -->
</div>
</code>```

This means that jQuery needs to manage individual handers for all of these elements. This is the downside. The upside is that you don't need to run a selector to see what received the event. It will always be represented by this (assuming you used separate functions for the p and the span.

Using .delegate(), you assign a handler only to the container. This is done for each type of element that should trigger an event.

As you can see, there are only two handlers assigned. One for the
 element, and the other for the . This obviously reduces the quantity of handlers needed. But the expense is that jQuery needs to run the selectors that you passed to .delegate() for each event that occurs inside container to see which type of element actually received the event.

So there's some give and take.

```<code>$('#container').delegate('span.target','click',function() { /* do something with span */ });
               .delegate('p.anothertarget','click',function() { /* do something with p */ });
</code>```

html

```<code><div id='container'>   <!-- i get a handler for the span.target -->
                       <!--             and for p.anothertarget -->
    <span class='target'>click me</span>
    <div>i don't do anything</div>
    <p class='anothertarget'>i get a click too</p>
    <span class='target'>click me</span>
    <div>i don't do anything</div>
    <p class='anothertarget'>i get a click too</p>
    <span class='target'>click me</span>
    <div>i don't do anything</div>
    <p class='anothertarget'>i get a click too</p>
    <span class='target'>click me</span>
</div>
</code>```

The trouble with the code in your previous answer was that it was effectively combining the inefficiency of the first example (many handlers being assigned) with the inefficiency of the second example (running a selector). That's what I meant by the worst of both worlds.

Body:
This is regarding Patrick DW's comment on my answer to this question.

Multiple selectors: identify the triggering one?

My Answer:

Using $(this) will get you the element that was clicked..  and using is() can help you determine what was clicked.

$('a.button, span.xyz, a.another').click(function(e) {
   if ($(this).is("a.button")) {
     alert("a.button was clicked");
   } else if ($(this).is("span.xyz")) {
     alert("span.xyz was clicked");
   } else if($(this).is("a.another")) {
     alert("a.another was clicked);
   }
});

Patrick's Comments

Trouble with this is that it is effectively combining the inefficiency that .delegate() suffers (testing against a selector) with the inefficiency of assigning multiple redundant handlers. So you get the worst of both worlds.

@John - Yes, it would make more sense to break them up into separate handlers, and place any common functionality they share into a named function that can be called from within the handlers. This eliminates the need to run the .is() tests at every event occurrence, which can be costly. It can sometimes be beneficial to test for the element that was clicked. This is what .delegate() does. You suffer the expense of the test, but gain from the reduced number of handlers being assigned

Could someone explain (in detail) the inefficiencies that Patrick is talking about? Why is .is() costly in this scenario? Can you give an example as well using .delegate()

Body:
Using jQuery's .delegate() method suffers a performance hit because every time the event occurs inside the element with the delegate handler, a similar test needs to take place to determine which element received the event.

This is often worthwhile because by using .delegate() you are (presumably) avoiding the need to assign individual handlers to every element.

With the code above, you have the overhead of assigning multiple handlers, and you are still running the code that needs to test to see which received the event.

Hard to say if .delegate() is the appropriate choice for the question you referenced, but it would be much better to assign individual handlers, and avoid the if( $(this).is('something') ) tests.

If the purpose of the original OP's code was to have individual functionality for each element type, but still have them share some subset of common functionality, it would be better to roll that common functionality into its own named function and call it. This is a much more efficient approach.

EDIT:

Take this example. Let's say the span.target and p.anothertaget elements are to get handlers. As you can see, there are a number of elements in the container.

Using selectors to assign a .click(), you end up with several separate event handlers.

$('span.target').click(function() { /* do something with span */ });
$('p.anothertarget').click(function() { /* do something with p */ });

html

<div id='container'>
    <span class='target'>click me</span>             <!-- i get a handler -->
    <div>i don't do anything</div>
    <p class='anothertarget'>i get a click too</p>   <!-- i get a handler -->
    <span class='target'>click me</span>             <!-- i get a handler -->
    <div>i don't do anything</div>
    <p class='anothertarget'>i get a click too</p>   <!-- i get a handler -->
    <span class='target'>click me</span>             <!-- i get a handler -->
    <div>i don't do anything</div>
    <p class='anothertarget'>i get a click too</p>   <!-- i get a handler -->
    <span class='target'>click me</span>             <!-- i get a handler -->
</div>

This means that jQuery needs to manage individual handers for all of these elements. This is the downside. The upside is that you don't need to run a selector to see what received the event. It will always be represented by this (assuming you used separate functions for the p and the span.

Using .delegate(), you assign a handler only to the container. This is done for each type of element that should trigger an event.

As you can see, there are only two handlers assigned. One for the <p> element, and the other for the <span>. This obviously reduces the quantity of handlers needed. But the expense is that jQuery needs to run the selectors that you passed to .delegate() for each event that occurs inside container to see which type of element actually received the event.

So there's some give and take.

$('#container').delegate('span.target','click',function() { /* do something with span */ });
               .delegate('p.anothertarget','click',function() { /* do something with p */ });

html

<div id='container'>   <!-- i get a handler for the span.target -->
                       <!--             and for p.anothertarget -->
    <span class='target'>click me</span>
    <div>i don't do anything</div>
    <p class='anothertarget'>i get a click too</p>
    <span class='target'>click me</span>
    <div>i don't do anything</div>
    <p class='anothertarget'>i get a click too</p>
    <span class='target'>click me</span>
    <div>i don't do anything</div>
    <p class='anothertarget'>i get a click too</p>
    <span class='target'>click me</span>
</div>

The trouble with the code in your previous answer was that it was effectively combining the inefficiency of the first example (many handlers being assigned) with the inefficiency of the second example (running a selector). That's what I meant by the worst of both worlds.


问:
Protecting a Subdomain with htaccess
I have my own server and do everything on my end as much as possible for a gaming community (in order to keep overhead down).  This includes hosting the website myself with WAMP and Windows 10. Let's say I have a domain. I'm using a REST server for .. stuff. I need to provide access to the REST server via a Web Control Panel that uses a chunk of complicated PHP and Javascript noise to work. The only way to run it is through the server (obviously) which means it needs it's own virtual host to operate (I think. It doesn't work if I just use PHP Include). So I created a subdomain (rest.domain.com) and plugged that into the src for an iframe that I put on a webpage that is password protected. The only problem I'm facing right now is that anyone can go to rest.domain.com and go right around the paltry Wordpress security and mess about with my stuff.

I'm open to either

Blocking direct URL access and including some fancy code so only the iFrame can get to it.

Passwording the SubDomain and just giving my REST users the rest.domain.com url.

Something entirely different that I didn't know existed.

What should I do?

EDIT:1

So, we've gotten to the point where we're using an .htaccess file to restrict the subdomain with a login/password.  I've created the .htaccess file in the directory of the REST files and created an .htpasswd file.

I am now receiving 500ISE errors.
I have gone down through 3 Google Search pages trying to research the issue and have made dozens of edits to my .htaccess file to make it work.  Without the htaccess, the REST server can be accessed without restriction.  The error is in the .htaccess file.  Here is what my .htaccess file looks like upon giving up on this for the evening:

Messing around with this for hours and have gone down 3 Google Pages, opening and researching every single hit (most are on SO) and still stuck on a 500 Internal Server Error.  This is where I'm sitting at right now with my htaccess file and this is where I'm giving up for the night:

```<code>AuthType Basic
AuthName "Locked"
AuthUserFile o:\..\..\..\..\.htpasswd
Require valid-user

SetEnvIf Host rest.domain.com !secure_content

Order Allow,Deny
Allow env secure_content
Deny From All

Satisfy Any
</code>```

EDIT:1.1

So, instead of giving up (because I ain't no quitta!) I've started noticing a trend from a few other sites that using a far less complicated .htaccess than the "instructional" I originally found.  I went ahead and commented out the following lines:

```<code>#SetEnvIf Host rest.radio-takeover.com !secure_content

#Order Allow,Deny
#Allow env secure_content
#Deny From All

#Satisfy Any
</code>```

It now appears to be working as intended.  Thank you, Jenny, for somewhat pointing me down the right path.

答: iframe source page can easily be protected through php redirection. In that way if a user is logged in iframe will show. Direct access to the iframe will show forbidden. Also Check laravel middleware authcheck and role and permissions..</p>

Title: Protecting a Subdomain with htaccess

Body:
I have my own server and do everything on my end as much as possible for a gaming community (in order to keep overhead down).  This includes hosting the website myself with WAMP and Windows 10. Let's say I have a domain. I'm using a REST server for .. stuff. I need to provide access to the REST server via a Web Control Panel that uses a chunk of complicated PHP and Javascript noise to work. The only way to run it is through the server (obviously) which means it needs it's own virtual host to operate (I think. It doesn't work if I just use PHP Include). So I created a subdomain (rest.domain.com) and plugged that into the src for an iframe that I put on a webpage that is password protected. The only problem I'm facing right now is that anyone can go to rest.domain.com and go right around the paltry Wordpress security and mess about with my stuff.

I'm open to either

Blocking direct URL access and including some fancy code so only the iFrame can get to it.

Passwording the SubDomain and just giving my REST users the rest.domain.com url.

Something entirely different that I didn't know existed.

What should I do?

EDIT:1

So, we've gotten to the point where we're using an .htaccess file to restrict the subdomain with a login/password.  I've created the .htaccess file in the directory of the REST files and created an .htpasswd file.

I am now receiving 500ISE errors.
I have gone down through 3 Google Search pages trying to research the issue and have made dozens of edits to my .htaccess file to make it work.  Without the htaccess, the REST server can be accessed without restriction.  The error is in the .htaccess file.  Here is what my .htaccess file looks like upon giving up on this for the evening:

Messing around with this for hours and have gone down 3 Google Pages, opening and researching every single hit (most are on SO) and still stuck on a 500 Internal Server Error.  This is where I'm sitting at right now with my htaccess file and this is where I'm giving up for the night:

AuthType Basic
AuthName "Locked"
AuthUserFile o:\..\..\..\..\.htpasswd
Require valid-user

SetEnvIf Host rest.domain.com !secure_content

Order Allow,Deny
Allow env secure_content
Deny From All

Satisfy Any

EDIT:1.1

So, instead of giving up (because I ain't no quitta!) I've started noticing a trend from a few other sites that using a far less complicated .htaccess than the "instructional" I originally found.  I went ahead and commented out the following lines:

#SetEnvIf Host rest.radio-takeover.com !secure_content

#Order Allow,Deny
#Allow env secure_content
#Deny From All

#Satisfy Any

It now appears to be working as intended.  Thank you, Jenny, for somewhat pointing me down the right path.


问:
how to avoid unsupported formats in audio player
I am creating an audio player and i am using this code to get all the songs

```<code>String[] STAR = {"*"};

    Cursor cursor;
    Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
    String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";

      File file;

    cursor =context.getContentResolver().query(uri, STAR, selection, null, null);

    if (cursor != null) {

        if (cursor.moveToFirst()) {
            int i = 0;
            do {

                String songName = cursor
                        .getString(cursor
                                .getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME));

                path[i] = cursor.getString(cursor
                        .getColumnIndex(MediaStore.Audio.Media.DATA));

                String albumName = cursor.getString(cursor
                        .getColumnIndex(MediaStore.Audio.Media.ALBUM));
                albumId[i] = cursor
                        .getInt(cursor
                                .getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));

                String artist= cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
                String albumname= cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM));
                artistId[i]=cursor.getInt(cursor
                                .getColumnIndex(MediaStore.Audio.Media.ARTIST_ID));

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

This gets me the songs but i get audio of unsupported formats too. such as .wav any idea how to avoid unsupported formats

答:
You can use MimeType to do this. See below example code how it is done for mp3.

```<code>ContentResolver contentResolver = context.getContentResolver();
Uri uri = MediaStore.Files.getContentUri("external");
String[] projection = null;
String sortOrder = null;
String selectionMimeType = MediaStore.Files.FileColumns.MIME_TYPE + "=?";
String mimeType = imeTypeMap.getSingleton().getMimeTypeFromExtension("mp3");
String[] selectionArgsMp3 = new String[]{ mimeType };
Cursor mp3Songs = contentResolver.query(uri, projection,selectionMimeType,selectionArgsmp3, sortOrder);
</code>```

Another approach it that you can check is there any compatible application installed on device using below code while opening/playing application.

```<code>private void openRelevantFileHandler(String pathToMusicFile)
{
    String extension = MimeTypeMap.getFileExtensionFromUrl(pathToMusicFile);
    String type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);

    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_VIEW);
    intent.setDataAndType(Uri.parse("file://" + pathToMusicFile), type);

    PackageManager packageManager = context.getPackageManager();
    List activities = packageManager.queryIntentActivities(intent, PackageManager.MATCH_ALL);
    boolean isIntentSafe = activities.size() > 0;
    if (!isIntentSafe) {
        Utility.showToast(context, "No application available on your device to open this type of file.");
    }
    else
    {
        context.startActivity(intent);//Start related application
    }
}
</code>```

Hope this will help you in some way :)

Body:
I am creating an audio player and i am using this code to get all the songs

String[] STAR = {"*"};

    Cursor cursor;
    Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
    String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";

      File file;

    cursor =context.getContentResolver().query(uri, STAR, selection, null, null);

    if (cursor != null) {

        if (cursor.moveToFirst()) {
            int i = 0;
            do {

                String songName = cursor
                        .getString(cursor
                                .getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME));

                path[i] = cursor.getString(cursor
                        .getColumnIndex(MediaStore.Audio.Media.DATA));

                String albumName = cursor.getString(cursor
                        .getColumnIndex(MediaStore.Audio.Media.ALBUM));
                albumId[i] = cursor
                        .getInt(cursor
                                .getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));

                String artist= cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
                String albumname= cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM));
                artistId[i]=cursor.getInt(cursor
                                .getColumnIndex(MediaStore.Audio.Media.ARTIST_ID));

        }cursor.close();

This gets me the songs but i get audio of unsupported formats too. such as .wav any idea how to avoid unsupported formats

Body:
You can use MimeType to do this. See below example code how it is done for mp3.

ContentResolver contentResolver = context.getContentResolver();
Uri uri = MediaStore.Files.getContentUri("external");
String[] projection = null;
String sortOrder = null;
String selectionMimeType = MediaStore.Files.FileColumns.MIME_TYPE + "=?";
String mimeType = imeTypeMap.getSingleton().getMimeTypeFromExtension("mp3");
String[] selectionArgsMp3 = new String[]{ mimeType };
Cursor mp3Songs = contentResolver.query(uri, projection,selectionMimeType,selectionArgsmp3, sortOrder);

Another approach it that you can check is there any compatible application installed on device using below code while opening/playing application.

private void openRelevantFileHandler(String pathToMusicFile)
{
    String extension = MimeTypeMap.getFileExtensionFromUrl(pathToMusicFile);
    String type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);

    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_VIEW);
    intent.setDataAndType(Uri.parse("file://" + pathToMusicFile), type);

    PackageManager packageManager = context.getPackageManager();
    List activities = packageManager.queryIntentActivities(intent, PackageManager.MATCH_ALL);
    boolean isIntentSafe = activities.size() > 0;
    if (!isIntentSafe) {
        Utility.showToast(context, "No application available on your device to open this type of file.");
    }
    else
    {
        context.startActivity(intent);//Start related application
    }
}

Hope this will help you in some way :)


问:
how to compute the dynamic price of items in cart and output the total
When a user add items to its cart it will be hold on my temporary database table user_cart and there will be an output of the item in the cart page which the user will see their items in their cart. so the php code i used is while loop to output the items. how to compute all the item price and output it on the total section?</p>

```<code><table class="table table-hover">
    <thead>
        <tr>
            <th>Product</th>
            <th>Quantity</th>
            <th class="text-center">Price</th>
            <th class="text-center">Total</th>
            <th> </th>
        </tr>
    </thead>
    <tbody>
        <tr>
        <?php
            $count = 1;
            $cart_query = "Select * from user_cart where email = '$email'";
            $cart_res = mysqli_query($con,$cart_query);
            while($cart_row = mysqli_fetch_assoc($cart_res)) {
        ?>
            <td class="col-sm-8 col-md-6">
            <div class="media">
                <a class="thumbnail pull-left" href="#"> <?php
                $image_count = 1;
                $product_name = stripslashes($cart_row["product_name"]);
                $image_query = "Select * from tbl_products where item_category = 'Laptop' AND item_name = '$product_name'";
                $image_res = mysqli_query($con,$image_query);
                while($row = mysqli_fetch_assoc($image_res)){
                $imageData = $row["images"];
                echo '<img src ="data:image/jpeg;base64,'.base64_encode($imageData).'"class="img-responsive" style = "width:100px; height:80px;"/>';?>
                <?php $count++; } ?>
                </a>
                <div class="media-body">
                 <h4 class="media-heading"><a href="#"><?php echo stripslashes($cart_row["product_name"]);?></a></h4>
                <h5 class="media-heading"> by <a href="#"><?php echo $cart_row["brand"];?></a></h5>
                <span>Status: </span>
                <span class="text-success">
                <strong><?php echo $cart_row["item_available"];?></strong>
                </span>
                </div>
            </div></td>
            <td class="col-sm-1 col-md-1" style="text-align: center">
                <input type="email" class="form-control" id="exampleInputEmail1" value="<?php echo $cart_row["quantity"];?>">
            </td>
            <td class="col-sm-1 col-md-1 text-center">
            <strong><?php echo $cart_row["item_price"];?></strong></td>
            <td class="col-sm-1 col-md-1 text-center" id = "item_total_price">
            <strong><?php echo $cart_row["item_total_price"];?></strong></td>
            <td class="col-sm-1 col-md-1">
            <form action  = "functions/delete.php" method = "post">
            <button type="submit" class="btn btn-danger">
             <input type = "hidden" value = "<?php echo $cart_row['cart_id'];?>" name = "cart_id">
            <span class="glyphicon glyphicon-remove"></span> Remove
            </button></td>
            </form>
            </tr>
            <?php $count++; } ?>
            <tr>
            <td>   </td>
            <td>   </td>
            <td>   </td>
            <td><h5>Subtotal</h5></td>
            <td class="text-right" id = "sub_total">
            <h5><strong></strong></h5></td>
            </tr>
            <tr>
            <td>   </td>
            <td>   </td>
            <td>   </td>
            <td><h3>Total</h3></td>
            <td class="text-right">
              <h3><strong>$31.53</strong></h3>
            </td></tr>
            <tr>
            <td>   </td>
            <td>   </td>
            <td>   </td>
            <td>
            <button type="button" class="btn btn-default">
            <span class="glyphicon glyphicon-shopping-cart">
            </span> Continue Shopping</button></td>
            <td>
            <button type="button" class="btn btn-success">
                Checkout <span class="glyphicon glyphicon-play"></span>
            </button></td>
            </tr>
            </tbody>
            </table>
</code>```

答: take the trouble to add to cart when calculating the total price and record in a table,another is a SQL calculation : "select sum('goos_price') * buys_count as total_price from your_table";if use php :$total_price  = 0;foreach($cart_data as $key=>$val){ $total_price = $val['goos_price'] * $val['buys_count'];}</p>

Body:
When a user add items to its cart it will be hold on my temporary database table user_cart and there will be an output of the item in the cart page which the user will see their items in their cart. so the php code i used is while loop to output the items. how to compute all the item price and output it on the total section?

            Product
            Quantity
            Price
            Total

        <?php
            $count = 1;
            $cart_query = "Select * from user_cart where email = '$email'";
            $cart_res = mysqli_query($con,$cart_query);
            while($cart_row = mysqli_fetch_assoc($cart_res)) {
        ?>

                 <?php
                $image_count = 1;
                $product_name = stripslashes($cart_row["product_name"]);
                $image_query = "Select * from tbl_products where item_category = 'Laptop' AND item_name = '$product_name'";
                $image_res = mysqli_query($con,$image_query);
                while($row = mysqli_fetch_assoc($image_res)){
                $imageData = $row["images"];
                echo '';?>
                <?php $count++; } ?>

<?php echo stripslashes($cart_row["product_name"]);?>

 by <?php echo $cart_row["brand"];?>

                Status:

                <?php echo $cart_row["item_available"];?>

                <input type="email" class="form-control" id="exampleInputEmail1" value="<?php echo $cart_row["quantity"];?>">

            <?php echo $cart_row["item_price"];?>

            <?php echo $cart_row["item_total_price"];?>

            <form action  = "functions/delete.php" method = "post">
            <button type="submit" class="btn btn-danger">
             <input type = "hidden" value = "<?php echo $cart_row['cart_id'];?>" name = "cart_id">
             Remove
            </button>
            </form>

            <?php $count++; } ?>

Subtotal

Total

$31.53

            <button type="button" class="btn btn-default">

             Continue Shopping</button>

            <button type="button" class="btn btn-success">
                Checkout
            </button>


问:
How to add a space between images in a CSS image slideshow?
EDIT:

Good progress... By updating the following code, I almost get exactly what I want to achieve, but I don't understand exactly why it almost works. Spacing both sides during transition, spacing hidden after transition, but with a slight amount of clipping of image: https://codepen.io/anon/pen/LWqPJB

```<code>body {
     margin: -6%;
}
div#slider {
     overflow: hidden;
}
div#slider figure img {
     width: 18%;
     float: left;
     padding-left: 1%;
     padding-right: 1%;
}
</code>```

Although, it's not a perfect solution, the second alternative that seems to do the job is:

```<code>div#slider {
    margin-left: -6%;
    margin-right: -6%;
    overflow: hidden;
}
div#slider figure img {
    width: 18%;
    margin-left: 1%;
    margin-right: 1%;
    float: left;
}
</code>```

Problem

I'm implementing a simple image slideshow in a webpage using only HTML and CSS. The code I am starting with is below and at https://codepen.io/anon/pen/wJRVwP

Currently each slide follows the next with no space between images (image 1). However, I'm trying to add a 100px space between each image that is only visible during the transition. So attempting to add a gap, I change the CSS code below;

from:

```<code>div#slider figure img { width: 20%; float: left;}
</code>```

(demo 1: https://codepen.io/anon/pen/wJRVwP)

to:

```<code>div#slider figure img { width: 20%; float: left; padding-left: 100px;}
</code>```

(demo 2: https://codepen.io/anon/pen/vxvoNy)

The result of changing the code adds a 100px space between all images, but, the code change introduces a new problem — images no longer align and progressively get worse after each slide change (image 2).

Question

How can I achieve a space between images and fix this? In code, how
  can I change the CSS code to add a 100px space between each image, and keep
  all images aligned during and after transition?

Images

demo 1 during transition.

demo 1 after transition.

required outcome.

Code

https://codepen.io/anon/pen/wJRVwP

@keyframes slidy {
  0% {
    left: 0%;
  }
  20% {
    left: 0%;
  }
  25% {
    left: -100%;
  }
  45% {
    left: -100%;
  }
  50% {
    left: -200%;
  }
  70% {
    left: -200%;
  }
  75% {
    left: -300%;
  }
  95% {
    left: -300%;
  }
  100% {
    left: -400%;
  }
}

body {
  margin: 0;
}

div#slider {
  overflow: hidden;
}

div#slider figure img {
  width: 20%;
  float: left;
}

div#slider figure {
  position: relative;
  width: 500%;
  margin: 0;
  left: 0;
  text-align: left;
  font-size: 0;
  animation: 20s slidy infinite;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><base href="https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/">
<div id="slider">
  <figure>
    <img src="austin-fireworks.jpg" alt>
    <img src="taj-mahal_copy.jpg" alt>
    <img src="austin-fireworks.jpg" alt>
    <img src="ankor-wat.jpg" alt>
    <img src="austin-fireworks.jpg" alt>
  </figure>
</div></code>```

Body:
EDIT:

Good progress... By updating the following code, I almost get exactly what I want to achieve, but I don't understand exactly why it almost works. Spacing both sides during transition, spacing hidden after transition, but with a slight amount of clipping of image: https://codepen.io/anon/pen/LWqPJB

body {
     margin: -6%;
}
div#slider {
     overflow: hidden;
}
div#slider figure img {
     width: 18%;
     float: left;
     padding-left: 1%;
     padding-right: 1%;
}

Although, it's not a perfect solution, the second alternative that seems to do the job is:

div#slider {
    margin-left: -6%;
    margin-right: -6%;
    overflow: hidden;
}
div#slider figure img {
    width: 18%;
    margin-left: 1%;
    margin-right: 1%;
    float: left;
}

Problem

I'm implementing a simple image slideshow in a webpage using only HTML and CSS. The code I am starting with is below and at https://codepen.io/anon/pen/wJRVwP

Currently each slide follows the next with no space between images (image 1). However, I'm trying to add a 100px space between each image that is only visible during the transition. So attempting to add a gap, I change the CSS code below;

from:

div#slider figure img { width: 20%; float: left;}

(demo 1: https://codepen.io/anon/pen/wJRVwP)

to:

div#slider figure img { width: 20%; float: left; padding-left: 100px;}

(demo 2: https://codepen.io/anon/pen/vxvoNy)

The result of changing the code adds a 100px space between all images, but, the code change introduces a new problem — images no longer align and progressively get worse after each slide change (image 2).

Question

How can I achieve a space between images and fix this? In code, how
  can I change the CSS code to add a 100px space between each image, and keep
  all images aligned during and after transition?

Images

demo 1 during transition.

demo 1 after transition.

required outcome.

Code

https://codepen.io/anon/pen/wJRVwP

@keyframes slidy {
  0% {
    left: 0%;
  }
  20% {
    left: 0%;
  }
  25% {
    left: -100%;
  }
  45% {
    left: -100%;
  }
  50% {
    left: -200%;
  }
  70% {
    left: -200%;
  }
  75% {
    left: -300%;
  }
  95% {
    left: -300%;
  }
  100% {
    left: -400%;
  }
}

body {
  margin: 0;
}

div#slider {
  overflow: hidden;
}

div#slider figure img {
  width: 20%;
  float: left;
}

div#slider figure {
  position: relative;
  width: 500%;
  margin: 0;
  left: 0;
  text-align: left;
  font-size: 0;
  animation: 20s slidy infinite;
}

<base href="https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/">

Body:
Change the CSS like below:
@keyframes slidy {
    0% { left: 0%;}
    20% { left: 0%; }
    25% { left: -100%;}
    45% { left: -100%; }
    50% { left: -200%; margin-left: 100px;}
    70% { left: -200%; }
    75% { left: -300%; }
    95% { left: -300%; }
    100% { left: -400%; margin-left: 0px;}
}


问:
How to play a sound continuously without break?
I am trying to play a vehicle driven sound in a browser based game (continuously without break).

My .wav file length is 1 second and has same frequency from beginning to end. But sound takes a little break before next iteration.

Here is code:

```<code>function playSound()
{
    //alert("");
    myAudio = new Audio('http://ithmbwp.com/feedback/SoundsTest/sounds/tank_driven.wav');
    if (typeof myAudio.loop == 'boolean')
    {
        myAudio.loop = true;
    }
    else
    {
        myAudio.addEventListener('ended', function() {
            this.currentTime = 0;
            this.play();
        }, false);
    }
    myAudio.volume = 0.3;
    myAudio.play();
}
</code>```

Can anyone help me to play the sound continuously?

Edition

You can visit my page here to observe the problem.

window.onload = function() {
  playSound();
};

function playSound()
{
 //alert("");
 myAudio = new Audio('http://ithmbwp.com/feedback/SoundsTest/sounds/tank_driven.wav');
 if (typeof myAudio.loop == 'boolean')
 {
  myAudio.loop = true;
 }
 else
 {
  myAudio.addEventListener('ended', function() {
   this.currentTime = 0;
   this.play();
  }, false);
 }
 myAudio.volume = 0.3;
 myAudio.play();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h3 style="font-family:verdana;">Please listen the sound break.</h3>
<h3 style="font-family:verdana;">It should be continuous.</h3></code>```

答:
Bee Cool, just use few lines code

window.onload = function() {
  playSound();
};

function playSound()
{
var myAudio = new Audio('http://ithmbwp.com/feedback/SoundsTest/sounds/tank_driven.wav');

myAudio.volume = 0.3 ;

var tank_driven_sound = setInterval(function()
{
 myAudio.currentTime = 0;
 myAudio.play();
}, 800);

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h3 style="font-family:verdana;">Please listen, it's continuous.</h3></code>```

Body:
I am trying to play a vehicle driven sound in a browser based game (continuously without break).

My .wav file length is 1 second and has same frequency from beginning to end. But sound takes a little break before next iteration.

Here is code:

function playSound()
{
    //alert("");
    myAudio = new Audio('http://ithmbwp.com/feedback/SoundsTest/sounds/tank_driven.wav');
    if (typeof myAudio.loop == 'boolean')
    {
        myAudio.loop = true;
    }
    else
    {
        myAudio.addEventListener('ended', function() {
            this.currentTime = 0;
            this.play();
        }, false);
    }
    myAudio.volume = 0.3;
    myAudio.play();
}

Can anyone help me to play the sound continuously?

Edition

You can visit my page here to observe the problem.

window.onload = function() {
  playSound();
};

function playSound()
{
 //alert("");
 myAudio = new Audio('http://ithmbwp.com/feedback/SoundsTest/sounds/tank_driven.wav');
 if (typeof myAudio.loop == 'boolean')
 {
  myAudio.loop = true;
 }
 else
 {
  myAudio.addEventListener('ended', function() {
   this.currentTime = 0;
   this.play();
  }, false);
 }
 myAudio.volume = 0.3;
 myAudio.play();
}

Please listen the sound break.

It should be continuous.

Body:
Bee Cool, just use few lines code

window.onload = function() {
  playSound();
};

function playSound()
{
var myAudio = new Audio('http://ithmbwp.com/feedback/SoundsTest/sounds/tank_driven.wav');

myAudio.volume = 0.3 ;

var tank_driven_sound = setInterval(function()
{
 myAudio.currentTime = 0;
 myAudio.play();
}, 800);

}

<h3 style="font-family:verdana;">Please listen, it's continuous.</h3>


问:
File was loaded in the wrong encoding:'UTF-8' in IntelliJ IDEA
Before asking the question, I searched for a similar question on StackOverflow:

file was loaded in the wrong encoding: 'UTF-8' in android studio

But it did not give an explicit answer there.

My issue is that the project is downloaded from the network, and it is an eclipse project, I open it with IntelliJ IDEA, and get this issue:

答: As Tarik point out, click the Reload in another encoding, and if you want UTF-8 encoding, then click the more -> UTF-8.


问:
Styling jQuery Validation with Select2 4.0 and Bootstrap 3+
I have a project that uses Bootstrap 3.3.4, Select2 4.0, and Jquery Validation 1.13.1

I have set the jquery validator defaults to style bootstrap 3 classes like so

```<code> $.validator.setDefaults({
    errorElement: "span",
    errorClass: "help-block",

    highlight: function (element, errorClass, validClass) {
    $(element).addClass(errorClass);
        $(element).closest('.form-group').removeClass('has-success').addClass('has-error');
    },
    unhighlight: function (element, errorClass, validClass) {
    $(element).removeClass(errorClass);
        $(element).closest('.form-group').removeClass('has-error').addClass('has-success');
    },

    errorPlacement: function(error, element) {
        if(element.parent('.input-group').length) {
           error.insertAfter(element.parent());
        } else {
            error.insertAfter(element);
        }

    }
});
</code>```

But these defaults do not style select2 fields the same... in the image below, the "metals" select is a bootstrap field, while the "colors" select is a select2 field.

I tried searching other SO's , but all of these use the 3.5.xx version of select2

I included a jsfiddle of the example pictured, I am looking for adjustments to the validator defaults to have select2 look uniform

http://jsfiddle.net/z49mb6wr/

答:
A small modification to @Sparky's solution - I don't take the credit except for figuring out that error and valid classes are used by latest jquery validate(:P) as on date:

```<code>/*! jQuery Validation Plugin - v1.16.0 - 12/2/2016
 * http://jqueryvalidation.org/
 * Copyright (c) 2016 Jörn Zaefferer; Licensed MIT */
</code>```

Now code:

```<code>$('#MyForm').validate({
    errorPlacement: function (error, element) {
        if (element.parent('.input-group').length) {
            error.insertAfter(element.parent());      // radio/checkbox?
        } else if (element.hasClass('select2-hidden-accessible')) {
            error.insertAfter(element.next('span'));  // select2
            element.next('span').addClass('error').removeClass('valid');
        } else {
            error.insertAfter(element);               // default
        }
    }
});

// add valid and remove error classes on select2 element if valid
$('.select2-hidden-accessible').on('change', function() {
    if($(this).valid()) {
        $(this).next('span').removeClass('error').addClass('valid');
    }
});
</code>```

Use CSS on error class as it pleases you.

Body:
I have a project that uses Bootstrap 3.3.4, Select2 4.0, and Jquery Validation 1.13.1

I have set the jquery validator defaults to style bootstrap 3 classes like so

 $.validator.setDefaults({
    errorElement: "span",
    errorClass: "help-block",

    highlight: function (element, errorClass, validClass) {
    $(element).addClass(errorClass);
        $(element).closest('.form-group').removeClass('has-success').addClass('has-error');
    },
    unhighlight: function (element, errorClass, validClass) {
    $(element).removeClass(errorClass);
        $(element).closest('.form-group').removeClass('has-error').addClass('has-success');
    },

    errorPlacement: function(error, element) {
        if(element.parent('.input-group').length) {
           error.insertAfter(element.parent());
        } else {
            error.insertAfter(element);
        }

    }
});

But these defaults do not style select2 fields the same... in the image below, the "metals" select is a bootstrap field, while the "colors" select is a select2 field.

I tried searching other SO's , but all of these use the 3.5.xx version of select2

I included a jsfiddle of the example pictured, I am looking for adjustments to the validator defaults to have select2 look uniform

http://jsfiddle.net/z49mb6wr/

Body:
A small modification to @Sparky's solution - I don't take the credit except for figuring out that error and valid classes are used by latest jquery validate(:P) as on date:

/*! jQuery Validation Plugin - v1.16.0 - 12/2/2016
 * http://jqueryvalidation.org/
 * Copyright (c) 2016 Jörn Zaefferer; Licensed MIT */

Now code:

$('#MyForm').validate({
    errorPlacement: function (error, element) {
        if (element.parent('.input-group').length) {
            error.insertAfter(element.parent());      // radio/checkbox?
        } else if (element.hasClass('select2-hidden-accessible')) {
            error.insertAfter(element.next('span'));  // select2
            element.next('span').addClass('error').removeClass('valid');
        } else {
            error.insertAfter(element);               // default
        }
    }
});

// add valid and remove error classes on select2 element if valid
$('.select2-hidden-accessible').on('change', function() {
    if($(this).valid()) {
        $(this).next('span').removeClass('error').addClass('valid');
    }
});

Use CSS on error class as it pleases you.


问:
Scenario: Global variables in DLL which is used by Multi-threaded Application
Few months back, I had come across this interesting scenario asked by a guy (on orkut). Though, I've come up with a "non-portable" solution to this problem (have tested it with small code), but still would like to know what you guys have to say and suggest.

Suppose, I created a DLL, exporting some functionalities, written in C++, for single threaded client. This DLL declares lots of global variables, some maybe const variables (read-only) and others are modifiable.

Anyway, later things changed and now I want the same DLL to work with multi-threaded application (without modifying the DLL); that means, several threads access the functions and global variables from the DLL, and modify them.. and so on. All these may cause global variables to hold inconsistent values.

So the question is,

Can we do something in the client code to prevent multi-access of the DLL, and at the same time, ensuring that each thread runs in it's own context (meaning, when it gets access to the DLL, the DLL's global values are same as it was before)?

答:
Can we do something in the client code to prevent multi-access of the DLL, and at the same time, ensuring that each thread runs in it's own context (meaning, when it gets access to the DLL, the DLL's global values are same as it was before)?

This is the hard part.  I think the only way top do this would be to create a wrapper around teh existing DLL.  When it is called, it would restore the state (global variables) for the current thread, and save them when the call to the DLL returns.  You would need to know all of the state variables in the DLL, and be able to read/write them.

If performance is not an issue, a single lock for the entire DLL would suffice, and be the easiest to implement correctly.  That would ensure that only one thread was accessing (reading or writing) the DLL at one time.