text:
Q: Gremlin: Find duplicates of a vertex by 'name' property and execute as list of 'id' The below code groups all userProfileTemplates by name, finds where there are duplicates and then projects the "name" of the userProfileTemplate where the count of name is > 1. I want to find duplicates by "name", but I want to execute it as a list of "Id" (Id is a property of userProfileTemplate). Any suggestions?
g.V().hasLabel('userProfileTemplate').group().by(values('name').fold()).unfold().filter(select(values).count(local).is(gt(1))).select(keys)unfold().project('Duplicate User Profiles')
Update: The below is executing a column named "value" with the multiple 'id' that correspond to the duplicate 'name', separated by commas in betweeen brackts.
g.V().hasLabel('userProfileTemplate').group().by('name').by('id').unfold().filter(select(values).count(local).is(gt(1))).select(values)
I would like to also execute a column that shows the corresponding 'name' for all duplicate ids.

A: It's almost what you already have, you only need to add another by().
g.V().hasLabel('userProfileTemplate').
  group().
    by('name').
    by('Id').
  unfold().
  filter(select(values).count(local).is(gt(1))).
  select(keys)


text:
Q: Playwright hook / callback / try-catch to handle the overall test timeout When the timeout specified as below in playwright.config.ts expires, Playwright simply blows away the browser.  How can I catch this timeout expiry in my Playwright test script, and handle it gracefully?  I would like to log the timeout and exit the test gracefully.
Thanks,
Sanjoy
// playwright.config.ts
import type { PlaywrightTestConfig } from '@playwright/test';
const config: PlaywrightTestConfig = {
  timeout: 60000, // Timeout is shared between all tests.

I would like a hook / callback that can log the timeout and close the browser gracefully.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using namespace spread over multiple module files in TypeScript I've started work on a large-scale typescript project.
Right from the outset, I want to keep my files organized (this project will be split between lots of developers so order is very necessary).
I have been attempting to use modules / namespaces and splitting classes out into separate files for each one, with a folder holding the namespace.
The file structure is:
app.ts
\Classes
---- \Animals
---- ---- Mammals.ts
---- ---- Reptiles.ts

I then attempt to import all files in that namespace in app.ts using something like: import * as Animals from "./Classes/Animals"
As for the namespace files themselves, I have tried the following, with no success:
namespace Animals {
    export class Mammals {
        constructor() {
        }
    }
}

and also:
module Animals {
    export class Reptiles {
        constructor() {
        }
    }
}

Unfortunately, the path is never recognized (as it points to a folder and not a single file). Is this even possible? Having all my classes from a single namespace in one file will result in files which are thousands of lines long and for this project that is not maintainable.
I have also noticed that TypeScript 1.5 has support for tsconfig.json - however, having to add each file manually to the map is a sure-fire way of introducing issues when developers start adding classes.
NOTE: I'm using Visual Studio 2015, TypeScript 1.5 (I believe, not sure how to verify). I also have ES6 support turned on.

A: If you have your own library and you want to export the multiple files like from namespace, you can do this:
// classes/animals/mammals.ts
export enum Mammals {
  cow = 'cow',
  goat = 'goat',
}

// classes/animals/reptiles.ts
export interface Reptile {
  isOurOverlord: boolean;
}
export function isOurOverlord(specimen: Reptile) { ... }

// classes/animals/index.ts
import * as mammals from './mammals';
import * as reptiles from './reptiles';
export { mammals, reptiles };

// classes/index.ts
import * as animals from './animals';
export { animals };

// app.ts
import { animals } from './classes';
const reptile: animals.reptiles.Reptile = {
  isOurOverlord: animals.reptiles.isOurOverlord(...),
}

edit: i.e. you don't need typescript's namespaces in order to use that super convenient syntax of animals.reptiles.Reptile for types and values animals.mammals.Mammals within the same "namespace".

A: Use re-exporting to create an external module that groups and exposes types from other modules:
// Classes/Animals.ts
export * from '.\Animals\Mammals';
export * from '.\Animals\Reptiles';

Then import the types from the new module as usual:
// app.ts
import * as Animals from '.\Classes\Animals'

let dog: Animals.Dog;
let snake: Animals.Snake;

Or
// app.ts
import { Dog, Snake } from '.\Classes\Animals'

let dog: Dog;
let snake: Snake;

A: Seems there is no way to do this using namespaces on their own (unless you want to use Module Augmentation and declare every new item to add separately); however, a namespace can be part of a class, which can be extended!  This is the best alternative I can find:
CoreLibraryTypes.ts
abstract class Types { }
namespace Types {
    export class TypeA { }
    export class TypeB { }
    export class TypeC { }
}
export { Types };

CoreTypesExtended.ts
import CoreLibraryTypes from "./CoreLibraryTypes";

abstract class Types extends CoreLibraryTypes { }
namespace Types {
    export class TypeD { }
    export class TypeE { }
    export class TypeF { }
}
export { Types };

The downside, of course, is that only the import of the second module will have the new types added.  The first module will remain as before. Ideally it would be nice to "update" a namespace of types with additional types (like from plugins), such that module augmentation was more naturally supported (instead of having to write it by hand), but I guess that will have to do until someone realizes augmentation of modules by manually declaring updated definitions is just a half-a$$ way to do what namespaces already do lol (including classes, as seen above, which can already use namespace merging as part of the class). ;)
Note: In the example above I used export { Types }; for a reason - this will allow others to augment my modules.  Augmentation is not supported for default exports (unless that is desired - sort of seals it virtually).

A: Found a way to achieve your goal but not with the namespace keyword.

*

*The "Animals" classes, Animal.ts & Mammal.ts & Reptile.ts under namespace.

*with index.ts for the barrel.

*animals.ts for namespace grouping.

Sample Classes:

index.ts (as barrel)

animals.ts (for namespace grouping)

And here you go of the concept of the namespace.

A: External modules imply that you load modules file by file. Both AMD and CommonJS do not have such thing as namespace. You can use some kind of postprocessing to bundle files in one module.

The following defines an internal module:
module Animals {
    export class Reptiles {
        constructor() {
        }
    }
}

You shouldn't use import for it. Animals.Reptiles is visible anywhere.   The only aim is to load scripts in the proper order (e.g. base classes before heritors). So you should list all files in ts.config or somewhere else. In my project I use bundles on folders and have a convention to add @ to filenames of base classes.
Another solution is to use external modules: AMD (RequireJS) or CommonJS (Browserify). In that case remove upper level module from declaration. If one file contains only one type you can export it as a root:
class Reptiles {
    constructor() {
    }
}

export = Reptiles;

You can refer module by file path:
import Reptilies = require('..\Animals\Reptilies')
var  reptile = new Reptile();

Or with new ES6 modules:
export class Reptiles {
    constructor() {
    }
}

import { Reptiles } from '..\Animals\Reptilies';


text:
Q: C check before writing to closed pipe Is there an easy way to check if a pipe is closed before writing to it in C? I have a child and parent process, and the parent has a pipe to write to the child. However, if the child closes the pipe and the parent tries to read - I get a broken pipe error.
So how can I check to make sure I can write to the pipe, so I can handle it as an error if I can't? Thanks!

A: A simple way to check would be to do a 0 byte write(2) to the pipe and check the return.  If you're catching SIGPIPE or checking for EPIPE, you get the error.  But that's just the same as if you go ahead and do your real write, checking for the error return.  So, just do the write and handle an error either in a signal handler (SIGPIPE) or, if the signal is ignored, by checking the error return from write.

A: How about just try to write and deal with the error? The same way you would for a write to a file or a database. I see no value in the idiom:
check if *this* is going to work
do *this*

You merely introduce a smaller, and harder to catch in testing, window of opportunity:
check if *this* is going to work
   child thinks "Ha, fooled you, I'm off now!"
do *this*, which now fails!


text:
Q: A Generic way to create a checkable context menu from a list of enum values I want to create a context menu where one of the menuItem would be a submenu with a choice among enum values.
I do not want to hard code any of the values from my enum into xaml because I want that any enum value changes would be automtically reflected in the UI without any intervention.
I want my menu to be a regular context menu without any artifact (I mean the appearance should be as a regular ContextMenu).
I've tried many ways without success. Each of my trial always misses something but mainly it seems that the main missing part is a converterParamter that could be bound to something.
I red:

*

*Creating a checkable context menu from a list of enum values

*WPF Multibinding to View Model

*Binding to Converter Parameter
This is my many trials and related code:
<Window x:Class="WpfContextMenuWithEnum.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:wpfContextMenuWithEnum="clr-namespace:WpfContextMenuWithEnum"
        xmlns:system="clr-namespace:System;assembly=mscorlib"
        xmlns:converter="clr-namespace:WpfContextMenuWithEnum.Converter"
        Title="MainWindow" Height="350" Width="525"
        Name="MyWindow">
    <Window.DataContext>
        <wpfContextMenuWithEnum:MainWindowModel></wpfContextMenuWithEnum:MainWindowModel>
    </Window.DataContext>

    <Window.Resources>
        <ObjectDataProvider x:Key="EnumChoiceProvider" MethodName="GetValues" ObjectType="{x:Type system:Enum}">
            <ObjectDataProvider.MethodParameters>
                <x:Type TypeName="wpfContextMenuWithEnum:EnumChoice"/>
            </ObjectDataProvider.MethodParameters>
        </ObjectDataProvider>

        <converter:EnumToBooleanConverter x:Key="EnumToBooleanConverter"></converter:EnumToBooleanConverter>
        <converter:MultiBind2ValueComparerConverter x:Key="MultiBind2ValueComparerConverter"></converter:MultiBind2ValueComparerConverter>
    </Window.Resources>

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"></RowDefinition>
        </Grid.RowDefinitions>

        <TextBox Text="Right click me">
            <TextBox.ContextMenu>
                <ContextMenu ItemsSource="{Binding Source={StaticResource EnumChoiceProvider}}">
                    <ContextMenu.ItemTemplate>
                        <DataTemplate>
                            <MenuItem IsCheckable="True" Header="{Binding Path=.}">
                                <MenuItem.IsChecked>
                                    <MultiBinding Converter="{StaticResource MultiBind2ValueComparerConverter}">
                                        <Binding Path="DataContext.ModelEnumChoice" RelativeSource="{RelativeSource FindAncestor, AncestorType={x:Type Window}}" />
                                        <Binding Path="." Mode="OneWay"></Binding>
                                    </MultiBinding>
                                </MenuItem.IsChecked>
                            </MenuItem>
                        </DataTemplate>
                    </ContextMenu.ItemTemplate>
                </ContextMenu>
            </TextBox.ContextMenu>
        </TextBox>
    </Grid>
</Window>

Enum:
using System.ComponentModel;

    namespace WpfContextMenuWithEnum
    {
        public enum EnumChoice
        {
            [Description("Default")]
            ChoiceDefault = 0, // easier if the default have value = 0

            [Description("<1>")]
            Choice1 = 1,

            [Description("<2>")]
            Choice2 = 2,
        }
    }

Converters:
using System;
using System.Windows;
using System.Windows.Data;

namespace WpfContextMenuWithEnum.Converter
{
    public class ConverterWrapperWithDependencyParameterConverter : DependencyObject, IValueConverter
    {
        public static readonly DependencyProperty ParameterProperty = DependencyProperty.Register("Parameter",
            typeof(object), typeof(ConverterWrapperWithDependencyParameterConverter));

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (parameter != null)
            {
                throw new ArgumentException("The parameter should be set directly as a property not into the Binding object.");
            }

