text:
Q: WPF: binding a flag with checkboxes I wrote this enum (flag):
using System;
namespace AndreyBushman.AutoCAD {
    // Specifies, how and when .NET application will load.
    // It is a flag.
    [Flags]
    public enum LoadCtrls {
        // Load application upon detection of proxy object
        AtProxyFound = 1,
        // Load the application at startup
        AtAutoCADStart = 2,
        // Load the application at start of a command
        AtCommandStart = 4,
        // Load the application at the request of a user
        // or another application
        AtUserOrApplicationRequirement = 8,
        // Do not load the application
        NotLoad = 16,
        // Load the application transparently
        TransparencyLoad = 32,
    }
}

Now I have created StackPanel with CheckBox items:
<StackPanel x:Name="stackAllUsersLoadCtrls">
    <CheckBox Margin="2">At proxy found</CheckBox>
    <CheckBox Margin="2">At AutoCAD start</CheckBox>
    <CheckBox Margin="2">At command start</CheckBox>
    <CheckBox Margin="2">At user or application requirement</CheckBox>
    <CheckBox Margin="2">Not load</CheckBox>
    <CheckBox Margin="2">Transparency load</CheckBox>
</StackPanel>

Result screen:

How can I bind instance of LoadCtrls (it is a flag) with CheckBox items?

UPD
I have rewritten my code (added wrapper, rewrote converter, and XAML):
Wrapper:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ab = AndreyBushman.AutoCAD;
using System.ComponentModel;

namespace AcadLoadManaged {

    public sealed class LoadCtrlsWrapper : INotifyPropertyChanged {
        ab.LoadCtrls loadCtrls;

        public ab.LoadCtrls GetloadCtrls() {
            return loadCtrls;
        }
        public LoadCtrlsWrapper() {
            loadCtrls = default(ab.LoadCtrls);
        }
        public LoadCtrlsWrapper(ab.LoadCtrls loadCtrls) {
            this.loadCtrls = loadCtrls;
        }

        public Boolean AtAutoCADStart {
            get {
                return (loadCtrls & ab.LoadCtrls.AtAutoCADStart) != 0;
            }
            set {
                if (value)
                    loadCtrls |= ab.LoadCtrls.AtAutoCADStart;
                else
                    loadCtrls &= ~ab.LoadCtrls.AtAutoCADStart;
                OnPropertyChanged("AtAutoCADStart");
            }
        }

        public Boolean AtCommandStart {
            get {
                return (loadCtrls & ab.LoadCtrls.AtCommandStart) != 0;
            }
            set {
                if (value)
                    loadCtrls |= ab.LoadCtrls.AtCommandStart;
                else
                    loadCtrls &= ~ab.LoadCtrls.AtCommandStart;
                OnPropertyChanged("AtCommandStart");
            }
        }

        public Boolean AtProxyFound {
            get {
                return (loadCtrls & ab.LoadCtrls.AtProxyFound) != 0;
            }
            set {
                if (value)
                    loadCtrls |= ab.LoadCtrls.AtProxyFound;
                else
                    loadCtrls &= ~ab.LoadCtrls.AtProxyFound;
                OnPropertyChanged("AtProxyFound");
            }
        }

        public Boolean AtUserOrApplicationRequirement {
            get {
                return (loadCtrls & ab.LoadCtrls.AtUserOrApplicationRequirement) != 0;
            }
            set {
                if (value)
                    loadCtrls |= ab.LoadCtrls.AtUserOrApplicationRequirement;
                else
                    loadCtrls &= ~ab.LoadCtrls.AtUserOrApplicationRequirement;
                OnPropertyChanged("AtUserOrApplicationRequirement");
            }
        }

        public Boolean NotLoad {
            get {
                return (loadCtrls & ab.LoadCtrls.NotLoad) != 0;
            }
            set {
                if (value)
                    loadCtrls |= ab.LoadCtrls.NotLoad;
                else
                    loadCtrls &= ~ab.LoadCtrls.NotLoad;
                OnPropertyChanged("NotLoad");
            }
        }

        public Boolean TransparencyLoad {
            get {
                return (loadCtrls & ab.LoadCtrls.TransparencyLoad) != 0;
            }
            set {
                if (value)
                    loadCtrls |= ab.LoadCtrls.TransparencyLoad;
                else
                    loadCtrls &= ~ab.LoadCtrls.TransparencyLoad;
                OnPropertyChanged("TransparencyLoad");
            }
        }

        void OnPropertyChanged(String propertyName) {
            PropertyChangedEventHandler temp = PropertyChanged;
            if (null != temp)
                temp(this, new PropertyChangedEventArgs(propertyName));
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }
}

Converter:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
using ab = AndreyBushman.AutoCAD;

namespace AcadLoadManaged {

    public sealed class LoadCtrlsConverter : IValueConverter {

        public object Convert(object value, Type targetType, object parameter,
            System.Globalization.CultureInfo culture) {
            ab.LoadCtrls x = (ab.LoadCtrls)value;
            return new LoadCtrlsWrapper(x);
        }

        public object ConvertBack(object value, Type targetType, object parameter,
            System.Globalization.CultureInfo culture) {
            LoadCtrlsWrapper x = (LoadCtrlsWrapper)value;
            return x.GetloadCtrls();
        }
    }
}

XAML:
<GroupBox Grid.Row="4" Header="Load this plugin, when...:" Grid.Column="0"
          Grid.ColumnSpan="2" Padding="3">
    <GroupBox.DataContext>
        <Binding ElementName="lstAllUsers" Path="SelectedItem.LoadCtrls" Mode="TwoWay">
            <Binding.Converter>
                <local:LoadCtrlsConverter/>
            </Binding.Converter>
        </Binding>
    </GroupBox.DataContext>
    <StackPanel>
        <CheckBox Margin="2" Content="At proxy found" IsChecked="{Binding Path=AtProxyFound}"/>
        <CheckBox Margin="2" Content="At AutoCAD start" IsChecked="{Binding Path=AtAutoCADStart}"/>
        <CheckBox Margin="2" Content="At command start" IsChecked="{Binding Path=AtCommandStart}"/>
        <CheckBox Margin="2" Content="At user or application requirement"
                  IsChecked="{Binding Path=AtUserOrApplicationRequirement}"/>
        <CheckBox Margin="2" Content="Not load" IsChecked="{Binding Path=NotLoad}"/>
        <CheckBox Margin="2" Content="Transparency load" IsChecked="{Binding Path=TransparencyLoad}"/>
    </StackPanel>
</GroupBox>

But my binding works only one way. If I modify CheckBox values - they don't save. I have tried breakpoint on ConvertBack method, but it is not happening. Why?

A: Had similar needs, here is my approach of TwoWay flags binding.
No hardcoded enum types or any sort of values. Simply set the TargetType and Flags. Brilliant for settings window.
Usage:
<TextBox Text="{Binding ElementName=flagsCtrl, Path=Flags, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
<local:FlagsControl x:Name="flagsCtrl" TargetType="{x:Type local:TestFlags}" SelectionMode="Multiple"/>

FlagsControl:
using System;
using System.Collections.ObjectModel;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;

namespace FlagsControlDemoApplication
{
    public class FlagsControl : ItemsControl
    {
        public FlagsControl()
        {
            DataProvider = new ObservableCollection<Model>();

            Loaded += OnControlLoaded;
        }

        private void OnControlLoaded(object sender, RoutedEventArgs e)
        {
            Loaded -= OnControlLoaded;

            Binding isCheckedBinding = new Binding();
            isCheckedBinding.Path = new PropertyPath(Model.IsCheckedProperty);
            isCheckedBinding.Mode = BindingMode.TwoWay;
            isCheckedBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;

            Binding nameBinding = new Binding();
            nameBinding.Path = new PropertyPath(Model.NameProperty);
            nameBinding.Mode = BindingMode.TwoWay;
            nameBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;

            var checkBoxFactory = new FrameworkElementFactory(typeof(CheckBox));
            checkBoxFactory.SetValue(CheckBox.IsCheckedProperty, isCheckedBinding);
            checkBoxFactory.SetValue(CheckBox.ContentProperty, nameBinding);
            checkBoxFactory.AddHandler(CheckBox.CheckedEvent, new RoutedEventHandler(OnCheckBoxChecked));
            checkBoxFactory.AddHandler(CheckBox.UncheckedEvent, new RoutedEventHandler(OnCheckBoxUnchecked));

            ItemTemplate = new DataTemplate(typeof(CheckBox));
            ItemTemplate.VisualTree = checkBoxFactory;
            ItemsSource = DataProvider;
        }

        public FlagSelectionMode SelectionMode
        {
            get { return (FlagSelectionMode)GetValue(SelectionModeProperty); }
            set { SetValue(SelectionModeProperty, value); }
        }
        public static readonly DependencyProperty SelectionModeProperty =
            DependencyProperty.Register(nameof(SelectionMode), typeof(FlagSelectionMode), typeof(FlagsControl), new PropertyMetadata(FlagSelectionMode.Multiple));

        public ObservableCollection<Model> DataProvider
        {
            get { return (ObservableCollection<Model>)GetValue(DataProviderProperty); }
            set { SetValue(DataProviderProperty, value); }
        }
        public static readonly DependencyProperty DataProviderProperty =
            DependencyProperty.Register(nameof(DataProvider), typeof(ObservableCollection<Model>), typeof(FlagsControl), new PropertyMetadata(null));

        public uint Flags
        {
            get { return (uint)GetValue(ValueProperty); }
            set { SetValue(ValueProperty, value); }
        }
        public static readonly DependencyProperty ValueProperty =
            DependencyProperty.Register(nameof(Flags), typeof(uint), typeof(FlagsControl), new PropertyMetadata(OnValuePropertyChanged));

        private static void OnValuePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            foreach (var model in ((FlagsControl)d).DataProvider)
            {
                var val = (uint)Convert.ChangeType(e.NewValue, typeof(uint));

                if (Exists(val, model.Value) != model.IsChecked)
                {
                    model.IsChecked = !model.IsChecked;
                }
            }
        }

        public Type TargetType
        {
            get { return (Type)GetValue(TargetTypeProperty); }
            set { SetValue(TargetTypeProperty, value); }
        }
        public static readonly DependencyProperty TargetTypeProperty =
            DependencyProperty.Register(nameof(TargetType), typeof(Type), typeof(FlagsControl), new PropertyMetadata(null, new PropertyChangedCallback(OnTargetTypePropertyChanged)));

        private static void OnTargetTypePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var provider = ((FlagsControl)d).DataProvider;

            FieldInfo[] fields = ((Type)e.NewValue).GetFields(BindingFlags.Public | BindingFlags.Static);

            provider.Clear();

            foreach (var field in fields)
            {
                var fieldValue = (uint)Convert.ChangeType(field.GetValue(null), typeof(uint));

                provider.Add(new Model() { Name = field.Name, IsChecked = Exists(((FlagsControl)d).Flags, fieldValue), Value = fieldValue });
            }