            return Converter.Convert(value, targetType, Parameter, culture);
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (parameter != null)
            {
                throw new ArgumentException("The parameter should be set directly as a property not into the Binding object.");
            }

            return Converter.ConvertBack(value, targetType, Parameter, culture);
        }

        public object Parameter
        {
            get { return GetValue(ParameterProperty); }
            set { SetValue(ParameterProperty, value); }
        }

        public IValueConverter Converter { get; set; }
    }
}

using System;
using System.Windows.Data;

namespace WpfContextMenuWithEnum.Converter
{
    public class EnumToBooleanConverter : IValueConverter
    {
        // **********************************************************************
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return value.Equals(parameter);
        }

        // **********************************************************************
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return value.Equals(true) ? parameter : Binding.DoNothing;
        }

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

}

   using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Data;

    namespace WpfContextMenuWithEnum.Converter
    {
        public class MultiBind2ValueComparerConverter : IMultiValueConverter
        {
            public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
            {
                if (values.Length != 2)
                {
                    throw new ArgumentException("Can compare only 2 values together fo equality");
                }

                return (values[0].Equals(values[1]));
            }

            public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
            {
                // if ((bool)value == true)
                throw new NotImplementedException();
            }
        }
    }

Trial 1: MultiBindConverter ConvertBack can't work, it misses information.
<ContextMenu ItemsSource="{Binding Source={StaticResource EnumChoiceProvider}}">
            <ContextMenu.ItemTemplate>
                <DataTemplate>
                    <MenuItem IsCheckable="True" Header="{Binding Path=.}">
                        <MenuItem.IsChecked>
                            <MultiBinding Converter="{StaticResource MultiBind2ValueComparerConverter}">
                                <Binding Path="DataContext.ModelEnumChoice" RelativeSource="{RelativeSource FindAncestor, AncestorType={x:Type Window}}" />
                                <Binding Path="."></Binding>
                            </MultiBinding>
                        </MenuItem.IsChecked>
                    </MenuItem>
                </DataTemplate>
            </ContextMenu.ItemTemplate>
        </ContextMenu>

Trial 2: My ConverterParameter bind did not work at all. It never received any value
<ContextMenu ItemsSource="{Binding Source={StaticResource EnumChoiceProvider}}">
                    <ContextMenu.ItemTemplate>
                        <DataTemplate>
                            <MenuItem IsCheckable="True" Header="{Binding Path=.}">
                                <MenuItem.IsChecked>
                                    <Binding Path="DataContext.ModelEnumChoice" RelativeSource="{RelativeSource FindAncestor, AncestorType={x:Type Window}}">
                                        <Binding.Converter>
                                            <converter:ConverterWrapperWithDependencyParameterConverter Converter="{StaticResource EnumToBooleanConverter}"
                                                Parameter="{Binding Path=.}"/>
                                        </Binding.Converter>
                                    </Binding>
                                </MenuItem.IsChecked>
                            </MenuItem>
                        </DataTemplate>
                    </ContextMenu.ItemTemplate>
                </ContextMenu>

Trial 3:
With a listBox using template and SelectedItem but the UI is not as standard as it should be (an additional frame appears).

A: I add my solution as reference. Both solution (accepted answer and mine works fine). I created one in the meantime I was waiting for a valid complete answer. I think that Mikko has a more standard way of doing the job and should probably be easier to maintain. Mikko solution also show nice usages of few WPF tricks (Relaycommand, MultiBinding, ...).
The main advantage of my solution is the abstraction of the "complexity" by using generic code that simulate a collection of item representing each enum value and their properties (IsChecked, Name, DisplayName). All of that is hidden and does not require anything in the model.
But anyway, just as additional information...
<Window x:Class="WpfContextMenuWithEnum.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:wpfContextMenuWithEnum="clr-namespace:WpfContextMenuWithEnum"
        Title="MainWindow" Height="350" Width="525"
        Name="MyWindow">
    <Window.DataContext>
        <wpfContextMenuWithEnum:MainWindowModel></wpfContextMenuWithEnum:MainWindowModel>
    </Window.DataContext>

    <Window.Resources>
        <wpfContextMenuWithEnum:EnumWrapperIteratorAndSelector x:Key="EnumWrapperIteratorAndSelector"
                                                               Enum="{Binding DataContext.SelectedEnumChoice, Mode=TwoWay, ElementName=MyWindow}" />
    </Window.Resources>

    <Grid>
        <TextBox Text="Right click me">
            <TextBox.ContextMenu>
                <ContextMenu ItemsSource="{Binding Source={StaticResource EnumWrapperIteratorAndSelector}}">
                    <ContextMenu.ItemTemplate>
                        <DataTemplate>
                            <MenuItem IsCheckable="True" Header="{Binding DisplayName}" IsChecked="{Binding IsChecked}">
                            </MenuItem>
                        </DataTemplate>
                    </ContextMenu.ItemTemplate>
                </ContextMenu>
            </TextBox.ContextMenu>
        </TextBox>
    </Grid>
</Window>

Generic classes that could be used anywhere:
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Collections.Specialized;
    using System.ComponentModel;
    using System.Reflection;
    using System.Windows;

    namespace WpfContextMenuWithEnum
    {
        /// <summary>
        /// Note: Freezable is necessary otherwise binding will never occurs if EnumWrapperIteratorAndSelector is defined
        /// as resources. See article for more info:
        /// http://www.thomaslevesque.com/2011/03/21/wpf-how-to-bind-to-data-when-the-datacontext-is-not-inherited/
        ///  </summary>
        public class EnumWrapperIteratorAndSelector : Freezable, IEnumerable<EnumWrapperIteratorAndSelectorChoice>, INotifyCollectionChanged
        {
            // ******************************************************************
            public static readonly DependencyProperty EnumProperty =
                DependencyProperty.Register("Enum", typeof(Enum), typeof(EnumWrapperIteratorAndSelector), new PropertyMetadata(null, PropertyChangedCallback));

            ObservableCollection<EnumWrapperIteratorAndSelectorChoice> _allEnumValue = new ObservableCollection<EnumWrapperIteratorAndSelectorChoice>();

            // ******************************************************************
            private static void PropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
            {
                if (!(dependencyPropertyChangedEventArgs.NewValue is Enum))
                {
                    throw new ArgumentException("Only enum are supported.");
                }

                var me = dependencyObject as EnumWrapperIteratorAndSelector;
                if (me != null)
                {
                    if (dependencyPropertyChangedEventArgs.OldValue == null)
                    {
                        me.ResetWithNewEnum(dependencyPropertyChangedEventArgs.NewValue);
                    }
                    else
                    {
                        foreach(EnumWrapperIteratorAndSelectorChoice enumWrapperIteratorAndSelectorChoice in me._allEnumValue)
                        {
                            enumWrapperIteratorAndSelectorChoice.RaiseChangeIfAppropriate(dependencyPropertyChangedEventArgs);
                        }
                    }
                }
            }

            // ******************************************************************
            private void ResetWithNewEnum(object enumValue)
            {
                _allEnumValue.Clear();

                var enumType = Enum.GetType();
                foreach (Enum enumValueIter in Enum.GetValues(enumValue.GetType()))
                {
                    MemberInfo[] memberInfos = enumType.GetMember(enumValueIter.ToString());
                    if (memberInfos.Length > 0)
                    {
                        var desc = memberInfos[0].GetCustomAttribute<DescriptionAttribute>();
                        if (desc != null)
                        {
                            _allEnumValue.Add(new EnumWrapperIteratorAndSelectorChoice(this, enumValueIter, desc.Description));
                        }
                        else
                        {
                            _allEnumValue.Add(new EnumWrapperIteratorAndSelectorChoice(this, enumValueIter));
                        }
                    }
                }
            }

            // ******************************************************************
            public Enum Enum
            {
                get { return (Enum)GetValue(EnumProperty); }
                set
                {
                    SetValue(EnumProperty, value);
                }
            }

            // ******************************************************************
            internal void SetCurrentValue(Enum enumValue)
            {
                SetCurrentValue(EnumProperty, enumValue);
            }

            // ******************************************************************
            public IEnumerator GetEnumerator()
            {
                return _allEnumValue.GetEnumerator();
            }

            // ******************************************************************
            IEnumerator<EnumWrapperIteratorAndSelectorChoice> IEnumerable<EnumWrapperIteratorAndSelectorChoice>.GetEnumerator()
            {
                return _allEnumValue.GetEnumerator();
            }

            // ******************************************************************
            public event NotifyCollectionChangedEventHandler CollectionChanged
            {
                add { _allEnumValue.CollectionChanged += value; }
                remove { _allEnumValue.CollectionChanged -= value; }
            }

            // ******************************************************************
            protected override Freezable CreateInstanceCore()
            {
                return new EnumWrapperIteratorAndSelector();
            }

            // ******************************************************************

        }
    }

    using System;
    using System.ComponentModel;
    using System.Windows;

    namespace WpfContextMenuWithEnum
    {
        public class EnumWrapperIteratorAndSelectorChoice : INotifyPropertyChanged
        {
            public event PropertyChangedEventHandler PropertyChanged;

            private EnumWrapperIteratorAndSelector _enumWrapperIteratorAndSelector;
            public Enum EnumValueRef { get; private set; }
            public string Name { get; set; }
            public string Description { get; set; }

            public bool IsChecked
            {
                get
                {
                    return _enumWrapperIteratorAndSelector.Enum.Equals(EnumValueRef);
                }

                set
                {
                    if (value) // Can only set value
                    {
                        _enumWrapperIteratorAndSelector.SetCurrentValue(EnumValueRef);
                    }
                }
            }

            internal void RaiseChangeIfAppropriate(DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
            {
                if (EnumValueRef.Equals(dependencyPropertyChangedEventArgs.OldValue) ||
                    EnumValueRef.Equals(dependencyPropertyChangedEventArgs.NewValue))
                {
                    var propertyChangeLocal = PropertyChanged;
                    if (propertyChangeLocal != null)
                    {
                        propertyChangeLocal(this, new PropertyChangedEventArgs("IsChecked"));
                    }
                }
            }

            public EnumWrapperIteratorAndSelectorChoice(EnumWrapperIteratorAndSelector enumWrapperIteratorAndSelector,
                Enum enumValueRef, string description = null)
            {
                _enumWrapperIteratorAndSelector = enumWrapperIteratorAndSelector;
                EnumValueRef = enumValueRef;
                Name = enumValueRef.ToString();
                Description = description;
            }

            public string DisplayName
            {
                get { return Description ?? Name; }
            }
        }
    }

using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows.Input;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.CommandWpf;

namespace WpfContextMenuWithEnum
{
    public class MainWindowModel : ViewModelBase
    {
        private EnumChoice _selectedEnumChoice;

        public EnumChoice SelectedEnumChoice
        {
            get { return _selectedEnumChoice; }
            set { _selectedEnumChoice = value; RaisePropertyChanged(); }
        }
    }
}

A: So you want to be  able to

*

*Bind any Enum to ContextMenu and display it's Description attribute

*Have a checkmark in front of selected Enum, only one can be "active" at any given time

*Store selected value in ViewModel & excute some logic when selection changes

Something like the following?

MainWindow.xaml
<Window x:Class="WpfApplication1.View.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:viewModel="clr-namespace:WpfApplication1.ViewModel"
        xmlns:local="clr-namespace:WpfApplication1"
        Title="MainWindow"
        Height="300"
        Width="250">

    <!-- Set data context -->
    <Window.DataContext>
      <viewModel:MainViewModel />
    </Window.DataContext>

    <!-- Converters -->
    <Window.Resources>
      <local:EnumDescriptionConverter x:Key="EnumDescriptionConverter" />
      <local:EnumCheckedConverter x:Key="EnumCheckedConverter" />
    </Window.Resources>

    <!-- Element -->
    <TextBox Text="Right click me">
      <!-- Context menu -->
      <TextBox.ContextMenu>
        <ContextMenu ItemsSource="{Binding EnumChoiceProvider}">
          <ContextMenu.ItemTemplate>
            <DataTemplate>
              <!-- Menu item header bound to enum converter -->
              <!-- IsChecked bound to current selection -->
              <!-- Toggle bound to a command, setting current selection -->
              <MenuItem
                IsCheckable="True"
                Width="150"
                Header="{Binding Path=., Converter={StaticResource EnumDescriptionConverter}}"
                Command="{Binding DataContext.ToggleEnumChoiceCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ContextMenu}}"
                CommandParameter="{Binding}">
                <MenuItem.IsChecked>
                  <MultiBinding Mode="OneWay"
                                NotifyOnSourceUpdated="True"
                                UpdateSourceTrigger="PropertyChanged"
                                Converter="{StaticResource EnumCheckedConverter}">
                    <Binding Path="DataContext.SelectedEnumChoice"
                             RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType=ContextMenu}"  />
                    <Binding Path="."></Binding>
                  </MultiBinding>
                </MenuItem.IsChecked>
              </MenuItem>
            </DataTemplate>
          </ContextMenu.ItemTemplate>
        </ContextMenu>
      </TextBox.ContextMenu>
    </TextBox>
</Window>

MainViewModel.cs
namespace WpfApplication1.ViewModel
{
    public class MainViewModel : ViewModelBase // where base implements INotifyPropertyChanged
    {
        private EnumChoice? _selectedEnumChoice;

        public MainViewModel()
        {
            EnumChoiceProvider = new ObservableCollection<EnumChoice>
                (Enum.GetValues(typeof(EnumChoice)).Cast<EnumChoice>());

            ToggleEnumChoiceCommand = new RelayCommand<EnumChoice>
                (arg => SelectedEnumChoice = arg);
        }

        // Selections
        public ObservableCollection<EnumChoice> EnumChoiceProvider { get; set; }

        // Current selection
        public EnumChoice? SelectedEnumChoice
        {
            get
            {
                return _selectedEnumChoice;
            }
            set
            {
                _selectedEnumChoice = value != _selectedEnumChoice ? value : null;
                RaisePropertyChanged();
            }
        }

        // "Selection changed" command
        public ICommand ToggleEnumChoiceCommand { get; private set; }
    }
}

EnumChoice.cs
namespace WpfApplication1
{
    public enum EnumChoice
    {
        [Description("Default")]
        ChoiceDefault,
        [Description("<1>")]
        Choice1,
        [Description("<2>")]
        Choice2
    }
}

EnumDescriptionConverter.cs
namespace WpfApplication1
{
    // Extract enum description
    public class EnumDescriptionConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            MemberInfo[] memberInfos = value.GetType().GetMember(value.ToString());

            if (memberInfos.Length > 0)
            {
                object[] attrs = memberInfos[0].GetCustomAttributes(typeof (DescriptionAttribute), false);
                if (attrs.Length > 0)
                    return ((DescriptionAttribute) attrs[0]).Description;
            }

            return value;

            // or maybe just
            //throw new InvalidEnumArgumentException(string.Format("no description found for enum {0}", value));
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}

EnumCheckedConverter.cs
namespace WpfApplication1
{
    // Check if currently selected
    public class EnumCheckedConverter : IMultiValueConverter
    {
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            return !values.Contains(null) && values[0].ToString().Equals(values[1].ToString(), StringComparison.OrdinalIgnoreCase);
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}

A: To add to the rest of the answers: you can get rid of the "menu in a menu" style problem by setting ItemContainerStyle instead of ItemTemplate:
DataTemplate
<MenuItem.ItemTemplate>
    <DataTemplate>
        <MenuItem IsCheckable="True"
                  Header="{Binding DisplayName}"
                  IsChecked="{Binding IsChecked}">
        </MenuItem>
    </DataTemplate>
</MenuItem.ItemTemplate>

ItemContainerStyle
<MenuItem.ItemContainerStyle>
    <Style TargetType="MenuItem" BasedOn="{StaticResource {x:Type MenuItem}}">
        <Setter Property="IsCheckable" Value="True" />
        <Setter Property="Header" Value="{Binding DisplayName}" />
        <Setter Property="IsChecked" Value="{Binding IsChecked}" />
    </Style>
</MenuItem.ItemContainerStyle>

A: To finalize the addition of Daniel, here is the full code with the appropriates bindings that goes inside the MainWindow initially provided by Mikko.
<ContextMenu ItemsSource="{Binding EnumChoiceProvider}">
    <ContextMenu.ItemContainerStyle>
        <Style TargetType="MenuItem" BasedOn="{StaticResource {x:Type MenuItem}}">
            <Setter Property="IsCheckable" Value="True" />
            <Setter Property="Header" Value="{Binding Path=., Converter={StaticResource EnumDescriptionConverter}}" />
            <Setter Property="Command" Value="{Binding DataContext.ToggleEnumChoiceCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ContextMenu}}" />
            <Setter Property="CommandParameter" Value="{Binding}"/>
            <Setter Property="IsChecked">
                <Setter.Value>
                    <MultiBinding Mode="OneWay"
                                  NotifyOnSourceUpdated="True"
                                  UpdateSourceTrigger="PropertyChanged"
                                  Converter="{StaticResource EnumCheckedConverter}">
                        <Binding Path="DataContext.RunEnv.ControllerViewModel.SimulationMode"
                                 RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType=ContextMenu}"  />
                        <Binding Path="."></Binding>
                    </MultiBinding>
                </Setter.Value>
            </Setter>
        </Style>
    </ContextMenu.ItemContainerStyle>
</ContextMenu>


text:
Q: String representation of formatters in java.time.format.DateTimeFormatter Is there a way to get a string representation of formatters defined statically in DateTimeFormatter?
E.g. for DateTimeFormatter.ISO_OFFSET_DATE_TIME I would like to get something like:
"uuuu-MM-dd'T'HH:mm:ss.SSSX"
I've checked DateTimeFormatter source and I coudln't find any methods which gives this info. It internally uses DateTimeFormatterBuilder with programmatically set fields, properties etc and does not uses String.
When I call toString() on a particaular formatter I get e.g.:
DateTimeFormatter.ISO_OFFSET_DATE_TIME.toString()

gives:
ParseCaseSensitive(false)(ParseCaseSensitive(false)(Value(Year,4,10,EXCEEDS_PAD)'-'Value(MonthOfYear,2)'-'Value(DayOfMonth,2))'T'(Value(HourOfDay,2)':'Value(MinuteOfHour,2)[':'Value(SecondOfMinute,2)[Fraction(NanoOfSecond,0,9,DecimalPoint)]]))Offset(+HH:MM:ss,'Z')


text:
Q: How to trigger validation when user removes original field value? I am well aware of JQuery validation's lazy behavior. In reality, it is only semi-lazy in that if a field contains a valid value, loses focus, and then is changed to an invalid value, an error message is displayed immediately, even before the field is unfocused again. This behavior is very reliable, except in one very specific scenario that I want to find a workaround for.
If a field initially contains a valid value, changing it to a non-empty invalid value triggers immediate validation, as expected. But removing the initial value does not trigger validation. Example:
<form id="muh-form" action="post">
  <input name="input1" type="number" value="10" required min="10"/>

  <input name="input2" type="text"/>

  <input type="submit" value="Submit"/>
</form>

If the user changes "10" to "1" and unfocuses the field, an error message appears immediately, as expected. Furthermore, if the user then changes "1" to empty, the required validation is triggered, as expected.  Only a direct transition from initially valid to empty fails to trigger validation.
fiddle
As a workaround, can I force the validator to immediately validate all fields when the form is loaded?

A:
Quote OP:  If the user changes input1 to some value < 10 and unfocuses the field, validation is triggered as expected. But if the user simply removes the initial value (without first changing it) and unfocuses the field, validation is not triggered.

You are describing the default validation of the plugin, which is called "lazy" validation.  See the docs:

"Before a field is marked as invalid, the validation is lazy: Before submitting the form for the first time, the user can tab through fields without getting annoying messages – they won't get bugged before having the chance to actually enter a correct value"

If you'd like to use "eager" validation instead, then you'll need to use a custom onfocusout callback function...
onfocusout: function(element) {
    // "eager" validation
    this.element(element);
}

DEMO:  jsfiddle.net/r60L5bfx/3/

A: You can call .valid() in change event.
$(document).ready(function() {
  $("#muh-form").on('change', function(e) {
    $("#muh-form").valid();
  });

  $("#muh-form").validate({
    submitHandler: function (form) { }
  });
});

JSFiddle link


text:
Q: Is .show() a Spark action? When one calls show() on a Spark dataframe, is this an "action" in the sens that the full calculation is actually performed? Clearly in order to show any results, some of a given calculation actually needs to be performed, but in some cases it may in principle be possible to show a subset of the results without performing the full calculation (analogous to using LIMIT in a SQL query).
This documentation page lists "some of the common actions" but I wasn't able to find an exhaustive list.


text:
Q: How to compute volume flow rate of water being sucked up in a straw? If I know the pressure on one side of the straw (atmospheric) and the pressure inside the mouth, can I compute the volume flow rate?  This is first disregarding the transient rise and fall and only consider the steady-state suck.
My current list of assumptions includes:

*

*Newtonian fluid (water)

*Laminar flow ($\text{Re} < 2000$), estimated assuming $D = 7\text{ mm}$ and an assumed upper fluid speed of $0.25\text{ m/s}$  Of course this will have to be re-confirmed once a flow rate has been calculated.

*$T_{\text{atm}} = 20\text{ C}$

*$P_{\text{atm}}$ at $20\text{ C} = 101325\text{ Pa}$

This model and calculator seemed relevant, but my inlet and outlet diameters are the same and my attempts to compute the same volumetric flow rate are around $50\%$ too small:
$$Q = C_f \times A_o \times \sqrt{2 \times \frac{\delta_p}{\rho}}$$

*

*$C_f = 0.9$

*$A_o = 3.84\times10^{-5} \text{ m^2} (D = 7\text{ mm})$

*$\delta_p = 2000 \text{ Pa}$

*$\rho = 999.97 \text{ kg/m}^3$

If the flow is laminar and fully-developed, I'm considering using the following taken from here and setting $\theta = 90$ degrees:
$$Q = \frac{\pi D^4 (\delta_p - \rho g L \sin \theta)}{128 \mu L}$$
Example geometry:
$D = 7E^-3 m$
$L = 20E^-2m$
$\theta = 0degrees$
Constants:
$\rho = 999.97 kg / m^3$
$g = 9.81 m / s^2$
$\mu = 1.002E^-3 Pa * s$
$\nu = 1.004E^-6 Pa * s$
Computing $Q(\delta_p = 50 Pa)$:
$Q => 2.51E^-05m^3/s => 25.1mL/s$
$V_{avg} = Q / A_c => 2.51E^-05m^3/s / 5.03E-05 => 0.5m / s$
Re-checking laminar assumption:
$Re = V_{avg} * D / \nu \Longrightarrow 10K > Re_{cr}$