            ((FlagsControl)d).DataProvider = provider;
        }

        private void OnCheckBoxChecked(object sender, RoutedEventArgs e)
        {
            if (SelectionMode == FlagSelectionMode.Multiple)
                Flags = Add(Flags, ((Model)((CheckBox)sender).DataContext).Value);
            else Flags = ((Model)((CheckBox)sender).DataContext).Value;
        }
        private void OnCheckBoxUnchecked(object sender, RoutedEventArgs e)
        {
            Flags = Remove(Flags, ((Model)((CheckBox)sender).DataContext).Value);
        }

        public static bool Exists(uint flags, uint flag) => (flags & flag) == flag;
        public static uint Add(uint flags, uint flag) => flags |= flag;
        public static uint Remove(uint flags, uint flag) => Exists(flags, flag) ? flags ^ flag : flags;
    }

    public enum FlagSelectionMode
    {
        Multiple, Single
    }

    public class Model : DependencyObject
    {
        public bool IsChecked
        {
            get { return (bool)GetValue(IsCheckedProperty); }
            set { SetValue(IsCheckedProperty, value); }
        }
        public static readonly DependencyProperty IsCheckedProperty =
            DependencyProperty.Register(nameof(IsChecked), typeof(bool), typeof(Model));

        public string Name
        {
            get { return (string)GetValue(NameProperty); }
            set { SetValue(NameProperty, value); }
        }
        public static readonly DependencyProperty NameProperty =
            DependencyProperty.Register(nameof(Name), typeof(string), typeof(Model));

        public uint Value
        {
            get { return (uint)GetValue(ValueProperty); }
            set { SetValue(ValueProperty, value); }
        }
        public static readonly DependencyProperty ValueProperty =
            DependencyProperty.Register(nameof(Value), typeof(uint), typeof(Model));
    }
}

DemoApp & SourceCode

A: To adapt a Model(LoadCtrls) to a View(XAML), use a ViewModel.
public class ApplicationSettingsViewModel :
    MyViewModelBaseImplementingINotifyPropertyChanged {

    public ApplicationSettingsViewModel(ApplicationSettings model)
    {
      m_model = model;
      m_model.PropertyChanged += OnModelPropertyChanged;
    }

    ... OnModelPropertyChanged(object sender, WhateverArgs e)
    {
      switch(e.PropertyName)
      {
        ...
        case "Load":
          RaisePropertyChanged("IsAtProxyFoundSet");
          RaisePropertyChanged("IsAtAutoCADStartSet");
          ...
          break;
        ...
      }
    }

    ...
    public bool IsAtProxyFoundSet
    {
       get { return m_model.Load & LoadCtrls.AtProxyFound; }
       set { m_model.Load |= LoadCtrls.AtProxyFound; }
    }

    public bool IsAtAutoCADStartSet
    {
       get { return m_model.Load & LoadCtrls.AtAutoCADStart; }
       set { m_model.Load |= LoadCtrls.AtAutoCADStart; }
    }

    ...
}

UPDATE
Here is an updated example :
public sealed class UserWrapper {

    private User m_user;

    public UserWrapper(User user) {
        m_user = user;
    }

    public Boolean AtAutoCADStart {
        get {
            return (m_user.loadCtrls & ab.LoadCtrls.AtAutoCADStart) != 0;
        }
        set {
            if (value)
                m_user.loadCtrls |= ab.LoadCtrls.AtAutoCADStart;
            else
                m_user.loadCtrls &= ~ab.LoadCtrls.AtAutoCADStart;
        }
    }

    public Boolean AtCommandStart {
        get {
            return (m_user.loadCtrls & ab.LoadCtrls.AtCommandStart) != 0;
        }
        set {
            if (value)
                m_user.loadCtrls |= ab.LoadCtrls.AtCommandStart;
            else
                m_user.loadCtrls &= ~ab.LoadCtrls.AtCommandStart;
        }
    }

    public Boolean AtProxyFound {
        get {
            return (m_user.loadCtrls & ab.LoadCtrls.AtProxyFound) != 0;
        }
        set {
            if (value)
                m_user.loadCtrls |= ab.LoadCtrls.AtProxyFound;
            else
                m_user.loadCtrls &= ~ab.LoadCtrls.AtProxyFound;
        }
    }

    public Boolean AtUserOrApplicationRequirement {
        get {
            return (m_user.loadCtrls & ab.LoadCtrls.AtUserOrApplicationRequirement) != 0;
        }
        set {
            if (value)
                m_user.loadCtrls |= ab.LoadCtrls.AtUserOrApplicationRequirement;
            else
                m_user.loadCtrls &= ~ab.LoadCtrls.AtUserOrApplicationRequirement;
        }
    }

    public Boolean NotLoad {
        get {
            return (m_user.loadCtrls & ab.LoadCtrls.NotLoad) != 0;
        }
        set {
            if (value)
                m_user.loadCtrls |= ab.LoadCtrls.NotLoad;
            else
                m_user.loadCtrls &= ~ab.LoadCtrls.NotLoad;
        }
    }

    public Boolean TransparencyLoad {
        get {
            return (m_user.loadCtrls & ab.LoadCtrls.TransparencyLoad) != 0;
        }
        set {
            if (value)
                m_user.loadCtrls |= ab.LoadCtrls.TransparencyLoad;
            else
                m_user.loadCtrls &= ~ab.LoadCtrls.TransparencyLoad;
        }
    }

}

Converter:
    public sealed class UserToUserWrapperConverter : IValueConverter {

        public object Convert(object value, Type targetType, object parameter,
            System.Globalization.CultureInfo culture) {
              return new UserWrapper((User)value);
        }

        public object ConvertBack(object value, Type targetType, object parameter,
            throw new Exception(); // never called
        }
    }
}

XAML:
<GroupBox Grid.Row="4" Header="Load this plugin, when...:" Grid.Column="0"
          Grid.ColumnSpan="2" Padding="3">
    <GroupBox.DataContext>
        <Binding ElementName="lstAllUsers" Path="SelectedItem">
            <Binding.Converter>
                <local:UserToUserWrapperConverter/>
            </Binding.Converter>
        </Binding>
    </GroupBox.DataContext>
    <StackPanel>
        <CheckBox Margin="2" Content="At proxy found" IsChecked="{Binding Path=AtProxyFound}"/>
        <CheckBox Margin="2" Content="At AutoCAD start" IsChecked="{Binding Path=AtAutoCADStart}"/>
        <CheckBox Margin="2" Content="At command start" IsChecked="{Binding Path=AtCommandStart}"/>
        <CheckBox Margin="2" Content="At user or application requirement"
                  IsChecked="{Binding Path=AtUserOrApplicationRequirement}"/>
        <CheckBox Margin="2" Content="Not load" IsChecked="{Binding Path=NotLoad}"/>
        <CheckBox Margin="2" Content="Transparency load" IsChecked="{Binding Path=TransparencyLoad}"/>
    </StackPanel>
</GroupBox>

A: I use a custom checkbox and bind on 2 properties because of the dependency between the enum flag and its enum value.
This is my code (I use it in production with success and it is very simple to use - see comments on top of the class).
Do you like it ?
using System;
using System.Windows;
using System.Windows.Controls;

namespace HQ.Wpf.Util.MyControl
{
    /// <summary>
    /// Usage: Bind on EnumFlag and Two way binding on EnumValue instead of IsChecked
    /// Example: <myControl:CheckBoxForEnumWithFlagAttribute
    ///                 EnumValue="{Binding SimulationNatureTypeToCreateStatsCacheAtEndOfSimulation, Mode=TwoWay}"
    ///                 EnumFlag="{x:Static Core:SimulationNatureType.LoadFlow }">Load Flow results</myControl:CheckBoxForEnumWithFlagAttribute>
    /// </summary>
    public class CheckBoxForEnumWithFlagAttribute : CheckBox
    {
        // ************************************************************************
        public static DependencyProperty EnumValueProperty =
            DependencyProperty.Register("EnumValue", typeof(object), typeof(CheckBoxForEnumWithFlagAttribute), new PropertyMetadata(EnumValueChangedCallback));

        public static DependencyProperty EnumFlagProperty =
            DependencyProperty.Register("EnumFlag", typeof(object), typeof(CheckBoxForEnumWithFlagAttribute), new PropertyMetadata(EnumFlagChangedCallback));

        // ************************************************************************
        public CheckBoxForEnumWithFlagAttribute()
        {
            base.Checked += CheckBoxForEnumWithFlag_Checked;
            base.Unchecked += CheckBoxForEnumWithFlag_Unchecked;
        }

        // ************************************************************************
        private static void EnumValueChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
        {
            var checkBoxForEnumWithFlag = dependencyObject as CheckBoxForEnumWithFlagAttribute;
            if (checkBoxForEnumWithFlag != null)
            {
                checkBoxForEnumWithFlag.RefreshCheckBoxState();
            }
        }

        // ************************************************************************
        private static void EnumFlagChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
        {
            var checkBoxForEnumWithFlag = dependencyObject as CheckBoxForEnumWithFlagAttribute;
            if (checkBoxForEnumWithFlag != null)
            {
                checkBoxForEnumWithFlag.RefreshCheckBoxState();
            }
        }

        // ************************************************************************
        public object EnumValue
        {
            get { return GetValue(EnumValueProperty); }
            set { SetValue(EnumValueProperty, value); }
        }

        // ************************************************************************
        public object EnumFlag
        {
            get { return GetValue(EnumFlagProperty); }
            set { SetValue(EnumFlagProperty, value); }
        }

        // ************************************************************************
        private void RefreshCheckBoxState()
        {
            if (EnumValue != null)
            {
                if (EnumValue is Enum)
                {
                    Type underlyingType = Enum.GetUnderlyingType(EnumValue.GetType());
                    dynamic valueAsInt = Convert.ChangeType(EnumValue, underlyingType);
                    dynamic flagAsInt = Convert.ChangeType(EnumFlag, underlyingType);

                    base.IsChecked = ((valueAsInt & flagAsInt) > 0);
                }
            }
        }

        // ************************************************************************
        private void CheckBoxForEnumWithFlag_Checked(object sender, RoutedEventArgs e)
        {
            RefreshEnumValue();
        }

        // ************************************************************************
        void CheckBoxForEnumWithFlag_Unchecked(object sender, RoutedEventArgs e)
        {
            RefreshEnumValue();
        }