text:
Q: Hibernate Cascading problems with OneToMany I'm trying to understand how to properly annotate classes to get cascading to work.
Here is a simple parent/children scenario.
Child:
@Entity
@Table(name = "testChild")
public class testChild implements Serializable {
    @Id
    @GeneratedValue(generator = "uuid")
    @GenericGenerator(name = "uuid", strategy = "uuid2")
    @Column(name = "uuid", unique = true, nullable = false)
    @JsonProperty
    private String uuid;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name="parent_uuid", nullable=false)
    @Cascade(value={CascadeType.ALL})
    @JsonIgnore
    private testParent parent;

    @Column(name = "name")
    @JsonProperty
    private String name;

    public testChild (testParent parent, String name) {
        this.uuid = UUID.randomUUID().toString();
        this.name = name;
        this.parent = parent;
    }

    public String getUuid() {
        return this.uuid;
    }

    public void setUuid(String uuid) {
        this.uuid = uuid;
    }

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public testParent getParent () {
        return this.parent;
    }

    public void setParent (testParent parent) {
        this.parent = parent;
    }
}

Parent:
    @Entity
@Table(name = "testParent")
public class testParent implements Serializable {
    @Id
    @GeneratedValue(generator = "uuid")
    @GenericGenerator(name = "uuid", strategy = "uuid2")
    @Column(name = "uuid", unique = true, nullable = false)
    @JsonProperty
    private String uuid;        // This is the figure uuid:<number>

    @Column(name = "name")
    @JsonProperty
    private String name;

    @Column(name = "children")
    @OneToMany(fetch = FetchType.EAGER, mappedBy = "parent", orphanRemoval=true, cascade = javax.persistence.CascadeType.ALL)
    @Cascade({CascadeType.SAVE_UPDATE, CascadeType.DELETE})
    @JsonProperty
    private List <testChild> children;

    public testParent (String name) {
        this.uuid = UUID.randomUUID().toString();
        this.name = name;
        this.children = new ArrayList<>();
    }

    public String getUuid() {
        return this.uuid;
    }

    public void setUuid(String uuid) {
        this.uuid = uuid;
    }

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List <testChild> getChildren () {
        return this.children;
    }

    public void setChildren (List <testChild> children) {
        this.children = children;
    }

    public testChild addChild(String childname) {
        testChild c = new testChild(this, childname);
        this.children.add(c);
        return c;
    }
}

And the test code:
testParent p = new testParent("Dan");
sid = p.getUuid();

testChild c1 = p.addChild("Dan jr.");
testChild c2 = p.addChild("Dannielle");
session.save(p);

My problem is that it's resulting in an update to the (first) child instead of an insert:
DEBUG org.hibernate.SQL - insert into testParent (name, uuid) values (?, ?)
DEBUG org.hibernate.SQL - update testChild set name=?, parent_uuid=? where uuid=?

Of course this throws an error.
I have tried quite a few combinations for Cascade in both the parent and child classes.
The only thing that does work is if I explicitly "session.save(object)" all the time.    i.e.
Create the parent - save,
create child1 - save,
create child2 - save,
finally save the parent again.
I'd really like to know how to tell Hibernate to simply save everything from the top down.
Tried a lot of different suggestions from this site and others, but nothing seems to be working.

A: You have to explicitly use the setter for parent and child.
Here is what you have to do:
 testParent p = new testParent("Dan");

 testChild c1 = new testChild("Dan");
 testChild c2 = new testChild("Dannielle");

 c1.setParent(p);
 c2.setParent(p);

 p.getChildren().add(c1);
 p.getChildren().add(c2);
 session.save(p);

You've also probably mixed up the entity cascades. On your OneToMany side, i.e testParent, you need to have CascadeType.ALL or include CascadeType.PERSIST. You want to say that whenever you want to 'insert' or 'update' or 'delete' a parent, please also do the same action on the children.
The save of the parent should cascade the save to its referenced children as well.

A: I have a partial answer.   It fixes the problem, but I'm still a little confused.
The problem has to do with using the generated ID's.   I was also trying to set them manually and that I think was breaking the mappings between parent and child.
Here is some working code:
    try {
        testParent p = new testParent("Dan");
        sid = p.getUuid();

        testChild c1 = new testChild("Dan Jr.");
        testChild c2 = new testChild("Danielle");

        c1.setParent(p);
        c2.setParent(p);
        p.getChildren().add(c1);
        p.getChildren().add(c2);

        session.save(p);
        tx.commit();

    } catch(Exception e) {
        tx.rollback();
        log.error("Exception occured. "+e.getMessage());
        assertTrue(false);
    }

But it only works when I do two things:

*

*Remove the @GeneratedValue and @GenericGenerator annotations from the class definitions.

*Make sure that my constructors manually create these id fields.

If I don't do that, then it seems that setUuid does not update the uuid field when persisted to the DB.   The object gets the new id, but only the original generated ID is saved.
I wonder if this is the best way to do this.


text:
Q: (Java) Having trouble with recursive overloading I'm studying basic Java and I there's a question on a programming assignment that I'm having a lot of trouble with concerning recursive overloading of sort of a search method. Here's what I'm being asked to do:
Write a method that accepts a two-dimensional int[][] array as the parameter and searches for legal "paths" through it, starting at [0][0] and ending at the end of the array. (For instance if the array is declared [5][5] then the end would be [4][4]).
In order for a path to be legal, "jumps" must be performed between the cells until the end of the array is reached. If a path doesn't end at the end of the array, it isn't legal. Here's an example:

The logic here is that a "jump" can be performed either to the right by the 10s and down by the 1s place of the number in the cell or vice versa, and the goal of the method is to return the number of legal pathways that exist through the array.
This wouldn't really be so much of a problem if it wasn't for the fact that the professor has several requirements for the assignment:
1) Absolutely no loops - the method must be carried out completely through recursion.
2) No global or constant variables
3) No changing the contents of the array or duplicating it
4) No creating or using other methods - overloading is encouraged (and probably required at this point) but writing a new method to assist in the process is out of the question.
Here's what I have so far:
public class Question4 {
//step 1 - location: [0][0]
    public static int countPaths(int[][] mat) {
        int current = mat[0][0];
        //case 1: x < 10
        if(current < 10) {
            //check right
            if(current < mat.length-1) {
                return countPaths(mat, current, 0, 0);
            }
            //check left
            if(current < (mat[0].length-1)) {
                return countPaths(mat, 0, current, 0);
            }
        //case 2: x >= 10
        } else if(current >= 10) {
            int tens = (int)(Math.floor(current / 10));
            int ones = current % 10;

            //check down by 10s, right by 1s
                if(tens < mat.length-1 && ones < mat[0].length-1) {
                return countPaths(mat, tens, ones, 0);
            }

            //check right by 10s, down by 1s
            if(ones < mat.length-1 && tens < mat[0].length-1) {
                return countPaths(mat, ones, tens, 0);
            }
        }

        return 0;
    }

    //step 2 - two options: down by 10s, right by 1s / right by 10s, down by 1s
    public static int countPaths(int[][] mat, int r, int c, int paths) {
        //check if the end of the array has been reached
        if(r == mat.length-1 && c == mat[r].length-1) {
            return paths + 1;
        } else {
            int current = mat[r][c], tens = (int)Math.floor(current / 10), ones = current % 10;

            //check down by 10s, right by 1s
            if(r + tens < mat.length-1 && c + ones < mat[r].length-1) {
                return countPaths(mat, r + tens, c + ones, paths);
            }

            //check down by 1s, right by 10s
            if(r + ones < mat.length-1 && c + tens < mat[r].length-1) {
                return countPaths(mat, r + ones, c + tens, paths);
            } else {
                return paths;
        }
    }
  }
}

I do apologize for the long question - I've been stuck on this thing for a week and haven't been able to figure it out.
The array in the photo should give a result of 3 possible paths, but every time I run the method I get 0.
Any help at all would be greatly appreciated. Thank you :)

A: I fixed the code. Essentially I'd been going about the problem all wrong: I was missing a case check. What I mean is that there are four possible outcomes for each subsequent recursion of the method:

*

*The end of the array has been reached and the returned value should be 1.

*A jump that goes down by the tens place and right by the ones place is legal but the reverse is not true.

*A jump that goes down by the ones place and right by the tens place is legal but the reverse is not true.

*Both of the aforementioned jumps are legal.

All I had to do once I realized that was to write a series of cascading if statements, each of which return a different value for the recursive function. What I didn't understand before is that a return statement could contain more than one recursive call, which enables me to run the method again for each case simultaneously in a "divide-and-conquer" sort of way.
The resulting code is:
public class Paths {
public static int countPaths(int[][] a) {
    //declare method variables
    int start = a[0][0], tens = start / 10, ones = start % 10;
    boolean downByTens, downByOnes;

    //set the case booleans
    if(tens <= a.length-1 && ones <= a[tens].length-1) {
        downByTens = true;
    } else {
        downByTens = false;
    }

    if(ones <= a.length-1 && tens <= a[ones].length-1) {
        downByOnes = true;
    } else {
        downByOnes = false;
    }

    //check the cases, return the overloaded method
    if(downByTens) {
        if(downByOnes) {
            return countPaths(a, tens, ones) + countPaths(a, ones, tens);
        } else {
            return countPaths(a, tens, ones);
        }
    } else {
        if(downByOnes) {
            return countPaths(a, ones, tens);
        } else {
            return 0;
        }
    }
}

private static int countPaths(int[][] a, int row, int col) {
    //declare method variables
    int current = a[row][col], tens = current / 10, ones = current % 10, end = a[a.length-1][a[0].length-1];
    boolean downByTens, downByOnes;

    //set the case booleans
    if(row + tens <= a.length-1 && col + ones <= a[row + tens].length-1) {
        downByTens = true;
    } else {
        downByTens = false;
    }

    if(row + ones <= a.length-1 && col + tens <= a[row + ones].length-1) {
        downByOnes = true;
    } else {
        downByOnes = false;
    }

    //check to see if the end of the array has been reached
    if(current == end) {
        return 1;
    } else {
        //check the cases
        if(downByTens) {
            if(downByOnes) {
                return countPaths(a, row + tens, col + ones) + countPaths(a, row + ones, col + tens);
            } else {
                return countPaths(a, row + tens, col + ones);
            }
        } else {
            if(downByOnes) {
                return countPaths(a, row + ones, col + tens);
            } else {
                return 0;
            }
        }
    }
}
}

When I ran the method countPaths(int[][] array) on the array in the picture I posted in the original question, the returned result was 3, which is the correct answer.
Special thanks to Imchpers who helped me with this code two weeks ago. I hope this answer helps others who are struggling with these kinds of recursive functions in any language.

A: here is my updated list of conflicts now that I've had time to review the code.
Your first problem as I discussed below is here:
        //check down by 10s, right by 1s
        if(r + tens < mat.length-1 && c + ones < mat[r].length-1) {
            return countPaths(mat, r + tens, c + ones, paths);
        }

        //check down by 1s, right by 10s
        if(r + ones < mat.length-1 && c + tens < mat[r].length-1) {
            return countPaths(mat, r + ones, c + tens, paths);
        } else {
            return paths;
        }

When your program goes from countPaths(mat) to countPaths(mat, r, c, paths), the initial location at this step is mat[1][2].  When you perform the second if condition after the first one returns paths = 1, this if condition fails to hold true (as it should) and it returns the else { return paths; }.  Because the paths at this step still equals 0, this returns paths = 0 which overrides your previous work done in the previous recursive return.
Once this program finishes this step, it will return to countPaths(mat) which has the return value from countPaths(mat, r, c, paths) of 0.  Because this method received a valid return, it will exit at this point and won't continue on to the next if condition here:
        //check down by 10s, right by 1s
            if(tens < mat.length-1 && ones < mat[0].length-1) {
            return countPaths(mat, tens, ones, 0);
        }

        //check right by 10s, down by 1s (this if condition)
        if(ones < mat.length-1 && tens < mat[0].length-1) {
            return countPaths(mat, ones, tens, 0);
        }

These are your two main problem areas which will require a bit of work to fix the code to solve.  My first main suggestion is having ONE return in your countPaths(mat) function which will return countPaths(mat, ones, tens, 0) starting at the initial location instead of at mat[1][2].  Let your recursive function deal with all the jumps; don't try to do initial handling in the first function.  Once you get that part refactored, I think everything else will fall into place and you can make progress in other small problem areas.  Please feel free to come back here & edit your question and/or add a comment if you run into problems afterwards.
Good luck!

A:  public static int countP(int a[][],int x,int y,int count)
 {
     if(row==(a.length-1) &&(cell==a[0].length-1)) {count++;
         return 1; }

if(x<a.length  && y<a[0].length )
         {
              System.out.println("cell ["+x+"]["+y+"]="+a[x][y]);

             int tmp1=a[x][y]%10;
             int tmp2=a[x][y]/10;
          return (countP(a,x+tmp1,y+tmp2,count) +countP(a, x+tmp2, t+tmp2, count));
        }
     return 0;

 }

i see this question on programming course 20441 Intro to CS.
  i guess they many similar Recursive Question in the world
now days i finish project on "System Programming Laboratory
(C Unix  Writing Compiler for Assembler ..(without linker) )
Liran Franco
Telecomtodays@gmail.com


text:
Q: How to access windows enviroment variables on MSYS? I want to build ffmpeg by vs2015 from msys2.
In the first add vs2015\vc\bin\amd64 in to path enviroment in windows.
Run "vs2015 x64 command prompt" as administrator then run vcvarsall.bat amd64.
In the final go to "msys" path and then run "msys2_shell.cmd".
I use "which cl" command for localize cl.exe.
Output:

which: no cl in
  (/usr/local/bin:/usr/bin:/bin:/opt/bin:/c/Windows/System32:/c/Windows:/c/Windows/System32/Wbem:/c/Windows/System32/WindowsPowerShell/v1.0/)

How to access to windows enviroments in the msys ?

A: Ran into the same problem.
Cause:

The PATH environment variable is not inherited to msys2.

Solution:

Rather than run msys2_shell.cmd alone, run it with a -use-full-path parameter:

 msys2_shell.cmd -use-full-path


text:
Q: Swap sections in ELF Is there a way to force gcc or ld place code section at the end of output ELF-format file?
Maybe I can force them not to produce any other section except .text if, for example, I dont have anything in .data, .rodata, .bss and other sections?

A: The minimal version of script that worked for me looked like:
ENTRY(_start)

SECTIONS
{
    .data : { *(.data) }
    .bss :  { *(.bss)  *(COMMON) }
    .text : { *(.text) }
}

But after I've made some more research (docs here) I've replaced this script with default one (ld --verbose). Then I've just placed code section in the very end of verbose script and it worked perfectly.


text:
Q: How to fix 'Unfortunately app has stopped' errors androidstudio Heading ##I have Error when I want run my app on android studio
plus help me .what i do for resolve this error
my code logcat

? E/videowall-TranscodeReceiver: broadcastMSG :
  android.intent.action.ACTION_POWER_DISCONNECTED 06-22 02:54:15.250
  108-108/? E/SMD: DrReadUsbStatus File Open failed 06-22 02:54:15.370
  23967-23967/? E/dalvikvm: Could not find class
  'android.os.UserManager', referenced from method
  org.chromium.chrome.browser.superviseduser.SupervisedUserContentProvider.updateEnabledState
  06-22 02:54:15.580 23967-23967/? E/dalvikvm: Could not find class
  'android.app.AppOpsManager', referenced from method
  com.google.android.gms.common.cI.a 06-22 02:54:15.580 23967-23967/?
  E/dalvikvm: Could not find class 'android.os.UserManager', referenced
  from method com.google.android.gms.common.cI.a 06-22 02:54:16.540
  23994-23994/? E/dalvikvm: Could not find class
  'android.app.AppOpsManager', referenced from method bo.a 06-22
  02:54:16.560 23994-23994/? E/dalvikvm: Could not find class
  'android.app.Notification$Action$Builder', referenced from method bo.a
  06-22 02:54:16.610 23994-23994/? E/dalvikvm: Could not find class
  'android.graphics.drawable.RippleDrawable', referenced from method
  bo.a 06-22 02:54:16.670 23994-23994/? E/dalvikvm: Could not find class
  'android.media.MediaDescription$Builder', referenced from method bo.a
  06-22 02:54:16.690 23994-23994/? E/dalvikvm: Could not find class
  'android.view.accessibility.AccessibilityNodeInfo$AccessibilityAction',
  referenced from method bo.a 06-22 02:54:16.690 23994-23994/?
  E/dalvikvm: Could not find class
  'android.media.session.MediaController', referenced from method bo.a
  06-22 02:54:16.690 23994-23994/? E/dalvikvm: Could not find class
  'android.transition.Transition', referenced from method bo.a 06-22
  02:54:16.690 23994-23994/? E/dalvikvm: Could not find class
  'android.transition.Transition', referenced from method bo.a 06-22
  02:54:16.690 23994-23994/? E/dalvikvm: Could not find class
  'android.transition.Transition', referenced from method bo.a 06-22
  02:54:16.690 23994-23994/? E/dalvikvm: Could not find class 'lk',
  referenced from method bo.a 06-22 02:54:16.780 23994-23994/?
  E/dalvikvm: Could not find class
  'android.app.Notification$Action$Builder', referenced from method bo.a
  06-22 02:54:16.860 23994-23994/? E/dalvikvm: Could not find class
  'fn', referenced from method bo.a 06-22 02:54:16.860 23994-23994/?
  E/dalvikvm: Could not find class 'android.transition.Transition',
  referenced from method bo.a 06-22 02:54:16.860 23994-23994/?
  E/dalvikvm: Could not find class 'android.transition.Transition',
  referenced from method bo.a 06-22 02:54:16.880 23994-23994/?
  E/dalvikvm: Could not find class
  'android.media.MediaDescription$Builder', referenced from method bo.a
  06-22 02:54:16.880 23994-23994/? E/dalvikvm: Could not find class
  'android.media.MediaDescription$Builder', referenced from method bo.a
  06-22 02:54:16.880 23994-23994/? E/dalvikvm: Could not find class
  'android.media.MediaDescription$Builder', referenced from method bo.a
  06-22 02:54:16.880 23994-23994/? E/dalvikvm: Could not find class
  'android.media.MediaDescription', referenced from method bo.a 06-22
  02:54:16.880 23994-23994/? E/dalvikvm: Could not find class
  'android.transition.Transition', referenced from method bo.a 06-22
  02:54:16.880 23994-23994/? E/dalvikvm: Could not find class
  'android.transition.TransitionSet', referenced from method bo.a 06-22
  02:54:16.880 23994-23994/? E/dalvikvm: Could not find class
  'android.transition.Transition', referenced from method bo.a 06-22
  02:54:16.880 23994-23994/? E/dalvikvm: Could not find class
  'android.media.MediaDescription$Builder', referenced from method bo.a
  06-22 02:54:16.880 23994-23994/? E/dalvikvm: Could not find class
  'android.media.session.MediaController', referenced from method bo.a
  06-22 02:54:16.880 23994-23994/? E/dalvikvm: Could not find class
  'android.media.session.MediaController', referenced from method bo.a
  06-22 02:54:16.880 23994-23994/? E/dalvikvm: Could not find class
  'android.transition.Transition', referenced from method bo.a 06-22
  02:54:16.890 23994-23994/? E/dalvikvm: Could not find class
  'android.media.MediaDescription$Builder', referenced from method bo.a
  06-22 02:54:16.890 23994-23994/? E/dalvikvm: Could not find class
  'android.transition.Transition', referenced from method bo.a 06-22
  02:54:16.930 23994-23994/? E/dalvikvm: Could not find class
  'android.app.RemoteInput[]', referenced from method bo.a 06-22
  02:54:16.980 23994-23994/? E/dalvikvm: Could not find class
  'android.transition.Transition', referenced from method bo.b 06-22
  02:54:17.000 23994-23994/? E/dalvikvm: Could not find class
  'android.media.MediaDescription$Builder', referenced from method bo.b
  06-22 02:54:17.000 23994-23994/? E/dalvikvm: Could not find class
  'android.transition.Transition', referenced from method bo.b 06-22
  02:54:17.010 23994-23994/? E/dalvikvm: Could not find class
  'android.view.accessibility.AccessibilityNodeInfo$AccessibilityAction',
  referenced from method bo.b 06-22 02:54:17.020 23994-23994/?
  E/dalvikvm: Could not find class 'android.media.MediaDescription',
  referenced from method bo.c 06-22 02:54:17.030 23994-23994/?
  E/dalvikvm: Could not find class
  'android.media.MediaDescription$Builder', referenced from method bo.c
  06-22 02:54:17.030 23994-23994/? E/dalvikvm: Could not find class
  'android.view.accessibility.AccessibilityNodeInfo$CollectionInfo',
  referenced from method bo.c 06-22 02:54:17.040 23994-23994/?
  E/dalvikvm: Could not find class 'android.media.MediaDescription',
  referenced from method bo.d 06-22 02:54:17.040 23994-23994/?
  E/dalvikvm: Could not find class
  'android.view.accessibility.AccessibilityNodeInfo$CollectionItemInfo',
  referenced from method bo.d 06-22 02:54:17.050 23994-23994/?
  E/dalvikvm: Could not find class 'android.media.MediaDescription',
  referenced from method bo.e 06-22 02:54:17.060 23994-23994/?
  E/dalvikvm: Could not find class 'android.media.MediaDescription',
  referenced from method bo.f 06-22 02:54:17.070 23994-23994/?
  E/dalvikvm: Could not find class 'android.media.MediaDescription',
  referenced from method bo.g 06-22 02:54:17.080 23994-23994/?
  E/dalvikvm: Could not find class 'android.media.MediaDescription',
  referenced from method bo.h 06-22 02:54:17.080 23994-23994/?
  E/dalvikvm: Could not find class 'android.media.MediaDescription',
  referenced from method bo.i 06-22 02:54:17.090 23994-23994/?
  E/dalvikvm: Could not find class
  'android.media.MediaDescription$Builder', referenced from method bo.j
  06-22 02:54:17.090 23994-23994/? E/dalvikvm: Could not find class
  'android.media.session.MediaController', referenced from method bo.k
  06-22 02:54:17.100 23994-23994/? E/dalvikvm: Could not find class
  'android.media.session.MediaController', referenced from method bo.l
  06-22 02:54:17.100 23994-23994/? E/dalvikvm: Could not find class
  'android.media.session.MediaController', referenced from method bo.m
  06-22 02:54:17.100 23994-23994/? E/dalvikvm: Could not find class
  'android.media.session.MediaController', referenced from method bo.n
  06-22 02:54:17.110 23994-23994/? E/dalvikvm: Could not find class
  'android.media.session.MediaController$TransportControls', referenced
  from method bo.o 06-22 02:54:17.110 23994-23994/? E/dalvikvm: Could
  not find class
  'android.media.session.MediaController$TransportControls', referenced
  from method bo.p 06-22 02:54:17.110 23994-23994/? E/dalvikvm: Could
  not find class 'android.media.session.PlaybackState', referenced from
  method bo.q 06-22 02:54:17.120 23994-23994/? E/dalvikvm: Could not
  find class 'android.media.session.PlaybackState', referenced from
  method bo.r 06-22 02:54:17.120 23994-23994/? E/dalvikvm: Could not
  find class 'android.media.session.PlaybackState', referenced from
  method bo.s 06-22 02:54:17.120 23994-23994/? E/dalvikvm: Could not
  find class 'android.media.session.PlaybackState', referenced from
  method bo.t 06-22 02:54:17.130 23994-23994/? E/dalvikvm: Could not
  find class 'android.media.session.PlaybackState', referenced from
  method bo.u 06-22 02:54:17.130 23994-23994/? E/dalvikvm: Could not
  find class 'android.media.session.PlaybackState', referenced from
  method bo.v 06-22 02:54:17.130 23994-23994/? E/dalvikvm: Could not
  find class 'android.media.session.PlaybackState', referenced from
  method bo.w 06-22 02:54:17.140 23994-23994/? E/dalvikvm: Could not
  find class 'android.media.session.PlaybackState', referenced from
  method bo.x 06-22 02:54:17.140 23994-23994/? E/dalvikvm: Could not
  find class 'android.media.session.PlaybackState', referenced from
  method bo.y 06-22 02:54:17.250 108-108/? E/SMD: DrReadUsbStatus File
  Open failed 06-22 02:54:17.280 23994-23994/? E/dalvikvm: Could not
  find class 'android.media.session.PlaybackState', referenced from
  method len.a 06-22 02:54:17.290 23994-23994/? E/dalvikvm: Could not
  find class 'qz', referenced from method len.b 06-22 02:54:17.940
  23994-23994/? E/dalvikvm: Could not find class
  'android.media.session.PlaybackState$CustomAction', referenced from
  method fnj.getAction 06-22 02:54:17.940 23994-23994/? E/dalvikvm:
  Could not find class
  'android.media.session.PlaybackState$CustomAction', referenced from
  method fnj.getExtras 06-22 02:54:17.970 23994-23994/? E/dalvikvm:
  Could not find class
  'android.media.session.PlaybackState$CustomAction', referenced from
  method fnj.getIcon 06-22 02:54:17.970 23994-23994/? E/dalvikvm: Could
  not find class 'android.media.session.PlaybackState$CustomAction',
  referenced from method fnj.getName 06-22 02:54:17.990 23994-23994/?
  E/dalvikvm: Could not find class 'android.media.MediaMetadata',
  referenced from method fnj.writeToParcel 06-22 02:54:19.250 108-108/?
  E/SMD: DrReadUsbStatus File Open failed 06-22 02:54:19.750
  24022-24022/? E/dalvikvm: Could not find class
  'android.os.UserManager', referenced from method
  com.google.android.gms.common.zze.zzaq 06-22 02:54:19.750
  24022-24022/? E/dalvikvm: Could not find class