        // ************************************************************************
        private void RefreshEnumValue()
        {
            if (EnumValue != null)
            {
                if (EnumValue is Enum)
                {
                    Type underlyingType = Enum.GetUnderlyingType(EnumValue.GetType());
                    dynamic valueAsInt = Convert.ChangeType(EnumValue, underlyingType);
                    dynamic flagAsInt = Convert.ChangeType(EnumFlag, underlyingType);

                    dynamic newValueAsInt = valueAsInt;
                    if (base.IsChecked == true)
                    {
                        newValueAsInt = valueAsInt | flagAsInt;
                    }
                    else
                    {
                        newValueAsInt = valueAsInt & ~flagAsInt;
                    }

                    if (newValueAsInt != valueAsInt)
                    {
                        object o = Enum.ToObject(EnumValue.GetType(), newValueAsInt);

                        EnumValue = o;
                    }
                }
            }
        }

        // ************************************************************************
    }
}


text:
Q: Single paged website, which i want to get at a certain point after refreshing page I have a single paged website, in which i've got a div named sitecontent with the width of 4400, which holds 4 "pages". The pages start at 0px of sitecontent, 1100 px of sitecontent, 2200px of sitecontent, and 3300px.
I use Jquery to set de div position to the right px, so i get the right text displayed. After pressing a link i get for example:

At one of the pages i have to refresh the page, and after this refresh i want the page to display the same "page" on 1100px, but it starts at 0px, the home page.
Is there any way how i can make sure that the sitecontent starts at -1100px of home?
Thanks in advance,
Cheers

A: You need to append some identifier onto the hash of the URL that you can parse on the page load.
For example:
 http://www.somewebpage.com/somepage#page1

Then in the load of the page, you can inspect this hash value and immediately change the UI to show the new page:
 var hash = window.location.hash;

 if(hash == "#page1")
    $('#site-content').css('left', '-1100px');

A: You can use a cookie to store the value, then, every time the page loads, you need to check the cookie and deal with the value collected:
The link for Jquery Cookie with download and usage manual!
HTML (example)

  Click to view page 01

JQUERY (jquery.cookie)
// SET THE COOKIE
$('.setCookie').bind("click", function() {
  var pageNumber = $(this).attr("id");
  $.cookie('the_cookie_name', pageNumber, { expires: 7, path: '/' });
});

// READ THE COOKIE
$(function() {
  var oldNumber = $.cookie('the_cookie_name');
  if (oldNumber !== NULL) {
   $("#page_"+oldNumber).trigger("click");
  }
});

Note:
The link that you currently use to change pages, should have the class "setCookie" to trigger the cookie creation, and also the id that is being used to identify the page number.
One advantage of this is that you can control for how long is the cookie preserved and thus allowing the visitant to resume the website experience.

A: An approach very similar to what Tejs is proposing would be to use a hash-based routing framework that listens to hash changes. That will result in much cleaner code since you don't need to define the scrolling in two different places.
Every link in your page is currently being observed by a jQuery event listener (onclick -> moves the content container to the show the desired content). The HTML looks probably somewhat like this: Contact details.
With this approach, you don't need to watch those links. Instead, simply make them change the hash: Contact details.
Now observe the hash and react to changes. I'm using the Simrou framework (https://github.com/buero-fuer-ideen/Simrou) but you can go with any other framework that provides similar functionality.
jQuery(document).ready(function() {
    // Define a function that moves the content, e.g. moveContent(3300);
    function moveContent(pixelPosition) {
        $('#site-content').css('left', '-' + pixelPosition + 'px');
    }

    // Setup the router
    var router = new Simrou({
        'page1': function() { moveContent(0); },
        'page2': function() { moveContent(1100); },
        'page3': function() { moveContent(2200); },
        'page4': function() { moveContent(3300); }
    });
    router.start();
});