A: Try this.. it will help you..
1) Remove the support-library dependency reference from your module-level build.gradle file or files.
2) Than Clean the Project
3) Restart Android Studio.
4) Add the support-library back via Project Structure > Dependencies which you previously used.


text:
Q: How can I change the NoData value in QGIS 2.x using the python console I'm trying to add a NoData value to a single band raster image in QGIS 2.0 using the python console but can't find the right bit of code to do it.
Here's what I see on the console:
>>> layer = qgis.utils.iface.activeLayer()
>>> layer
<qgis.core.QgsRasterLayer object at 0x06AFFDF8>
>>> layer.renderer()
<qgis.core.QgsPalettedRasterRenderer object at 0x1874E0C0>

Any help here would be great!


text:
Q: WinSxS filling so fast that DISM cleanup cannot operate I have a Windows 10 machine that is seeing the WinSxS folder fill up so quickly that DISM cannot run, and c: shows 0 bytes free. The machine also has a D: with 30 GB+ free space, so I have tried running
dism /online /cleanup-image /startcomponentcleanup /scratchdir:d:\dism_temp

If I run without the scratchdisk option, dism won't even start. If I run with the scratchdisk option, dism errors out at 20% with a 112 error "There is not enough space on the disk."
/resetbase switch also errors out on not enough disk space even with /scratchdir switch used.
Disk Cleanup buys me a few MB for a minute or two, which is enough to get dism started without the d: scratchdisk, but then the freed space magically disappears in a few minutes.
Is there some way around this?

A: How big is WinSxS?  It is normally large, managed by Windows and should be left alone.
Look elsewhere to save space.  Check My Documents (and Pictures, Videos) for large or older files that can be moved elsewhere (your second drive) .
The Windows drive needs space for WinSxS (for repairs and management) and for updating (20GB + for feature updates).
Once you have moved some files, Admin Tools, Disk Cleanup works very well. Run Disk Cleanup, push "Cleanup System Files" and then (after it does its first run), select ALL items.
If you have done a feature update in past, Disk Cleanup will ask you about removing it and say OK or Yes.
Ultimately you may need a bigger drive C:.

A: For whatever reason, I was able to run DISM StartComponentCleanup by launching through Task Scheduler:

Task Scheduler>Task Scheduler
Library>Microsoft>Windows>Servicing>StartComponentCleanup

I also scheduled off-hours running of StartComponentCleanup to keep the WinSxS folder under control going forward.
EDIT:
Automatically scheduled tasks are auto-terminated if they take too long. I had to create the task, export it as an XML file, change the priority level to 4 (higher priority than 7, the default value) and import the updated task. At a higher priority, the task runs faster and doesn't time out, and is much more likely to complete.


text:
Q: Get id of previous tag I want to get ID of a previous p tag.
HTML:

One

    Two
    Three

jQuery:
$('#remove').click(function(e) {
    e.preventDefault();
    var x = $(this).prev("p").attr('id');
    alert(x);

});

It is giving nothing in alert. Where I am doing wrong?

A: Prev is only get direct previous element on same level please check below solution -

$('#remove').click(function(e) {
    e.preventDefault();
    var x = $(this).parent().prev("p").attr('id');
    alert(x);

});

One

 Two Three

A: You can use the .closest('p') function to select the parent p tag
$('#remove').click(function(e) {
    e.preventDefault();
    var x = $(this).closest('p').attr('id');
    x.remove();

});

A: If you use .prev(), it will try to get direct previous element of a.
You have to go to .parent() of a and then use .prev().
 var p = $(this).parent().prev("p").attr('id');


text:
Q: Get Lat & Lng from GeoDjango OSMGeoAdmin Django OSMGeoAdmin with PointField uses OpenLayers and it's hard to use.
I want to add two new input elements which are lat and lng. Using jQuery, when values of the input elements are changed, I want to change point on the OpenLayers.
How can I do that?
No complete code or instructions are necessary, main idea is enough.

A: i dont know is there any difference with geodjando and OSMGeoAdmin but in normal geodjango if you want to update any field, you can use following code:
def updateVal(request):
  poId = request.POST.get("pointID", default=0)
  objGeo = request.POST.get("meta", default=0)

  f = Points.objects.get(id = poId)

  try:
      f.geom = objGeo
      f.save()
      res = "OK"
  except:
      res = "ERROR"

i hope it helps you...


text:
Q: Insert objects into NSSet's with multiple many-to-many relationships in Swift Let's say I have a sports app with 2 Entities. (this is purely an example)
Teams and Players.
class Team:NSManagedObject{
    @NSManaged var name:String
    @NSManaged var players:NSSet
}

class Player:NSManagedObject{
    @NSManaged var firstName:String
    @NSManaged var lastName:String
    @NSManaged var playsFor:NSSet
}

Each Team has a set of players.
Each player has a set of teams they play for.
So in essence, I have 2 many-to-many relationships. Had there only been one, I could use the inverse to insert the object into its set without any trouble.
Because of this sad dual many-to-many structure of these object, I find myself in a pickle. Now before someone says I should take an intermediate object and do a one-to-many with that object to remove the second object, I would LOVE to do that, but, in this case, I can't, so I'd like to open the topic of how to solve this particular problem.
I've tried two different attempts.
The biggest issue is that the type of players is an NSSet, I can't just do an addObject because NSSet is immutable.
My first idea was the following:
func addPlayer(player: Player) {
    var allPlayers = self.players.allObjects
    allPlayers.append(player)
    self.players = NSSet(array: allPlayers)
}

Now this is bad on multiple levels. So I'll just move on right away.
My next idea was that clearly it was bad to be taking a NSSet to an Array to a Set again just to add one item, so I changed the data model of the Team to be
@NSManagedObject var players:Set<Player>

Then my method was simplified to:
func addPlayer(player: Player) {
    self.players.addObject(player)
}

I really liked this, until I turned on the profiler and my execution time had actually become SIGNIFICANTLY worse.
So my next attempt was the following, clearly leaving the types of the managedobjects as NSSet gives you some significant benefits, so I didn't mess with that anymore.
func addPlayer(player: Players) {
    let allPlayers = NSMutableSet(set: self.players)
    allPlayers.addObject(player)
    self.players = allPlayers
}

I got a small speed bump off of the last change but am still not happy with it. What other optimizations are possible? Any ideas?
In reality, I am working with an application using a VERY old database with hundreds of thousands of objects that we have no control over refactoring. I'm trying to do optimizations without completely reworking the data-model and destroying a front end. Any help advice or ideas would be appreciated.


text:
Q: apt-get can't install/remove linux-image-4.2.0-25-generic I tried to install a package (jsonlint) via apt-get on a Xubuntu 15.10 system and it failed due to an error installing linux-image-4.2.0-25-generic .  This was a new, clean install of 15.10, Jan 15 2016
I tried standalone
sudo apt-get install linux-image-4.2.0-25-generic

and it fails. I also cannot remove linux-image-4.2.0-25-generic.
linux-image-4.2.0-23-generic is active in /boot and boots correctly
via grub, but these broken -25 artifacts prevent updates.
Can't remove or install kernel did not help
below are my logs from trying install/remove. I don't use lilo, so I'm not sure what those errors mean or how to ignore them.
How can I clean this up so I can install other packages? apt-get --force-yes sounds dangerous; is there a better way?
I tried to remove after prior install failed:
$ uname -r
4.2.0-23-generic
$ sudo apt-get update
...
$ sudo apt-get remove linux-image-4.2.0-25-generic
(Reading database ... 208105 files and directories currently installed.)
Removing linux-generic (4.2.0.25.27) ...
Removing linux-image-generic (4.2.0.25.27) ...
Removing linux-image-extra-4.2.0-25-generic (4.2.0-25.30) ...
run-parts: executing /etc/kernel/postinst.d/apt-auto-removal 4.2.0-25-generic /boot/vmlinuz-4.2.0-25-generic
run-parts: executing /etc/kernel/postinst.d/dkms 4.2.0-25-generic /boot/vmlinuz-4.2.0-25-generic
run-parts: executing /etc/kernel/postinst.d/initramfs-tools 4.2.0-25-generic /boot/vmlinuz-4.2.0-25-generic
update-initramfs: Generating /boot/initrd.img-4.2.0-25-generic
run-parts: executing /etc/kernel/postinst.d/pm-utils 4.2.0-25-generic /boot/vmlinuz-4.2.0-25-generic
run-parts: executing /etc/kernel/postinst.d/unattended-upgrades 4.2.0-25-generic /boot/vmlinuz-4.2.0-25-generic
run-parts: executing /etc/kernel/postinst.d/update-notifier 4.2.0-25-generic /boot/vmlinuz-4.2.0-25-generic
run-parts: executing /etc/kernel/postinst.d/zz-runlilo 4.2.0-25-generic /boot/vmlinuz-4.2.0-25-generic
Warning: LBA32 addressing assumed
Fatal: raid_setup: stat("/dev/sdb")
run-parts: /etc/kernel/postinst.d/zz-runlilo exited with return code 1
dpkg: error processing package linux-image-extra-4.2.0-25-generic (--remove):
 subprocess installed post-removal script returned error exit status 1
Removing linux-image-4.2.0-25-generic (4.2.0-25.30) ...
Examining /etc/kernel/prerm.d.
run-parts: executing /etc/kernel/prerm.d/dkms 4.2.0-25-generic /boot/vmlinuz-4.2.0-25-generic
dkms: removing: vboxhost 5.0.12 (4.2.0-25-generic) (x86_64)

-------- Uninstall Beginning --------
Module:  vboxhost
Version: 5.0.12
Kernel:  4.2.0-25-generic (x86_64)
-------------------------------------

Status: Before uninstall, this module version was ACTIVE on this kernel.

vboxdrv.ko:
 - Uninstallation
   - Deleting from: /lib/modules/4.2.0-25-generic/updates/dkms/
 - Original module
   - No original module was found for this module on this kernel.
   - Use the dkms install command to reinstall any previous module version.

vboxnetflt.ko:
 - Uninstallation
   - Deleting from: /lib/modules/4.2.0-25-generic/updates/dkms/
 - Original module
   - No original module was found for this module on this kernel.
   - Use the dkms install command to reinstall any previous module version.

vboxnetadp.ko:
 - Uninstallation
   - Deleting from: /lib/modules/4.2.0-25-generic/updates/dkms/
 - Original module
   - No original module was found for this module on this kernel.
   - Use the dkms install command to reinstall any previous module version.

vboxpci.ko:
 - Uninstallation
   - Deleting from: /lib/modules/4.2.0-25-generic/updates/dkms/
 - Original module
   - No original module was found for this module on this kernel.
   - Use the dkms install command to reinstall any previous module version.

depmod....

DKMS: uninstall completed.
Examining /etc/kernel/postrm.d .
run-parts: executing /etc/kernel/postrm.d/initramfs-tools 4.2.0-25-generic /boot/vmlinuz-4.2.0-25-generic
update-initramfs: Deleting /boot/initrd.img-4.2.0-25-generic
run-parts: executing /etc/kernel/postrm.d/zz-runlilo 4.2.0-25-generic /boot/vmlinuz-4.2.0-25-generic
Warning: LBA32 addressing assumed
Fatal: raid_setup: stat("/dev/sdb")
run-parts: executing /etc/kernel/postrm.d/zz-update-grub 4.2.0-25-generic /boot/vmlinuz-4.2.0-25-generic
Generating grub configuration file ...
Warning: Setting GRUB_TIMEOUT to a non-zero value when GRUB_HIDDEN_TIMEOUT is set is no longer supported.
Found linux image: /boot/vmlinuz-4.2.0-23-generic
Found initrd image: /boot/initrd.img-4.2.0-23-generic
Found memtest86+ image: /boot/memtest86+.elf
Found memtest86+ image: /boot/memtest86+.bin
Found Windows 7 (loader) on /dev/sda1
Found Ubuntu 14.04.3 LTS (14.04) on /dev/sda5
done
The link /vmlinuz is a damaged link
Removing symbolic link vmlinuz
 you may need to re-run your boot loader[grub]
The link /initrd.img is a damaged link
Removing symbolic link initrd.img
 you may need to re-run your boot loader[grub]
Removing linux-firmware (1.149.3) ...
Errors were encountered while processing:
 linux-image-extra-4.2.0-25-generic
E: Sub-process /usr/bin/dpkg returned an error code (1)
Failed to perform requested operation on package.  Trying to recover:

Current status: 1 (+1) broken.

I tried to install to see if that would patch it:
$ sudo apt-get install linux-image-4.2.0-25-generic
Reading package lists... Done
Building dependency tree
Reading state information... Done
Suggested packages:
  fdutils linux-doc-4.2.0 linux-source-4.2.0 linux-tools
The following packages will be REMOVED:
  linux-image-extra-4.2.0-25-generic
The following NEW packages will be installed:
  linux-image-4.2.0-25-generic
0 upgraded, 1 newly installed, 1 to remove and 0 not upgraded.
1 not fully installed or removed.
Need to get 0 B/17.3 MB of archives.
After this operation, 112 MB disk space will be freed.
Do you want to continue? [Y/n] y
debconf: unable to initialize frontend: Dialog
debconf: (Dialog frontend will not work on a dumb terminal, an emacs shell buffer, or without a controlling terminal.)
debconf: falling back to frontend: Readline
(Reading database ... 201526 files and directories currently installed.)
Removing linux-image-extra-4.2.0-25-generic (4.2.0-25.30) ...
depmod: FATAL: could not load /boot/System.map-4.2.0-25-generic: No such file or directory
run-parts: executing /etc/kernel/postinst.d/apt-auto-removal 4.2.0-25-generic /boot/vmlinuz-4.2.0-25-generic
run-parts: executing /etc/kernel/postinst.d/dkms 4.2.0-25-generic /boot/vmlinuz-4.2.0-25-generic
run-parts: executing /etc/kernel/postinst.d/initramfs-tools 4.2.0-25-generic /boot/vmlinuz-4.2.0-25-generic
update-initramfs: Generating /boot/initrd.img-4.2.0-25-generic
depmod: WARNING: could not open /var/tmp/mkinitramfs_2vAXLr/lib/modules/4.2.0-25-generic/modules.order: No such file or directory
depmod: WARNING: could not open /var/tmp/mkinitramfs_2vAXLr/lib/modules/4.2.0-25-generic/modules.builtin: No such file or directory
run-parts: executing /etc/kernel/postinst.d/pm-utils 4.2.0-25-generic /boot/vmlinuz-4.2.0-25-generic
run-parts: executing /etc/kernel/postinst.d/unattended-upgrades 4.2.0-25-generic /boot/vmlinuz-4.2.0-25-generic
run-parts: executing /etc/kernel/postinst.d/update-notifier 4.2.0-25-generic /boot/vmlinuz-4.2.0-25-generic
run-parts: executing /etc/kernel/postinst.d/zz-runlilo 4.2.0-25-generic /boot/vmlinuz-4.2.0-25-generic
Warning: LBA32 addressing assumed
Fatal: raid_setup: stat("/dev/sdb")
run-parts: /etc/kernel/postinst.d/zz-runlilo exited with return code 1
dpkg: error processing package linux-image-extra-4.2.0-25-generic (--remove):
 subprocess installed post-removal script returned error exit status 1
Errors were encountered while processing:
 linux-image-extra-4.2.0-25-generic
E: Sub-process /usr/bin/dpkg returned an error code (1)

and I tried again to remove it:
$ sudo apt-get remove linux-image-4.2.0-25-generic
Building dependency tree
Reading state information... Done
Package 'linux-image-4.2.0-25-generic' is not installed, so not removed
The following packages will be REMOVED:
  linux-image-extra-4.2.0-25-generic
0 upgraded, 0 newly installed, 1 to remove and 0 not upgraded.
1 not fully installed or removed.
After this operation, 162 MB disk space will be freed.
Do you want to continue? [Y/n] y
(Reading database ... 201526 files and directories currently installed.)
Removing linux-image-extra-4.2.0-25-generic (4.2.0-25.30) ...
depmod: FATAL: could not load /boot/System.map-4.2.0-25-generic: No such file or directory
run-parts: executing /etc/kernel/postinst.d/apt-auto-removal 4.2.0-25-generic /boot/vmlinuz-4.2.0-25-generic
run-parts: executing /etc/kernel/postinst.d/dkms 4.2.0-25-generic /boot/vmlinuz-4.2.0-25-generic
run-parts: executing /etc/kernel/postinst.d/initramfs-tools 4.2.0-25-generic /boot/vmlinuz-4.2.0-25-generic
update-initramfs: Generating /boot/initrd.img-4.2.0-25-generic
depmod: WARNING: could not open /var/tmp/mkinitramfs_RhzV1u/lib/modules/4.2.0-25-generic/modules.order: No such file or directory
depmod: WARNING: could not open /var/tmp/mkinitramfs_RhzV1u/lib/modules/4.2.0-25-generic/modules.builtin: No such file or directory
run-parts: executing /etc/kernel/postinst.d/pm-utils 4.2.0-25-generic /boot/vmlinuz-4.2.0-25-generic
run-parts: executing /etc/kernel/postinst.d/unattended-upgrades 4.2.0-25-generic /boot/vmlinuz-4.2.0-25-generic
run-parts: executing /etc/kernel/postinst.d/update-notifier 4.2.0-25-generic /boot/vmlinuz-4.2.0-25-generic
run-parts: executing /etc/kernel/postinst.d/zz-runlilo 4.2.0-25-generic /boot/vmlinuz-4.2.0-25-generic
Warning: LBA32 addressing assumed
Fatal: raid_setup: stat("/dev/sdb")
run-parts: /etc/kernel/postinst.d/zz-runlilo exited with return code 1
dpkg: error processing package linux-image-extra-4.2.0-25-generic (--remove):
 subprocess installed post-removal script returned error exit status 1
Errors were encountered while processing:
 linux-image-extra-4.2.0-25-generic
E: Sub-process /usr/bin/dpkg returned an error code (1)

for additional info:
$ apt-cache policy linux-image-generic
linux-image-generic:
  Installed: (none)
  Candidate: 4.2.0.25.27
  Version table:
     4.2.0.25.27 0
        500 http://us.archive.ubuntu.com/ubuntu/ wily-updates/main amd64 Packages
        500 http://security.ubuntu.com/ubuntu/ wily-security/main amd64 Packages
     4.2.0.16.18 0
        500 http://us.archive.ubuntu.com/ubuntu/ wily/main amd64 Packages

A: I think I solved my problem -- I dug into those failure logs and saw some lilo errors.
Fatal: raid_setup: stat("/dev/sdb")
run-parts: /etc/kernel/postinst.d/zz-runlilo exited with return code 1

I (thought) was not using lilo because it failed during the Ubuntu install and I switched to grub instead. but apparently  the system thinks lilo is installed/active. The /etc/lilo.conf file pointed to old locations.  I renamed my /etc/lilo.conf file and reran liloconfig and now dpkg does not crash trying to uninstall 4.2.0-25 or install other packages.


text:
Q: How to get list of objects using Mono ResponseEntity objects, as it returns single object @RequestMapping("/api/v1")
public class RemoteActionHistoryController {

    public Mono<ResponseEntityDTO<List<RemoteActionHistoryDTO>>> excaliburData(@PathVariable(name = "deviceId", required = true)
String deviceId) {
        return service.getRemoteActionHistory(deviceId);
    }
}

public class RemoteActionHistoryServiceImpl {

    @Autowired
    RemoteActionHistoryRepository arrowFlightRepository;

    @Override
    public Mono<ResponseEntityDTO<List<RemoteActionHistoryDTO>>> getRemoteActionHistory(String deviceId) throws Exception {
        return (Mono<ResponseEntityDTO<List<RemoteActionHistoryDTO>>>) arrowFlightRepository.getRemoteActionDetailsByDeviceId(deviceId).collectList().flatMap(mapper);
    }