That's all the javascript you need!
(and here is a quick and dirty fiddle, demonstrating the whole thing: http://jsfiddle.net/R7F6r/)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Remove RDD values with condition I have an RDD like this:
[ (Person 1, [Cat, Dog, Cow]), (Person 2, [Cat]), (Person 3,[Cow, Chicken])]

And I have a list of frequent animals:
freq_animals=[Cat, Dog]

I want to delete in my RDD the values for each person that are not in the list of frequent animals i.e. Output would be:
[ (Person 1, [Cat, Dog]), (Person 2, [Cat]), (Person 3,[])]

Any idea how I could change my RDD?
Thank you!

A: You can do mapValues using a list comprehension:
rdd = sc.parallelize([("Person 1", ["Cat", "Dog", "Cow"]), ("Person 2", ["Cat"]), ("Person 3", ["Cow", "Chicken"])])

freq_animals = ["Cat", "Dog"]

rdd2 = rdd.mapValues(lambda v: [i for i in v if i in freq_animals])

print(rdd2.collect())
# [('Person 1', ['Cat', 'Dog']), ('Person 2', ['Cat']), ('Person 3', [])]


text:
Q: How to sort an arraylist of hotel rooms I have an arraylist of hotel rooms
Each hotel room has:
public class HotelRoom {
   int Number
   String roomType (Triple, family, double)
   String priceModel (perunit, per person,)
   Int Price
   Int MaxGuests
}

I need to return a list of the cheapest options for
a booking of 9 people
(Could be 2 family rooms / 3 triple rooms / 4 double, 1 single)
How could I do this?

A: A quick solution is to loop through the current list using a for each statement and add them to a new list using an if statement that checks the price


text:
Q: Add unique ID to identical links for tracking campaign value return I am attempting to get all links on a page where the link name and href are the same and assign a value to the return name to make the reference to that link unique.
So if a page had the following three identicial links:
            About Us
            About Us
            About Us

The expected result if second link clicked the return would be:

aboutus-link1-2

I can get the link name and href returned as below:
            var linkname = $(input).text().trim().replace(/\W/g, '').toLowerCase();
            var hrefname = $(input).closest('a').attr("href").replace(/\W/g, '').toLowerCase();
            return linkname + '-' + hrefname;

But I don't know how I would do the ID on the end, any help would be appreciated.

A: I came up with a vanilla js solution. It might be a little verbose, but you can get the id like this:
var q = document.querySelectorAll('.adobeTrackedCustomLink');

for(var i = 0; i<q.length; i++){
      q[i].id = i;
      var linkname;
      var hrefname;
      var id;
      q[i].addEventListener('click', function(e){
                e.preventDefault();
                linkname = this.textContent.replace(/\s+/g, '').toLowerCase();
                hrefname = this.getAttribute('href');
                id = Number(this.id);
                console.log("New Name",  linkname+"-"+hrefname+"-"+(Number(id)+1));
      })
 }


text:
Q: In Linked/Related questions list mark the questions with a status tag (Meta sites only) On meta sites (both per-site and MSE), I don't really care for accepted answer. What I do care about is the status of a bug report or feature request.
Currently, the Related/Linked questions in the sidebar got a different color when the question has an accepted answer. This is useful on main sites, however on meta sites (including here on MSE), I would prefer to have a different color for questions having a status tag on them.
For example, the Related questions list for this question would look like this:

This way I can easily know "those are handled", instead of "those got accepted answer", which is not really helpful on meta sites.

A: Color's not a great way to distinguish status. (Colorblindness is fairly common, after all.)
I suggest that any question with a status-* tag on it be displayed with Italics.
That won't change the aesthetics of the related question list design, but will still convey that certain of the questions are different.


text:
Q: Forward slashes preventing automatic creation of variable labels I've done quite a bit of searching on this, and haven't come up with a clear solution. I'm much better with SPSS syntax than I am python, so bear with me.
I have an SPSS dataset with a ton of variables that get recoded into different forms, and I'm trying to clean up the syntax, and I'm almost there.
The dataset comes from an excel file that has the full variable label as the column header, so when SPSS imports it the unedited version is stuck in the variable label field where I want it; in other words I am not explicitly defining the variable labels at any point.
After I recode the variables I need to copy the original variable label and append 'Recoded: ' to the beginning. I'm trying to avoid several hundred lines of explicitly defining the variable labels on all the recoded variables.
The problem I'm running into is one of the labels contains a forward slash, and using the syntax in the example below results in the slash being treated as an exit character within the syntax, and the label that contains the slash is only partially copied to the recoded variable.
data list /var001 1 var002 5.
begin data
3   4
4   5
2   3
5   5
end data.
variable labels
var001 "Variable label that contains apostrophes' but not forward slashes"
/var002 "Variable label that contains apostrophes' and/or forward slashes".
RECODE var001 var002 (1 thru 3 = 0) (4 thru 5 = 1) INTO var001_r var002_r.
EXECUTE.

begin program.
variables='var001 to var002'
import spss, spssaux, spssdata
spss.Submit("set mprint on.")
vdict=spssaux.VariableDict(caseless=True)
varlist=spssaux.VariableDict().expand(variables)
for var in varlist:
    vlab = vdict[var].VariableLabel
    spss.Submit("VARIABLE LABEL %s." % ("\n" .join([r"%s_r ""Recode: %s"" " % (str(var), vlab)])))
spss.Submit("set mprint off.")
end program.

A: Don't actually need python for this one.
The following syntax uses OMS to capture var names & labels from dictionary command and uses them to write a new syntax which creates the new labels:
dataset name orig.
DATASET DECLARE  vrlst.
OMS   /SELECT TABLES  /IF COMMANDS=['File Information'] SUBTYPES=['Variable Information']
  /DESTINATION FORMAT=SAV  OUTFILE='vrlst' .
DISPLAY DICTIONARY.
omsend.
dataset activate vrlst.
select if Label<>"<none>".
string cmd (a100).
compute cmd=concat("var labels ", rtrim(var1), '_r  "recoded: ', Label, '".').
write out="path\recode labels.sps" /cmd.
dataset activate orig.
insert file="path\recode labels.sps".


text:
Q: Modify array from TextField in Flutter I have this simple widget showing a textfield from which I modify a List:
Widget _elementTextField() {
    final TextEditingController inputNewElement = new TextEditingController();
    return Expanded(
      flex: 3,
      child: Padding(
        padding: EdgeInsets.fromLTRB(0, 16.0, 16.0, 16.0),
        child: Container(
          child: TextField(
            controller: inputNewElement,
            decoration: InputDecoration(labelText: "Add Element"),
            onSubmitted: (elem) {
              // method 1 to update UI
              /*setState(() {
                newSet.elements.add(elem);
              });*/
              // method 2 not updating UI
              // newSet.elements.add(elem);

              print(newSet.elements);
              inputNewElement.clear();
            },
          ),
        ),
      ),
    );
  }

If I uncomment any of those method I won't see the print and the input won't clean up.
This is not related to any other widget and the List is just a simple List with one value on it.
This works fine with other widget I have but on that case I modify the value on a global provider. This is using just a StateFul widget

A: Try to remove final TextEditingController inputNewElement = new TextEditingController(); from _elementTextField()
import 'package:flutter/material.dart';

class SamplePage extends StatefulWidget {

    SamplePage({Key key}) : super(key: key);

    @override
    State<StatefulWidget> createState() => SamplePageState();

}

class SamplePageState extends State<SamplePage> {

    final List<String> list = List();
    final TextEditingController inputNewElement = new TextEditingController();

    @override
    void initState() {
        super.initState();
    }

    @override
    void dispose() {
        inputNewElement.dispose();
        super.dispose();
    }

    @override
    Widget build(BuildContext context) {
        return Scaffold(
            body: Column(
                children: <Widget>[
                    Row(children: <Widget>[_elementTextField()]),
                    Text(list.isEmpty ? 'Empty' : list.toString()),
                ],
            )
        );
    }

    Widget _elementTextField() {
//        final TextEditingController inputNewElement = new TextEditingController();
        return Expanded(
            flex: 3,
            child: Padding(
                padding: EdgeInsets.fromLTRB(0, 16.0, 16.0, 16.0),
                child: Container(
                    child: TextField(
                        controller: inputNewElement,
                        decoration: InputDecoration(labelText: "Add Element"),
                        onSubmitted: (elem) {
                            setState(() {
                                list.add(elem);
                            });
                            print(list);
                            inputNewElement.clear();
                        },
                    ),
                ),
            ),
        );
    }

}

A: TextField itself is a Stateful widget, so when you call setState from inside the methods in TextField it will not update widgets outside of the text field.
To resolve this create the method in the parent widget to update the list and call setState from there, it will update the parent widget and the text field will be cleared.

A: You'll find the solution above this answer, this was just my approaches to fix the whole problem:
Trying to recreate a smaller version of my page, I found this issue:
@override
  Widget build(BuildContext context) {
   if (widget.data != null) {
      // editing set
      newSet.elements = widget.data['mySet']['elements'];
    } else {
      // creating set
      ...
    }

This was executed every time I added something to the array so I moved the check to initState().
Second error was this:
newSet.elements = widget.data['mySet']['elements'];

I had to modify this line and create my list without cloning it like so:
newSet.elements = []..addAll(widget.data['mySet']['elements']);

At this point, my list was adding more elements but it wasn't being displayed (I didn't mention this issue but I'll show the solution anyway).
I had this var containing some widgets:
_steps = [
      _step0(),
      _step1(),
      _step2(),
    ];

This list was being used to change dynamically a Swiper widget (more info).
So instead of doing this:
Swiper(
    itemBuilder: (BuildContext context, int index) {
       return _steps[index];
    },

I do this now:
    Swiper(
        itemBuilder: (BuildContext context, int index) {
              switch (index) {
                    case 1:
                      return _step1();
                      break;
                    case 2:
                      return _step2();
                      break;
                    default:
                      return _step0();
                  }
        },


text:
Q: Where to use Thread interupt I have some old code I am working with, and I'm not too experienced with Threads (mostly work on the front end).  Anyway, this Thread.sleep is causing the thread to hang and I'm unsure what to do about it.  I thought about using a counter and throwing a Thread.currentThread.interupt, but unsure of where to put it or which thread it will interupt.  Here is an example of the dump.  As you can see the thread count is getting pretty high at 1708.
Any advice?

"Thread-1708" prio=6 tid=0x2ceec400 nid=0x2018 waiting on condition
  [0x36cdf000]    java.lang.Thread.State: TIMED_WAITING (sleeping)  at
  java.lang.Thread.sleep(Native Method)    Locked ownable synchronizers:
    - None "Thread-1707" prio=6 tid=0x2d16b800 nid=0x215c waiting on condition [0x36c8f000]    java.lang.Thread.State: TIMED_WAITING
  (sleeping)    at java.lang.Thread.sleep(Native Method)    Locked ownable
  synchronizers:
    - None

@Override
public void run()
{
    Connection con = null;
    int i = 0;

    while (is_running)
    {
        try
        {
            con = ConnectionManager.getConnection();

            while (!stack.isEmpty())
            {
                COUNT++;
                String line = (String) stack.pop();
                getPartMfr(line);
                try
                {
                    if (this.mfr != null && !this.mfr.equals(EMPTY_STR))
                    {
                        lookupPart(con, line);
                    }
                }
                catch (SQLException e)
                {
                    e.printStackTrace();
                }
                if (COUNT % 1000 == 0)
                {
                    Log log = LogFactory.getLog(this.getClass());
                    log.info("Processing Count: " + COUNT);
                }
            }
        }
        catch (NamingException e)
        {
            e.printStackTrace();
        }
        catch (SQLException e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                ConnectionManager.close(con);
            }
            catch (SQLException e)
            {
                e.printStackTrace();
            }
        }

        try {
            Thread.sleep(80);

        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
    this.finished = true;

}

Here is where it calls the run method, as you can see it does set it to false, but I guess it is missing threads?
    HarrisWorker w[] = new HarrisWorker[WORKER_POOL_SIZE];
    try
    {
        for (int i = 0; i < w.length; i++)
        {
            w[i] = new HarrisWorker(pw);
            w[i].start();
        }
        pw.println(headers());
        File inputDir = new File(HARRIS_BASE);
        String files[] = inputDir.list();
        for (String file : files)
        {

            try
            {
                File f = new File(HARRIS_BASE + File.separator + file);
                if (f.isDirectory())
                    continue;
                final String workFile = workDir + File.separator + file;
                f.renameTo(new File(workFile));

                FileReader fr = new FileReader(workFile);
                BufferedReader br = new BufferedReader(fr);
                String line = br.readLine();

                boolean firstLine = true;

                while (line != null)
                {
                    if (firstLine)
                    {
                        firstLine = false;
                        line = br.readLine();
                        continue;
                    }
                    if (line.startsWith(","))
                    {
                        line = br.readLine();
                        continue;
                    }
                    //          if(line.indexOf("103327-1") == -1)
                    //          {
                    //              line = br.readLine();
                    //              continue;
                    //          }
                    HarrisWorker.stack.push(line);
                    line = br.readLine();
                }
                br.close();
                fr.close();
                for (int i = 0; i < w.length; i++)
                {
                    w[i].is_running = false;

                    while (!w[i].finished)
                    {

                        Thread.sleep(80);
                    }

                }
                move2Processed(file, workFile);
                long etime = System.currentTimeMillis();
                System.out.println("UNIQUE PARTS TOTAL FOUND: " + HarrisWorker.getFoundCount() + " of " + HarrisWorker.getUniqueCount() + ", "
                        + (HarrisWorker.getFoundCount() / HarrisWorker.getUniqueCount()));
                System.out.println("Time: " + (etime - time));

            }
            catch (Exception e)
            {
                e.printStackTrace();
                File f = new File(workDir + File.separator + file);
                if (f.exists())
                {
                    f.renameTo(new File(HARRIS_BASE + File.separator + ERROR + File.separator + file));
                }

            }
        }
    }

A: As a direct answer to the question in your title - nowhere. There is nowhere in this code that needs a Thread.interrupt().
The fact that the thread name is Thread-1708 does not necessarily mean there are 1708 threads. One can choose arbitrary names for threads. I usually include the name of the executor or service in the thread name. Maybe 1600 are now long stopped and there are only around a hundred alive. Maybe this particular class starts naming at 1700 to distinguish from other uses.
1708 threads may not be a problem. If you have a multi-threaded server that is serving 2000 connections in parallel, then it certainly expectable that there are 2000 threads doing that, along with a bunch of other threads.
You have to understand why the sleep is there and what purpose it serves. It's not there to just hog memory for nothing.
Translating the code to "plaintext" (btw it can be greatly simplified by using try-with-resources to acquire and close the connection):

*

*Acquire a connection

*Use the connection to send (I guess) whatever is in the stack

*When failed or finished - wait 80ms (THIS is your sleep)

*If run flag is still set - repeat from step 1

*Finish the thread.

Now reading through this, it's obvious that it's not the sleep that's the problem. It's that the run flag is not set to false. And your thread just continues looping, even if it can't get the connection at all - it will simply spend most of its time waiting for the retry. In fact - even if you completely strip the sleep out (instead of interrupting it mid-way), all you will achieve is that the Threads will start using up more resources. Given that you have both a logger and you print to stdout via printStackTrace, I would say that you have 2 problems:

*

*Something is spawning threads and not stopping them afterwards (not setting their run flag to false when done)

*You are likely getting exceptions when getting the Connection, but you never see them in the log.

It might be that the Thread is supposed to set it's own run flag (say when the stack is drained), but you would have to decide that yourself - that depends on a lot of specifics.

A: Not an answer but some things you should know if you are writing code for a live, production systemn:
:-(  Variable and method both have the same name, run.  A better name for the variable might be keep_running  Or, change the sense of it so that you can write while (! time_to_shut_down) { ... }
:-( Thread.sleep(80)  What is this for?  It looks like a big red flag to me.  You can never fix a concurrency bug by adding a sleep() call to your code.  All you can do is make the bug less likely to happen in testing.  That means, when the bug finally does bite, it will bite you in the production system.
:-( Your run() method is way too complicated (the keyword try appears four times).  Break it up, please.
:-( Ignoring five different exceptions catch (MumbleFoobarException e) { e.printStackTrace(); }  Most of those exceptions (but maybe not the InterruptedException) mean that something is wrong.  Your program should do something more than just write a message to the standard output.
:-( Writing error messages to standard output.  You should be calling log.error(...) so that your application can be configured to send the messages to someplace where somebody might actually see them.


text:
Q: tkinter can't save data from entry to text file The code works pretty good except from the .get() that doesn't retrieve the string from the Entry box into my new text file.
import tkinter

def save_register():

    full_name_info = full_name.get()
    email_info = email.get()
    password_info = password.get()

    with open("RegistrationInfo.txt", "w") as f:
        f.write("username: " + full_name_info + "\n")
        f.write("email: " + email_info + "\n")
        f.write("password: " + password_info + "\n")

        full_name_entry.delete(0, 100)
        email_entry.delete(0, 100)
        password_entry.delete(0, 100)

    tkinter.Label(screen1, text="Registration completed", fg="green").pack()

---- New Window ----
def new_user():

    global screen1
    global full_name
    global email
    global password
    global full_name_entry
    global email_entry
    global password_entry

    screen1 = tkinter.Tk()
    screen1.geometry("300x300")
    screen1.title("register page")

    full_name = tkinter.StringVar()
    email = tkinter.StringVar()
    password = tkinter.StringVar()

    tkinter.Label(screen1, text="Welcome please enter info below").pack()
    tkinter.Label(screen1, text="").pack()
    tkinter.Label(screen1, text="Full name:").pack()
    full_name_entry = tkinter.Entry(screen1, textvariable=full_name, width=25)
    full_name_entry.pack()
    tkinter.Label(screen1, text="Email:").pack()
    email_entry = tkinter.Entry(screen1, textvariable=email, width=25)
    email_entry.pack()
    tkinter.Label(screen1, text="Password:").pack()
    password_entry = tkinter.Entry(screen1, textvariable=password, width=25)
    password_entry.pack()
    tkinter.Label(screen1, text="").pack()
    tkinter.Button(screen1, text="Register", command=save_register).pack()

So I'm not really sure what is wrong here I will be more than happy if anyone will figure it out.

A: I'm not exactly sure what the culprit is here but I suspect it has something to do with the use of StringVar within tkinter.
From everything I've read, StringVar is a completely valid way to obtain the data that has been entered into your entry boxes.
However, I personally had some issues implementing StringVar into my own GUI program recently. Instead, I just used the .get method as follows:
full_name=''

full_name_entry = tkinter.Entry(screen1, width=25)
full_name_entry.pack()

full_name = full_name_entry.get()

I was then able to manipulate the data mathematically throughout the rest of my program. StringVar and IntVar is also made for this purpose, so sticking with that method is understandable.
This guide to StringVar was one of the more readable guides I read when faced with this same issue. It walks through the different Var types in tkinter and how to implement them.


text:
Q: Moving from using innerHTML for an AJAX response. (Code is not getting a response) I am currently using the code as seen below but it is insecure and can be used to exploit the website using XSS.
Old Code, that works:
document.getElementById('response').innerHTML = xmlHTTP.responseText;

New code that is giving no response:
var divContent = xmlHTTP.responseText;
  var getRes = document.getElementById('response');
  if (getRes.innerText) {
      getRes.innerText = divContent; //For Safari, Google Chrome and MSIE.
  }
  else
  if (getRes.textContent) {
      getRes.textContent = divContent; //For Firefox.
    }
}

The basic HTML Div below:

Furthermore the output is HTML, not text.

A: The div is empty. If innerText or textContent are defined, then they will be empty strings. Empty strings are not true values.
Create text nodes instead, they are standard and well supported.
document.getElementById('response').appendChild(
    document.createTextNode(
        xmlHTTP.responseText
    )
);

If you need to empty the element first you can always:
document.getElementById('response').innerHTML = "";


text:
Q: parsing Azure id using regex I have following id that I would need to parse so that I could use only the vm name of id but can't figure this out
/subscriptions/0000x0000x0000x000/resourceGroups/MyResourceGroup/providers/Microsoft.HybridCompute/machines/MyVirtualMachine/extensions/MyAgent

I have tried following lines but I have not gotten it work
| parse kind=regex id with '/machines/' vmanme
| parse kind=regex id with * 'machines=' machines
| parse kind=regex id with "(.*?)[a-zA-Z]*=" machines @"
| parse kind=regex id with  with * "machines=" machines ',' *
| parse kind=regex flags = Ui  id with * "MACHINES=" machines ',' *

Best try I had with | parse kind=regex id with '/machines/' vmanme but then I outputted a bit too much: /MyVirtualMachine/extensions/MyAgent insted only outputting MyVirtualMachine

A: Try using this syntax:
| parse kind=regex id with 'machines/' vmanme '/extensions'

Does it work for you?


text:
Q: OctoberCMS: How to maintain a two-way friendship relation? I'm extending the rainlab.user plugin to allow each user to have friends via a simple intermediate table with the following fields:
user_id
friend_id
status

I've extended the User model:
use RainLab\User\Models\User as FrontUser;

FrontUser::extend(function($model) {

    $model->belongsToMany['friends']=[
        'RainLab\User\Models\User',
        'table'    => 'meysam_social_friends',
        'pivot' => ['status'],
        'pivotModel' => 'Meysam\Social\Models\FriendsPivot',
        'timestamps' => true,
        'key'      => 'user_id',
        'otherKey' => 'friend_id'
    ];

    $model->addDynamicMethod('isFriendWith', function (FrontUser $user) use ($model) {
        $model->friends->contains($user->id);
    });

    $model->addDynamicMethod('addFriend', function (FrontUser $user) use ($model) {
        $model->friends()->attach($user->id);
    });

    $model->addDynamicMethod('removeFriend', function (FrontUser $user) use ($model) {
        $model->friends()->detach($user->id);
    });
});

And also extended the Rainlab.User Controller to have Friends tab where all friends of a user are listed and can be added and removed:
use RainLab\User\Controllers\Users as UsersController;

UsersController::extend(function($controller) {

    if(!isset($controller->implement['Backend.Behaviors.RelationController'])) {
        $controller->implement[] = 'Backend.Behaviors.RelationController';
    }
    $controller->relationConfig  =  '$/meysam/social/controllers/user/config_relations.yaml';
});

UsersController::extendFormFields(function($form, $model, $context) {
    if(!$model instanceof FrontUser or $context != 'preview'){
        // friends tab should not be displayed in update and create contexts
        return;
    }

    $form->addTabFields([
        'friends' => [
            'label' => '',
            'tab' => 'Friends',
            'type' => 'partial',
            'path' => '$/meysam/social/controllers/user/_friends.htm',
        ]
    ]);
});

Now I need to maintain a two-way friendship relationship. i.e. whenever user_id and friend_id is added to the friends table, I want to automatically add friend_id and user_id to the table as well. To achieve this, I implemented afterSave and beforeSave in the FriendsPivot model:
class FriendsPivot extends Pivot
{
    /*
     * Validation
     */
    public $rules = [
        'status' => 'required'
    ];

    public $belongsTo = [
        'user' => ['RainLab\User\Models\User', 'key' => 'user_id'],
        'friend' => ['RainLab\User\Models\User', 'key' => 'friend_id']
    ];

    public function getStatusOptions()
    {
        return [
            1 => 'Pending',
            2 => 'Approved',
            3 => 'Blocked',
        ];
    }

    public function afterSave()
    {
        Log::info('Saving pivot...');

        if(!$this->friend->isFriendWith($this->user)) {
            $this->friend->addFriend($this->user);
        }
    }

    public function beforeDelete()
    {
        Log::info('Deleting pivot...');

        if($this->friend->isFriendWith($this->user)) {
            $this->friend->removeFriend($this->user);
        }
    }
}

The problem is that beforeDelete is never called. afterSave gets called but beforeDelete never gets called and therefor the inverse of the relationship is not deleted (user_id-friend_id gets removed from database but friend_id-user_id does not get deleted). Why is beforeDelete not called? Is there anything I'm doing wrong? Is there any better way to maintain a two-way friendship relation?

A: I found this post because I'm trying to do exactly the same thing as you. If you have solved this then I wonder if you would be willing to share your solution?

A: This sounds very odd at first, but maybe this is because of the special delete behavior of the Pivot model. It appears that it builds a raw query using the QueryBuilder and thus bypasses any regular Eloquent (October) events.
In my eyes, the best solution would be to trigger the delete event manually in the delete method, but I'm unsure if this has any side effects.
Maybe you could test that and prepare a PR on Github if it works.


text:
Q: Programmatically format the java code using java I would like to format strings which contains codes like:
 "function() { for(i=0;i<n;i++){ return i; }}"

The point is to put new lines to each ; except in the for loop, so the formatted output should be something like this:
function() {
   for(i=0;i<n;i++){
    return i;
  }
 }

Is there any written function for this, or I have to loop through the whole string?

A: You have to use google-java-format-1.5.jar and google-java-format-1.5-all-deps.jar
and see the below example code
public class Main {
   public static void main(String[] args) {
      Formatter formatter = new Formatter();
      try {
        System.out.println(formatter.formatSource("public class Test{public static void main(String[] args) {String s;}}"));
      } catch (FormatterException e) {
        e.printStackTrace();
    }
 }

}

and output will be
public class Test {
  public static void main(String[] args) {
     String s;
  }
}

Sample working code

Hope this would helps to you


text:
Q: Do these sentences in "Algorithms 4th Edition" contain an errata? ("Algorithms 4th Edition" by Robert Sedgewick and Kevin Wayne) I am reading "Algorithms 4th Edition" by Robert Sedgewick and Kevin Wayne.
I am reading a section about Network-flow algorithms

Recall from SECTION 4.3 that a cut in a graph is a partition of the vertices into two disjoint sets, and a crossing edge is an edge that connects a vertex in one set to a vertex in the other set. For flow networks, we refine these definitions as follows:
Definition. An $st$-cut is a cut that places vertex $s$ in one of its sets and vertex $t$ in the other.
Each crossing edge corresponding to an $st$-cut is either an $st$-edge that goes from a vertex in the set containing $s$ to a vertex in the set containing $t$, or a $ts$-edge that goes in the other direction. We sometimes refer to the set of crossing $st$-edges as a cut set. The capacity of an $st$-cut in a flow network is the sum of the capacities of that cut's $st$-edges, and the flow across an $st$-cut is the difference between the sum of the flows in that cut's $st$-edges and the sum of the flows in that cut's $ts$-edges. Removing all the $st$-edges (the cut set) in an $st$-cut of a network leaves no path from $s$ to $t$, but adding any one of them back could create such a path.

Removing all the $st$-edges ($=\{e_1,e_3,e_4\}$) in an $st$-cut of the following network leaves no path from $s$ to $t$, and adding $e_1$ back cannot create such a path.
Do the above sentences in "Algorithms 4th Edition" contain an errata?

A: There's a couple of ways you could read that sentence, so (as mentioned in the comments) Sedgewick and Wayne are not necessarily making a false claim. Regardless, it is the case that:

*

*In an arbitrary $s-t$ cut, as the example in the question shows, not every edge in the cut set is part of an $s-t$ path.

*However, whenever an edge in the cut set is not part of an $s-t$ path, this can be exploited to generate a smaller cut. So in the minimum cut, every edge in the cut set will be part of an $s-t$ path.

We are usually most concerned with the minimum cut, so we don't have to worry about this issue too much either way.
To prove claim 2, let $(S,T)$ be the partition defining the cut, and let $vw$ be an edge in the cut set such that there is no $s-t$ path using $vw$ and no other edge in the cut set. Then let $W$ be the set of vertices in the subgraph $G[T]$ reachable from $w$, and define the new cut $(S \cup W, T - W)$. By construction, there are no edges from $W$ to $T-W$, so the cut set does not gain any new edges. However, edge $vw$ is removed from the cut set, so the new cut has a lower capacity. Similarly, if there is no $s-v$ path in $G[S]$, then let $V$ be the set of all vertices in the subgraph $G[S]$ that can reach $v$, and define the new cut set $(S - V, T \cup V)$; this will have lower capacity by the same argument.


text:
Q: Cross table constraints in PostgreSQL Using PostgreSQL 9.2.4, I have a table users with a 1:many relation to the table user_roles. The users table stores both employees and other kinds of users.
                                       Table "public.users"
    Column       |            Type   |                      Modifiers
-----------------+-------------------+-----------------------------------------------------
 uid             | integer           | not null default nextval('users_uid_seq'::regclass)
 employee_number | character varying |
 name            | character varying |

Indexes:
    "users_pkey" PRIMARY KEY, btree (uid)
Referenced by:
    TABLE "user_roles" CONSTRAINT "user_roles_uid_fkey" FOREIGN KEY (uid) REFERENCES users(uid)

                                      Table "public.user_roles"
    Column |            Type   |                            Modifiers
-----------+-------------------+------------------------------------------------------------------
 id        | integer           | not null default nextval('user_roles_id_seq'::regclass)
 uid       | integer           |
 role      | character varying | not null
Indexes:
    "user_roles_pkey" PRIMARY KEY, btree (id)
Foreign-key constraints:
    "user_roles_uid_fkey" FOREIGN KEY (uid) REFERENCES users(uid)

I want to ensure that the column users.employee_number cannot be NULL if there is a related row where user_roles.role_name contains an employee role name. That is, I want the database to enforce the constraint that for some roles, users.employee_number must have a value, but not for others.
How can I accomplish this, preferably without user-defined functions or triggers? I found (blog post, SO Answer) that SQL Server supports indexed views, which sounds like it would serve my purpose. However, I assume that materialized views will not work in my case, since they are not dynamically updated.

A: Clarifications
The formulation of this requirement leaves room for interpretation:
where UserRole.role_name contains an employee role name.
My interpretation:
with an entry in UserRole that has role_name = 'employee'.
Your naming convention is was problematic (updated now). User is a reserved word in standard SQL and Postgres. It's illegal as identifier unless double-quoted - which would be ill-advised. User legal names so you don't have to double-quote.
I am using trouble-free identifiers in my implementation.
The problem
FOREIGN KEY and CHECK constraint are the proven, air-tight tools to enforce relational integrity. Triggers are powerful, useful and versatile features but more sophisticated, less strict and with more room for design errors and corner cases.
Your case is difficult because a FK constraint seems impossible at first: it requires a PRIMARY KEY or UNIQUE constraint to reference - neither allows NULL values. There are no partial FK constraints, the only escape from strict referential integrity are NULL values in the referencing columns due to the default MATCH SIMPLE behavior of FK constraints. Per documentation:

MATCH SIMPLE allows any of the foreign key columns to be null; if any
  of them are null, the row is not required to have a match in the referenced table.

Related answer on dba.SE with more:

*

*Two-column foreign key constraint only when third column is NOT NULL
The workaround is to introduce a boolean flag is_employee to mark employees on both sides, defined NOT NULL in users, but allowed to be NULL in user_role:
Solution
This enforces your requirements exactly, while keeping noise and overhead to a minimum:
CREATE TABLE users (
   users_id    serial PRIMARY KEY
 , employee_nr int
 , is_employee bool NOT NULL DEFAULT false
 , CONSTRAINT role_employee CHECK (employee_nr IS NOT NULL = is_employee)
 , UNIQUE (is_employee, users_id)  -- required for FK (otherwise redundant)
);

CREATE TABLE user_role (
   user_role_id serial PRIMARY KEY
 , users_id     int NOT NULL REFERENCES users
 , role_name    text NOT NULL
 , is_employee  bool CHECK(is_employee)
 , CONSTRAINT role_employee
   CHECK (role_name <> 'employee' OR is_employee IS TRUE)
 , CONSTRAINT role_employee_requires_employee_nr_fk
   FOREIGN KEY (is_employee, users_id) REFERENCES users(is_employee, users_id)
);

That's all.
These triggers are optional but recommended for convenience to set the added tags is_employee automatically and you don't have to do anything extra:
-- users
CREATE OR REPLACE FUNCTION trg_users_insup_bef()
  RETURNS trigger AS
$func$
BEGIN
   NEW.is_employee = (NEW.employee_nr IS NOT NULL);
   RETURN NEW;
END
$func$ LANGUAGE plpgsql;

CREATE TRIGGER insup_bef
BEFORE INSERT OR UPDATE OF employee_nr ON users
FOR EACH ROW
EXECUTE PROCEDURE trg_users_insup_bef();

-- user_role
CREATE OR REPLACE FUNCTION trg_user_role_insup_bef()
  RETURNS trigger AS
$func$
BEGIN
   NEW.is_employee = true;
   RETURN NEW;
END
$func$ LANGUAGE plpgsql;

CREATE TRIGGER insup_bef
BEFORE INSERT OR UPDATE OF role_name ON user_role
FOR EACH ROW
WHEN (NEW.role_name = 'employee')
EXECUTE PROCEDURE trg_user_role_insup_bef();

Again, no-nonsense, optimized and only called when needed.
SQL Fiddle demo for Postgres 9.3. Should work with Postgres 9.1+.
Major points

*

*Now, if we want to set user_role.role_name = 'employee', then there has to be a matching user.employee_nr first.

*You can still add an employee_nr to any user, and you can (then) still tag any user_role with is_employee, irregardless of the actual role_name. Easy to disallow if you need to, but this implementation does not introduce any more restrictions than required.

*users.is_employee can only be true or false and is forced to reflect the existence of an employee_nr by the CHECK constraint. The trigger keeps the column in sync automatically. You could allow false additionally for other purposes with only minor updates to the design.

*The rules for user_role.is_employee are slightly different: it must be true if role_name = 'employee'. Enforced by a CHECK constraint and set automatically by the trigger again. But it's allowed to change role_name to something else and still keep is_employee. Nobody said a user with an employee_nr is required to have an according entry in user_role, just the other way round! Again, easy to enforce additionally if needed.

*If there are other triggers that could interfere, consider this:
How To Avoid Looping Trigger Calls In PostgreSQL 9.2.1
But we need not worry that rules might be violated because the above triggers are only for convenience. The rules per se are enforce with CHECK and FK constraints, which allow no exceptions.

*Aside: I put the column is_employee first in the constraint UNIQUE (is_employee, users_id) for a reason. users_id is already covered in the PK, so it can take second place here:
DB associative entities and indexing

A: First, you can solve this using a trigger.
But, I think you can solve this using constraints, with just a little weirdness:
create table UserRoles (
    UserRoleId int not null primary key,
    . . .
    NeedsEmployeeNumber boolean not null,
    . . .
);

create table Users (
    . . .
    UserRoleId int,
    NeedsEmployeeNumber boolean,
    EmployeeNumber,
    foreign key (UserRoleId, NeedsEmployeeNumber) references UserRoles(UserRoleId, NeedsEmployeeNumber),
    check ((NeedsEmployeeNumber and EmployeeNumber is not null) or
           (not NeedsEmployeeNumber and EmployeeNumber is null)
          )
);

This should work, but it is an awkward solution:

*

*When you add a role to an employee, you need to add the flag along with the role.

*If a role is updated to change the flag, then this needs to be propagated to existing records -- and the propagation cannot be automatic because you also need to potentially set EmployeeNumber.

A: New Answer:
This( SQL Sub queries in check constraint ) seems to answer your question, and the language is still in the 9.4 documentation( http://www.postgresql.org/docs/9.4/interactive/sql-createtable.html ).
Old Answer:
SELECT
  User.*
  , UserRole1.*
FROM
 User
  LEFT JOIN UserRole UserRole1
    ON User.id = UserRole1.UserId
     AND (
      (
       User.employee_number IS NOT NULL AND UserRole1.role_name IN (enumerate employee role names here)
      )
     OR
      (User.employee_number IS NULL)
     )

The above query selects all fields from User and all fields from UserRole(aliased as UserRole1).  I assumed that the key field between the two fields is known as User.id and UserRole1.UserId, please change these to whatever the real values are.
In the JOIN part of the query there is an OR that on the left side requires an employee number not be NULL in the user table and that UserRole1.role_name be in a list that you must supply to the IN () operator.
The right part of the JOIN is the opposite, it requires that User.employee_number be NULL(this should be your non-employee set).
If you require a more exact solution then please provide more details on your table structures and what roles must be selected for employees.


text:
Q: AWK split output with the line How can I split output lines using tailf and awk like this?
From this:
tail -f logfile.log | awk '/connected/ {print "\033[31m" $0 "\033[39m"}'

Output:
2018-01-31 10:00 user connected autentication successful
2018-01-31 10:10 user connected autentication successful
2018-01-31 10:23 user connected autentication successful
2018-01-31 10:34 user connected autentication unsuccessful
2018-01-31 10:35 user connected autentication unsuccessful

To this output:
2018-01-31 10:00 user connected autentication successful
----------------------------------------------------------
2018-01-31 10:10 user connected autentication successful
----------------------------------------------------------
2018-01-31 10:23 user connected autentication successful
----------------------------------------------------------
2018-01-31 10:34 user connected autentication unsuccessful
----------------------------------------------------------
2018-01-31 10:35 user connected autentication unsuccessful

Thanks in advance!

A: If you want the separator lines to be white:
tail -f logfile.log | awk '/connected/ {print "\033[31m" $0 "\033[39m\n-----------------------------------"}'

If you want the separator line to be red:
tail -f logfile.log | awk '/connected/ {print "\033[31m" $0 "\n-----------------------------------\033[39m"}'

A: If all you want to do is print ---------------------------------------------------------- after every line, set the ORS (output record separator) to whatever you want to come after every line:
$ awk -v ORS='\033[39m\n----------------------------------------------------------\n' '/connected/ {print "\033[31m" $0}' foo
2018-01-31 10:00 user connected autentication successful
----------------------------------------------------------
2018-01-31 10:10 user connected autentication successful
----------------------------------------------------------
2018-01-31 10:23 user connected autentication successful
----------------------------------------------------------
2018-01-31 10:34 user connected autentication unsuccessful
----------------------------------------------------------
2018-01-31 10:35 user connected autentication unsuccessful
----------------------------------------------------------

Here, I moved the \033[39m to the ORS from the print command, and surrounded the hyphens with newlines (\n).


text:
Q: Understanding "runwithfriends" facebook-app sample code this is my first web-programming experience so I hope my questions doesn't sound very dumb. I have been stucked on this for many days.
I am trying to understand a sample code:
https://github.com/facebook/runwithfriends
However I am not understanding very well how the information flow works and how can I modify that sample (i.e. how the code works).
For example, in the following section of the code:
class RecentRunsHandler(BaseHandler):
"""Show recent runs for the user and friends"""
def get(self):
    if self.user:
        friends = {}
        for friend in select_random(
                User.get_by_key_name(self.user.friends), 30):
            friends[friend.user_id] = friend

        self.render(u'runs',
            friends=friends,
            user_recent_runs=Run.find_by_user_ids(
                [self.user.user_id], limit=5),
            friends_runs=Run.find_by_user_ids(friends.keys()),
        )
    else:
        self.render(u'welcome')

As I understand (along with HTML) is useful for showing friends that are using the same app, and if I understand correctly, here is the essential part:
*friends_runs=Run.find_by_user_ids(friends.keys())*
But what if I want to show any given friend. How can I do it?
Summarizing, I would like to know:
1- How the flow of the code works? (I don't fully understand the explanation here)
2- How can I manipulate the code so to get, for example, to show a list of friends of the user (not necessary that use the same app)?
Moreover, Can I show friends filtered by some characteristic (for example, gender)?
Thanks a lot!

A: The python "SDK" for facebook I use I took from https://gist.github.com/1190267
and combined it with the code from the example app to achieve the functionality I wanted both for a canvas app and for website usage.
It depends whether you're using facebook with websites or a canvas application. For a canvas application you probably could do well with the javascript SDK but for a "login with facebook" I required serverside logic that should work with javascript turned off so I've completed that solution with details you might have help to know. You can try make small changes of that specific app 'runwithfriends' to get an understanding which code does what. The project you're looking at contains some outdated practice though:

*

*getting and setting cookies is likely preferable now doing with webapp2's builtin functions for this instead of the code that comes with the FB example app

*logging in and out is now done with OAuth 2.0 so it's likely that the login system you're looking at is outdated and you need to use OAuth 2.0 which is described here. I much rather do login/logout serverside so I did an OAuth 2.0 pure python solution to login / logout following the authentication steps mentioned in the tutorial from FB. I had to clear the cookie to log a user out which was not documented.

*To upgrade to python 2.7 I had to also modify so that HTTP header did not cast to unicode. I don't know why but otherwise it complained that headers were "not strings"
To more elaborately answer your specific questions:
1) The requesthandler class you posted is a subclass of a BaseHandler so to fully understand what it does you can look at the BaseHandler class since what you are posting is a BAseHandler. The BaseHandler uses django templates for rendering and if you want to can switch the template engine to jinja2 which is remmended. Further the code accesses the user object inherited from the BaseHandler and does some operations on it and renders it to a template. You can try make a requesthandler of your own, subclass BaseHandler and do what you want.
2) I could manipulate the code and I'm not an expert so you should be able to do it too. I wanted a simple FB app to display random images and I could manipulate it to select random images via blobs and render to to a template while keeping the facebook base functions. A function to use for getting the user using the Graph API I do this:
def parse_signed_request(signed_request, secret):
    """
    Parse signed_request given by Facebook (usually via POST),
    decrypt with app secret.

    Arguments:
    signed_request -- Facebook's signed request given through POST
    secret -- Application's app_secret required to decrpyt signed_request
    """

    if '.' in signed_request:
        (esig, payload) = signed_request.split('.')
    else:
        return {}

    sig = urlsafe_b64decode(str(esig))
    data = _parse_json(urlsafe_b64decode(str(payload)))

    if not isinstance(data, dict):
        raise SignedRequestError('Pyload is not a json string!')
        return {}

    if data['algorithm'].upper() == 'HMAC-SHA256':
        if hmac.new(secret, payload, hashlib.sha256).digest() == sig:
            return data
    else:

        raise SignedRequestError('Not HMAC-SHA256 encrypted!')

    return {}

def get_user_from_cookie(cookies, app_id, app_secret):
    """Parses the cookie set by the official Facebook JavaScript SDK.

    cookies should be a dictionary-like object mapping cookie names to
    cookie values.

    If the user is logged in via Facebook, we return a dictionary with the
    keys "uid" and "access_token". The former is the user's Facebook ID,
    and the latter can be used to make authenticated requests to the Graph API.
    If the user is not logged in, we return None.

    Download the official Facebook JavaScript SDK at
    http://github.com/facebook/connect-js/. Read more about Facebook
    authentication at http://developers.facebook.com/docs/authentication/.
    """
    cookie = cookies.get('fbsr_' + app_id, '')
    if not cookie:
        return None
    response = parse_signed_request(cookie, app_secret)
    if not response:
        return None

    args = dict(code=response['code'], client_id=app_id,
                client_secret=app_secret, redirect_uri='')

    file = \
        urllib.urlopen('https://graph.facebook.com/oauth/access_token?'
                       + urllib.urlencode(args))
    try:
        token_response = file.read()
    finally:
        file.close()

    access_token = cgi.parse_qs(token_response)['access_token'][-1]
    logging.debug('returning cookie')
    return dict(uid=response['user_id'], access_token=access_token)

See http://developers.facebook.com/docs/api for complete documentation for the API. And you can get the the official Facebook JavaScript SDK at http://github.com/facebook/connect-js/
I'm now writing code to sync a webapp2_extras.auth account with facebook so that custom accounts and facebook accounts can co-exist and we're discussing solutions for this in the webapp2 groups and categories. The current way I do it is adding the recommended current_user to a basehandler and using that as the FB identity while working on "merging" my class FBUser that is a custom class for facebook users that autheorized my website and/or canvas application to sync with webapp2_extras.auth.models.User which is an expando model so it can just add the properties it doesn't have such as facebookid, firstname, lastname, etc.
@property
def current_user(self):
    if not hasattr(self, '_current_user'):
        self._current_user = None
        cookie = get_user_from_cookie(self.request.cookies,
                facebookconf.FACEBOOK_APP_ID,
                facebookconf.FACEBOOK_APP_SECRET)
        if cookie:

            # Store a local instance of the user data so we don't need
            # a round-trip to Facebook on every request
            user = FBUser.get_by_key_name(cookie['uid'])
            if not user:
                graph = GraphAPI(cookie['access_token'])
                profile = graph.get_object('me')
                user = FBUser(key_name=str(profile['id']),
                              id=str(profile['id']),
                              name=profile['name'],
                              profile_url=profile['link'],
                              access_token=cookie['access_token'])
                user.put()
            elif user.access_token != cookie['access_token']:
                user.access_token = cookie['access_token']
                user.put()
            self._current_user = user
    return self._current_user

You can also solve your authentication with session objects and build your authentication system around that. That is what I do when using both custom accounts and facebook accounts and you're welcome to have a lok at my repository for more code examples how to intregrate facebook with google app engine using python 2.7.


text:
Q: Bluetooth headset connects, but provides no audio input option I have a bluetooth headset that I would like to use with Skype. It used to work perfectly a few Ubuntu versions ago. Then one day it stopped working, and it seems there were kernel bugs or something. I gave up on it for maybe half a year or more.
Recently, I thought I'd give it another go. On the upside, my headset seems to connect to my computer without any trouble:

However, when I open Skype, it does not see the headset at all. There is only one Pulseaudio option, which is network sound server, not my headset.

The bluetooth headset also does not seem to appear anywhere in my sound settings.

How do I get Skype to recognize my bluetooth headset?


text:
Q: With matplotlib for Python, how to plot a dot in the center of cells that were created with pcolor? I am using matplotlib.pyplot.pcolor to plot a 2D grid like the following:
PL.pcolor(array, cmap = PL.cm.YlOrRd, vmin = 0, vmax = 3)

Where array is just a simple 2D array. That part works fine. But next I try:
PL.hold(True)
PL.scatter(x, y, 'blue')
PL.hold(False)

Where x and y are the coordinates where I want a given dot to be plotted. However, instead of getting plotted in the center of the cells of the grid that is plotted with pcolor, the dot gets to the corner of the cells (no matter which cell I choose).

A: You can use meshgrid to generate the mesh of points. If your sampling x and y are uniform, then just add the separation divided by two in each direction. i.e. if separation is 1, then add 0.5 and subtract one point:
import numpy as np
import matplotlib.pyplot as plt
r = np.arange(10)
p = np.arange(10)
R,P = np.meshgrid(r,p)
data = np.random.random((10,10))
plt.pcolor(R,P,data)
plt.scatter(R[:-1,:-1]+0.5,P[:-1,:-1]+0.5, color = 'blue')

This is in case you use tripcolor:
You can calculate the centroid of your points: triang.triangles gives you the three point indexes of each triangle, then you calculate the centroid using those three points. i.e. centroidX = (x1+x2+x3)/3.; centroidY = (y1+y2+y3)/3.;
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.tri as tri
x = np.random.random(10)
y = np.random.random(10)
z = np.random.random(10)
triang = tri.Triangulation(x, y)
plt.tripcolor(triang,z)
centroidX = [x[i].sum()/3. for i in triang.triangles]
centroidY = [y[i].sum()/3. for i in triang.triangles]
plt.scatter(centroidX,centroidY, color = 'blue')


text:
Q: How to SELECT data from a table that displays a new column as a percent increase in data from an old column? I am learning SQL and I've been stumped on this question from my book for awhile now.
The questions in this book are asked in a way that I am the DBA for a book store.
So, I have all these tables (Books, Author, Publisher, Customer, Order, etc.) I assume were created by the author of this book (Oracle 11g by Joan Casteel).
This question asks me:

Management is proposing to increase the price of each book. The amount of the increase will be based on each book's category, according to the following scale: Computer books, 10%,Fitness books, 15%, Self-Help books, 25%, all other categories, 3%. Create a list that displays each book's title, category, current retail price, and revised retail price. The prices should be displayed with two decimal places. The column headings for the output should be as follows: Title, Category, Current Price, and Revised Price. Sort the results by category. If there's more than one book in a category, a secondary sort should be performed on the book's title.
Create a document to show management the SELECT statement used to generate the results and the results of the statement.

So I know in my SQL statement I need to SELECT the title of these books, category of the books, current retail price of the books, and a revised retail price of the books. For this revised retail price, I need to display a % increase of the old retail price, and do this by category.
This is what I have started doing:
SELECT title, category, retail AS "Current Price", retail + (10/100) AS "New Price"
FROM books
WHERE category = 'COMPUTER';

When I do this though, I only get results from the COMPUTER category of books and I need results from all categories and display the % increase in price by category.
How do I do it so that I can create that next column as "New Price" and display ALL of the books with their specific % increase in retail price according to the category of book?

A: You could use a CASE statement to do this.
SELECT title, category, retail AS "Current Price", retail * CASE category WHEN 'COMPUTER' THEN 1.1 WHEN 'FITNESS' THEN 1.15 ELSE 1.03 END AS "New Price"
FROM books

I didn't fill in all the categories and you'll want to check to make sure you know exactly how they are formatted in your field.

A: Do this:
SELECT title, category, retail AS "Current Price", retail + (10/100) AS "Revised Price"
FROM books
WHERE category IN ('COMPUTER', 'FITNESS', 'SELF HELP');


text:
Q: Hibernate restriction in causes an error if the list is empty If my list is empty, I get the following error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')'

Below is my hibernate related method:
  @Override
    public List<SomeThing> findByIds(List<Integer> someIds) {
        return sessionFactory.getCurrentSession().createCriteria(SomeClass.class)
                .add(Restrictions.in("id", someIds))
                .list();
    }

What should I do to guard against this error?
I know I could short-circuit the call and return an empty list like:
if(someIds == null || someIds.size() == 0) {
  return new List<SomeThing>();
}

But is there a more elegant way to do this?

A: (This is mostly base on @Yogendra Singh's reply, with a twist to make it more adoptable to commonly-seen situation of multiple optional argument)
Criteria API aims to let you compose your query programmatically.  Such kind of dynamic feature is expected to be handled in your code.
Normally we make optional criteria by this:
@Override
public List<SomeThing> findBySearchParams(SearchParam searchParam) {
   // create criteria with mandatory search criteria
   Criteria criteria = sessionFactory.getCurrentSession()
                           .createCriteria(SomeClass.class);
                           .add(Restriction("someField", searchParam.getSomeField()));

   // add "id" only if "someId" contains value
   if(searchParam.getSomeIds() != null && !searchParam.getSomeIds().empty()) {
       criteria.add(Restrictions.in("id", searchParam.getSomeIds()));
   }

   // add "anotherField" only if "anOptionalField" is not null
   if(searchParam.getAnOptionalField() != null) {
       criteria.add(Restrictions.in("anotherField", searchParam.getAnOptionalField()));
   }

   return criteria.list();
}

Edit:
Although Hibernate does not (yet) provide a more elegant way for that, you can write something yourself to make it looks more elegant:
class SmartCriteriaBuilder {
  private Criteria criteria;
  SmartCriteriaBuilder (Criteria criteria) { this.criteria = criteria;}

  SmartCriteriaBuilder in(String field, Collection values) {
    if (!empty(values)) {
      this.criteria.add(Restrictions.in(field,values));
    }
  }
  // all other kind of restrictions ....

  Criteria toCriteria() {
    return this.criteria;
  }
}

Then you can do something looks smarter:
SmartCriteriaBuilder criteriaBuilder =
    new SmartCriteriaBuilder(sessionFactory.getCurrentSession().createCriteria());

criteriaBuilder .in("someField", listPossiblyNullOrEmpty);

return criteriaBuilder .toCriteria().list();

A: NO. If you execute the query with empty parameters for in clause, it will fail (you may verify this by running plain SQL). Better not to execute the query if the input param is null/empty.
Only thing I can advice is  to use isEmpty() function and != null in if statement and little restructuring as:
@Override
public List<SomeThing> findByIds(List<Integer> someIds) {
   List<Something> result = null; //you may initialize with empty list
   if(someIds != null || !someIds.isEmpty() {
       result = sessionFactory.getCurrentSession().createCriteria(SomeClass.class)
            .add(Restrictions.in("id", someIds))
            .list();
   }
   return result;
}

A: I would say Hibernate needs to fix this issue, and give meaningful message.
I think its responsibility of the provider/hibernate to check for the empty/null List.
One can imagine the cause, it tries to construct where clause, something like id in (), somewhere in org.hibernate.loader.criteria.CriteriaQueryTranslator or similar..But because here the List is empty, it would be throwing an exception. But they already created query with ( and could not complete because of exception/empty List.


text:
Q: ASP.NET Core Register the service to run on hostnames other than localhost My app responds to port  5000, but only responds on localhost. How can I change the code so it will response not only to localhost but something like: https://*:5000
I need it so I will be able to deploy on Kubernetes and access it on port 5000 not only with localhost.
Program.cs code below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace myWebApp
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }
}

A: I know this is now an old question, but if anyone else is struggling with this:  try deploying to 0.0.0.0:5000 instead of localhost:5000 or 127.0.0.1:5000.  This will allow external connections.

A: Your method CreateHostBuilder builds an application that listens to/responds to requests on port 5000. It is the default configuration for Kestrel web server. But this is pretty much all the application can control.
Now if you want your application to respond to http://anUrl.com then you will have to configure the network so that the computer (running the application, inside Kubernetes) is accessible at the given URL and the request send to the 5000 port. The application configuration does not control that.
If the network is the whole Web, then you'll have to register the URL to map to your computer's IP. It is done on DNS; and usually on the website you purchased your URL.

A: If you want to set up your app for Kubernetes, there are very different models that can be used there. But a very common one is that you will have an ingress controller that will do all the communication from external networks to you cluster. Depending on the host in the HTTP request it will then redirect it to your pod and application, so the app won't even know how the traffic reached it.
Basically the thing is that your application will answer on port 5000 regardless of how the traffic reaches the application. It's the job for the web server (or ingress controller in standard Kubernetes) to do everything else.
I suggest that you read what does DNS mean to understand the relationship better.
P.S. Short version: Your app should not know anything about the host really, so your code is just fine

A: I also stumbled over a similar case when I wanted to test my Web app over my mobile phone and in my local network. The thing here is this, before any app can connect to your app, if you want it to be run and accessed in debug mode then you have to use the port which your ASP.NET application is launched with.
Else to access it over the network or with another IP address while the application is hosted on your PC then you have to host it in a web server (ie IIS, nginx, kestrel), and then you can just assign it a range of ports which you want it to be accessed over.


text:
Q: Append file to the end of an archive in C Can someone point me to the right direction on how to append multiple files to an archive file in C?
Below is what I'm planning to do. Can you please let me know if it's the right way (if not, can you let me know which is a better way)?  Thanks a lot!
-Use OPEN to open the archive file (O_RDONLY | O_WRONLY | O_APPEND)
-Use WRITE to write the regular file to archive

A: You should hopefully have a system header file named ar.h (normally located in /usr/include/), if you check that you will see the format of the archive files.
Each file in the archive is a ar_hdr structure followed by the data of the file contents. So to append a file to the archive, you just write a correct structure followed by the contents of the file you want to append.

A: In order to add files (or even one file) to an archive file, you first need to know the format of the archive. If you've studied the documentation for the file format as provided by your OS, (as was advised in this answer to your previous question,) then you should already know enough about the file format that you shouldn't need to ask us how to do it.
C does not have functions named OPEN or WRITE. there are open() and write(), however,  be advised that O_RDONLY|O_WRONLY is not equivalent to O_RDWR. You could use write() to write the content of the file to the end of the archive, yes, but (a) don't forget to write the file header first, and (b) are you sure you don't need to update the archive's symbol table? (If you do, you may need to rewrite the entire file.)
Why aren't you just using the ar command-line utility, again?


text:
Q: Solution Like Trash Can Animation I would like to put the undocumented trash can animation in my program. The call
method is:
+ (void)animateToolbarItemIndex:(unsigned)index duration:(double)duration target:(id)target didFinishSelector:(SEL)selector;

Can anyone figure out what I should plug in for:

*

*index

*duration

*target

*selector
?

My trials are not working resulting in the error:
2011-11-15 16:05:20.639 CNiPhone[973:707] +[UIToolbar animateToolbarItemIndex:duration:target:didFinishSelector:]: unrecognized selector sent to class 0x3f019c08
2011-11-15 16:05:20.641 CNiPhone[973:707] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+[UIToolbar animateToolbarItemIndex:duration:target:didFinishSelector:]: unrecognized selector sent to class 0x3f019c08'

Here is the relevant code:
@interface UIToolbar (privateMethods2)

+ (void)animateToolbarItemIndex:(unsigned)index duration:(double)duration target:(id)target didFinishSelector:(SEL)selector;

@end

    [UIToolbar animateToolbarItemIndex:0 duration:0.5 target:trashToolbarButton didFinishSelector:@selector(animateTrashStep2)];
    [UIToolbar commitAnimations];

- (void) animateTrashStep2 {
}

A: You need to call it on the toolbar connected to your IBOutlet as opposed to the class. E.g.:
[self.myToolbar /*(possibly just myToolbar)*/ animateToolbarItemIndex:0 duration:0.5 target:trashToolbarButton didFinishSelector:@selector(animateTrashStep2)];

A: You dont need to do any undocumented stuff for this, just create a custom UIButton. Download the UIKit Artwork Extractor and you'll find the frames for the trash can animation, as well as the UIBarButtonItem background.

A: You will probably find the answer here: https://stackoverflow.com/a/5101910/796103

A: It's probably because your target is set to trashButtonItem.  The target is the object that the didFinishSelector will be sent to.  Try setting the target to self.  Also, according to http://iphonedevwiki.net/index.php/UIToolbar this is not a class method so you will need to replace the [UIToolbar with the actual toolbar object.
In your didFinishSelector callback I guess you call the method again and the trashcan will close.
Good luck.

A: This 'undocumented' method is documented here: http://iphonedevwiki.net/index.php/UIToolbar
It's documented as being an instance method and not a class method, which explains the error message you're receiving in the exception.
@jrtc27 has answered the question correctly, in that this should be sent to the UIToolbar instance instead.  From your reply to the comments, it seems that you have not changed your class category to assist the compiler.  Try the following instead:
@interface UIToolbar (privateMethods2)
- (void)animateToolbarItemIndex:(unsigned)index duration:(double)duration target:(id)target didFinishSelector:(SEL)selector;
@end

And then use:
[self.navigationController.toolbar animateToolbarItemIndex:0 duration:0 target:self.trashToolbarButton didFinishSelector:@selector(animateTrashStep2)];

A: I think if you know how to do the suckEffect, then you can do a little bit hacking with the toolbar.
Basically, all the official controls are a subclass of UIView, hence you can find out the view hierarchy of the UIToolBar instance.

If you don't know how to find out the subview hierarchy of a given view, you can use a PRIVATE API - (void)recursiveDescription from UIView. Remember to use it in DEBUG configuration.

Why should we bother the view hierarchy?
The answer is, to hide certain view, or to add a subview as we want.
What's next

*

*Find the origin UIBarButtonItem view of your trash can

*Before the suckEffect start, hide it, add a new trash can view which can do the animation of open/close/shaking. This moment I think you need to ask it to do open animation.

*Then let the suckEffect fly...

*After the suckEffect ended, ask your view to do the close animation.

*After the close animation is finished, remove your view, and reshow the original trash can view.

Possibility?
I haven't done it before, but I think it's a possible solution because creating an trash can view with open/close/shaking animation is easy.
Risk?
Anyway, this solution is like some kind of hacking without touching the private api, the risk is on your own.
Good luck.


text:
Q: Unit-tests and joda-time-android I used joda-time-android library's classes in my Presenter class and it must not have any Android dependencies. So I can't test it properly. I know that I can use Robolectric for this, but I want to keep out of this tool and my Presenter clean. Should I abandon JodaTime? Any other solution?

A: Well, joda-time-android does depend on the Android runtime in order to work. Using Robolectric for this seems like an okay use case, since you won't be interacting with Fragment, Activity and other UI classes from the Android SDK.
Since setting up Robolectric is kind of a pain, there's another option - you could use the Adapter pattern to create a common interface for the regular Java Joda time library and the Android version.
If that's possible and practical (depending on how much of the Joda time API you want to use), you can back your Adapter with joda-time-android when running the app, and back it with joda-time when running the unit tests. I imagine that you can make it use the Android concrete implementation from your Application's onCreate() method and the Java concrete implementation from your unit test's @Before, for example.

A: For Unit-tests we can use default java implementation of JodaTime library because it has the same package and classes as joda-time-android.
// for android
compile 'net.danlew:android.joda:2.9.3'

// joda-time for tests
testCompile 'joda-time:joda-time:2.9.3'

Works like a charm.
For other cases with other libraries see @npace's answer.