    Function<List<RemoteActionHistory>, Mono<ResponseEntityDTO<RemoteActionHistoryDTO>>> mapper = remoteActions -> {
        var remoteActionDTO = new RemoteActionHistoryDTO();
        if (CollectionUtils.isEmpty(remoteActions)) {
            return Mono.justOrEmpty(new ResponseEntityDTO<>(RemoteActionHistoryConstants.CODE_RET_000, null, remoteActionDTO));
        }
        System.out.println("Printing remoteActions"+remoteActions);
        for (RemoteActionHistory excaliburData : remoteActions) {
            remoteActionDTO.setStartDateTime(excaliburData.getStartDateTime());
            remoteActionDTO.setEndDateTime(excaliburData.getEndDateTime());
            remoteActionDTO.setRemoteActionType(excaliburData.getCommand());
            remoteActionDTO.setTaskStatus(excaliburData.getStatus());
        }
        return Mono.justOrEmpty(new ResponseEntityDTO<>(RemoteActionHistoryConstants.CODE_RET_000, null, remoteActionDTO));
    };
}

public class RemoteActionHistoryServiceImpl {

    @Autowired
    RemoteActionHistoryRepository arrowFlightRepository;

    @Override
    public Mono<ResponseEntityDTO<List<RemoteActionHistoryDTO>>> getRemoteActionHistory(String deviceId) throws Exception {

        return (Mono<ResponseEntityDTO<List<RemoteActionHistoryDTO>>>) arrowFlightRepository.getRemoteActionDetailsByDeviceId(deviceId).collectList().flatMap(mapper);
    }

    Function<List<RemoteActionHistory>, Mono<ResponseEntityDTO<RemoteActionHistoryDTO>>> mapper = remoteActions -> {
        var remoteActionDTO = new RemoteActionHistoryDTO();
        if (CollectionUtils.isEmpty(remoteActions)) {
            return Mono.justOrEmpty(new ResponseEntityDTO<>(RemoteActionHistoryConstants.CODE_RET_000, null, remoteActionDTO));
        }
        System.out.println("Printing remoteActions"+remoteActions);
        for (RemoteActionHistory excaliburData : remoteActions) {
            remoteActionDTO.setStartDateTime(excaliburData.getStartDateTime());
            remoteActionDTO.setEndDateTime(excaliburData.getEndDateTime());
            remoteActionDTO.setRemoteActionType(excaliburData.getCommand());
            remoteActionDTO.setTaskStatus(excaliburData.getStatus());

        }
        return Mono.justOrEmpty(new ResponseEntityDTO<>(RemoteActionHistoryConstants.CODE_RET_000, null, remoteActionDTO));
    };
}

public class RemoteActionHistoryRepositoryImpl {

    @Override
    public Flux<RemoteActionHistory> getRemoteActionDetailsByDeviceId(String deviceId) throws Exception {
        return Flux.fromIterable(getExcaliburData(String.format(query, tableName, deviceId), true));
    }

    private List<RemoteActionHistory> getExcaliburData(String query, boolean retry) throws Exception {
        List<RemoteActionHistory> remoteActionData = new ArrayList<>();
        try (final FlightStream flightStream = adhocFlightClientConfig.createAdhocFlightClient().runQuery(query);) {
            while (flightStream.next()) {

                if (!flightStream.hasRoot()) {
                    break;
                }
                VectorSchemaRoot vectorSchemaRoot = flightStream.getRoot();

                TimeStampMilliVector createdDateVector = (TimeStampMilliVector) vectorSchemaRoot
                        .getVector(RemoteActionHistoryConstants.CREATED_DATE_TIME);
                TimeStampMilliVector modifiedDateVector = (TimeStampMilliVector) vectorSchemaRoot
                        .getVector(RemoteActionHistoryConstants.MODIFIED_DATE_TIME);

                RemoteActionHistory remoteAction = null;
                for (int i = 0; i < vectorSchemaRoot.getRowCount(); i++) {
                    remoteAction = new RemoteActionHistory();
                    remoteAction.setStartDateTime(createdDateVector.isNull(i)? null : new Timestamp(createdDateVector.get(i)));
                    remoteAction.setEndDateTime(modifiedDateVector.isNull(i)? null : new Timestamp(modifiedDateVector.get(i)));

                    remoteActionData.add(remoteAction);
                }

        } catch (Exception ex) {
            log.error(String.format("Exception string : %s with retryEnabled is %s", ex.toString(),retry));
            if (retry && StringUtils.containsIgnoreCase(ex.toString(), RemoteActionHistoryConstants.UNAUTHENTICATED_ERROR)) {
                adhocFlightClientConfig.removeToken();
                getExcaliburData(query, false);
            }
            throw ex;
        }
        return remoteActionData;
    }
}

I have attached the result which I'm currently getting single record. when i debugged the code in the object i have multiple records but it shows only one record in postman


text:
Q: Generically get the name of the current class? When logging data, I want a generic reference to the containing class. That way, if the code is moved elsewhere, the class name will change accordingly. (Otherwise, if the code moves to nameof(Class2), it will still be logged incorrectly as nameof(Class1)). For example:
class Class_Name {
   ICommand Command_Name =>
        new RelayCommand(() =>
        {
           // An loggable event occurs

           // Is there a smart and uncomplicated way of doing this generically?
           var provenance = $"{nameof(Class_Name)}.{nameof(Command_Name)}";

           // The event of whatever kind gets logged
      });
   }

   // OR
   void Method_Name() {
      var provenance = $"{nameof(Class_Name)}.{nameof(Method_Name)}";
   }
}

Using a generic nameof(this), where this should refer to the class itself, causes a compilation error: CS8081: Expression does not have a name. Using this.GetType() causes the same problem.
Not really understanding why the this keyword does not refer to the containing class in this context. Is there a way to refer to the current class generically?

A: If you combine the suggestion in the comments (this.GetType().Name) with a [CallerMemberName] attribute via a helper method, you can accomplish what you're looking for in a reusable fashion.
public class Class_Name
{
    public void Method_Name()
    {
        var provenance = CreateProvenance();
        Console.WriteLine(provenance);
    }

    private string CreateProvenance([CallerMemberName] string methodName = "")
    {
        return $"{this.GetType().Name}.{methodName}";
    }
}

This outputs "Class_Name.Method_Name".
You can even turn this into a handy extension method that allows you to call it from any method.
public class Class_Name
{
    public void Method_Name()
    {
        var provenance = this.CreateProvenance();
        Console.WriteLine(provenance);
    }
}

public static class ProvenanceExtensions
{
    public static string CreateProvenance(this object context,
        [CallerMemberName] string methodName = "")
    {
        return $"{context.GetType().Name}.{methodName}";
    }
}

As Jeppe Stig Nielsen pointed out, you may not want the inheriting runtime type to be used, which is what context.GetType().Name will return. If you want to get the compile-time type instead, you can use generics.
public static class ProvenanceExtensions
{
    public static string CreateProvenance<T>(this T context,
        [CallerMemberName] string methodName = "")
    {
        return $"{typeof(T).Name}.{methodName}";
    }
}

A: By design:

A nameof expression is evaluated at compile time and has no effect at
run time.

To access the type dynamically, in the runtime, you may use the GetType method. Just rememeber not to combine it with the nameof.
class Class_Name {
   void Method_Name() {
      // An event occurs

      // Is there a smart and uncomplicated way of doing this generically?
      var provenance = $"{this.GetType().Name}.{MethodBase.GetCurrentMethod().Name}";

      // The event of whatever kind gets logged
   }
}


text:
Q: Make emacs org-mode deadlines and scheduled blocked tasks visible in agenda view Here are the relevant parts of my .emacs
(setq org-enforce-todo-dependencies t)
(setq org-enforce-todo-checkbox-dependencies t)
(setq org-agenda-dim-blocked-tasks 'invisible)

When I visit my agenda view I want to see tasks which are scheduled or have a deadline (even if they are blocked by another task and are therefor stricly speaking rightly invisible).
Currently those tasks are not visible whilst they are being blocked by other tasks.
I would however prefer that an exception be made for these tasks which have been scheduled or given a deadline and that they be made visibile so that I maintain active awareness of them.

A: This could be accomplished by splitting off the scheduled and deadline tasks with a custom agenda view. Only scheduled and deadline items would be shown in the first block, and the setting to make blocked tasks invisible can be applied to uniquely to a the second block. For example:
;; Retain your default settings
(setq org-enforce-todo-dependencies t)
(setq org-enforce-todo-checkbox-dependencies t)
(setq org-agenda-dim-blocked-tasks t)

;; Create the custom agenda view
(setq org-agenda-custom-commands
 '(("c"
    "Agenda to show deadlines & hide blocked"
    (
     (agenda ""
            ((org-agenda-entry-types '(:deadline :scheduled))))
     (tags-todo "-TODO=\"DONE\""
          ((org-agenda-skip-entry-if 'deadline 'scheduled)
           (org-agenda-dim-blocked-tasks 'invisible)))
))))

A: Isn't it because of your setting:
(setq org-agenda-dim-blocked-tasks 'invisible)

?


text:
Q: How to implement blocking listening function in separate thread while the main keeps working in Python I have main method in module main.py which calls a method in another module called listener.py. They look like this.
main.py

def main():
   listener.start_server()
   print("Test")

listener.py

def start_server():
    t_server = threading.Thread(target=server.start)
    t_server.start()
    # signal.pause()

The listener thread is calling a class function in another module called server.py which has WHILE loop that blocks.
I don't want my main method to block, and it prints ("Test") indeed. However, than I am not able to catch KeyboardInterrupt in the listening thread, and that is why I need signal.pause(). When I use signal.pause() the main thread blocks and the print statement is not executed until the listening thread is finished. Is there any way to combine these two so that the main thread does not block when using signal.pause()?

A: For all the people who will come across this problem here is the simple solution:
IMPLEMENT SIGNAL HANDLER AND DO NOT USE signal.pause()
By implementing signal handler, the main method will continue to work, i.e the method in which the thread was created won't block. It is a simple solution I did not come across.
So instead of using:signal.pause()
use this:
def start_server():
   t_server = threading.Thread(target=server.start)
   t_server.start()
   # signal.pause()
   signal.signal(signal.SIGINT, handler)

def handler(signum, frame):
   ... # do whaterver you want to do, throw an exception, close your resources etc.


text:
Q: SQL Case Expression (Conditional) This is my CASE Expression:
case when count(distinct fcia.UserKey) > 1 and dd.FullDate between @CalcDate and @DefaultDate
            then count(distinct fcia.UserKey)
else case when count(distinct fcia.UserKey) > 1 and dd.FullDate not between @CalcDate and @DefaultDate
            then 0
else -1
end
end as StudentCount,

I would like to only display 1 condition, for example:
If the count > 1 and between the two dates then display
If the count > 1 and NOT BETWEEN dates then ONLY display if not equal to the above condition.
Lastly, else -1 if both conditions above do not equate.

A: Your current attempt is close.  The correct syntax is:
CASE WHEN (condition1) THEN ... WHEN (condition2) THEN ... ELSE ... END

So use this CASE statement:
CASE WHEN COUNT(DISTINCT fcia.UserKey) > 1 AND
          dd.FullDate BETWEEN @CalcDate AND @DefaultDate
     THEN COUNT(DISTINCT fcia.UserKey)
     WHEN COUNT(DISTINCT fcia.UserKey) > 1 AND
          dd.FullDate NOT BETWEEN @CalcDate AND @DefaultDate
     THEN 0
     ELSE -1
END AS StudentCount