text:
Q: how to make Collectionviewsource with entityframework and observablecollection type independent I've got a couple of pieces of code that I would love to make type independent.
context:
I've got an edmx file generated from a couple (8) of tables from a mssql database.
Using linq on these entity's I want to get a observable collection that I can use as a source for a CollectionViewSource, which in turn is bound to a datagrid. apply some filterting etc..
the problem:
The problem i'm getting is when i want the code for the binding/filtering/adding rows/removing rows to be independent of which table i generate my collection from. As of now I can only find a workable solution if I use switchcases in a number of places in my code. And I would rather not in favor of reuse-ability.
the question:
What do I do, what do i need to change, what do I mis. in short how do I get rid of the switchcases?
code snippit:
        ent = new Access2SQLEntitiesCon();
        CVS = (CollectionViewSource)this.Resources["CVS"];
        ///don't want this \/
        switch (tbl_enum)
        {
            case 1:
                    var wnings = from woning in ent.tblWoning
                             where woning.volg == ProjNum
                             select woning;
                var _oc  =  new ObservableCollection<tblWoning>(wnings);
                _oc.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(OC_CollectionChanged);
                CVS.Source = _oc;
                    break;
        }
        //don't want that /\

        CVS.Filter += CVS_Filter;
        MakeFilterListEFM();

so, I can post the other two problem-area's but I think this will do for now. I Get that I can change the linq part to something more dynamic but that not where the issue is. Its the observable collection and its mandatory type... :(
edit:cont:
I try'd using a ObservableCollection<object> but then my DataGrid just displays a bunch of small horizontal lines. Because it doesn't know anymore what type of items it has to display. Is there maybe a way to have that in another variable en point that (via datatemplate?) to the datagrid in order for the autogenerated columns to work again.
edit 2:
In short. What do I need to Do to replace ObservableConnection<tblWoning> with ObservableConnection<object> or ObservableConnection<dynamic>. But keeping the ability to autogenerate columns in the datagrid.


text:
Q: Compilation error from setup arm mbed environment I set up mbed-CLI in my Windows environment following step by step:
https://os.mbed.com/docs/mbed-os/v5.11/tools/windows.html
I installed Mercurial and the Arm Compiler 5.
I set up the environment variables see below.
I then try to compile a default blinky project I exported from the online compiler to a zip file. I initialise the repository. I compile with:
    mbed compile -t ARM -m LPC1768 -v

But obtain:
    [mbed] Working path "C:\Users\xx\OneDrive\Documents\Mbed\mbed-os-example-blinky_zip_lpc1768" (program)

    [mbed] Exec "C:\Python27\python.exe -u C:\Users\xx\OneDrive\Documents Mbed\mbed-os-example-blinky_zip_lpc1768\mbed-os\tools\make.py -t ARM -m LPC1768 --source . --build .\BUILD\LPC1768\ARM -v" in "C:\Users\xx\OneDrive Documents\Mbed\mbed-os-example-blinky_zip_lpc1768"

    WARNING:
    MBED_ARM_PATH set as environment variable but doesn't exist usage:

    make.py [-h] [-m MCU] [-t TOOLCHAIN] [--color] [--cflags CFLAGS]

           [--asmflags ASMFLAGS] [--ldflags LDFLAGS] [-c]

           [--profile PROFILE] [--app-config APP_CONFIG]

           [-p PROGRAM | -n PROGRAM | -L | -S [{matrix,toolchains,targets}]]

           [-j JOBS] [-v] [--silent] [-D MACROS] [-f GENERAL_FILTER_REGEX]

           [--stats-depth STATS_DEPTH] [--automated] [--host HOST_TEST]

           [--extra EXTRA] [--peripherals PERIPHERALS]

           [--dep DEPENDENCIES] [--source SOURCE_DIR]

           [--duration DURATION] [--build BUILD_DIR] [-N ARTIFACT_NAME]

           [--ignore IGNORE] [-b BAUD] [--rpc] [--usb] [--dsp] [--testlib]
           [--build-data BUILD_DATA] [-l LINKER_SCRIPT]

    make.py: error: Could not find executable for ARM.

    Currently set search path: No path set

    [mbed] ERROR: "C:\Python27\python.exe" returned error.
   Code: 2

I set up the path with the command:
    mbed config -G ARM_PATH <path to ARM bin\>"

I tried different paths :

*

*in local / global(-G)

*with and without the ""

*use slash and anti-slash,

*bin/bin64,

*add armcc at the end of the path / armcc.exe,

*add Windows System Environment variables: MBED_ARM_PATH, as C:\Program Files (x86)\ARM_Compiler_5.06u6\bin64
Using :
    mbed config --list

Provides me the result:
    [mbed] Working path "C:\Users\xx\OneDrive\Documents\Mbed\mbed-os-example-blinky_zip_lpc1768" (program)

    [mbed] Global config:
    ARM_PATH=C:\Program Files (x86)\ARM_Compiler_5.06u6\bin64\armcc
    GCC_ARM_PATH=C:\Program Files (x86)\GNU Tools ARM Embedded\6 2017-q2-update\bin

    MBED_ARM_PATH=C:\Program Files (x86)\ARM_Compiler_5.06u6"

    [mbed] Local config (C:\Users\xx\OneDrive\Documents\Mbed\mbed-os-example-blinky_zip_lpc1768):

    ARM_PATH=C:\Program Files (x86)\ARM_Compiler_5.06u6\bin64\armcc

I know mbed priority will be local, then global then system path. I'm not sure what is wrong here. Any ideas would be welcome. Please let me know if you need any screenshot. Thank you in advance.

A: Add the ARM Compiler path to your PATH variable in system environment variables and then try again. After changing the environment variables, just re-run the cmd terminal - worth trying restarting the PC if nothing works.
Also try where armcc in cmd and check if the correct path appears as the output of this command.

redpajama_set_name: RedPajamaStackExchange


text:
Q: List all available model attributes in Thymeleaf For debugging purposes I would like to list all model attributes available to my thymeleaf template while it is rendering.
Something like:

But obviously that's nonsense, and I get a well-deserved error.
(org.springframework.expression.spel.SpelParseException: EL1070E:(pos 0): Problem parsing left operand)
Is there a way of outputting such debug information?  I'd settle even for some logging output.
Or, does Thymeleaf provide something similar to Struts 2's struts.devMode where it added a debug section at the bottom of the page listing all available properties?

A: these are all the logging available configurations :
log4j.logger.org.thymeleaf=DEBUG
log4j.logger.org.thymeleaf.TemplateEngine.CONFIG=DEBUG
log4j.logger.org.thymeleaf.TemplateEngine.TIMER=DEBUG
log4j.logger.org.thymeleaf.TemplateEngine.cache.TEMPLATE_CACHE=DEBUG
log4j.logger.org.thymeleaf.TemplateEngine.cache.FRAGMENT_CACHE=DEBUG
log4j.logger.org.thymeleaf.TemplateEngine.cache.MESSAGE_CACHE=DEBUG
log4j.logger.org.thymeleaf.TemplateEngine.cache.EXPRESSION_CACHE=DEBUG

these will log all the thymeleaf actions. I hope it is helpful.

A: Try this:

A: The accepted answer does not seem to work for Thymeleaf 3; here's an update.  Please note that I'm using Spring; this might not work for non-Spring apps.

        param

        session

        application

That said, what I've done is created a standalone Bean that makes things a bit prettier and dumps to logs instead of to HTML:
@Component
public class ThymeleafDumper {

    private Logger log = LoggerFactory.getLogger(ThymeleafDumper.class);

    public void dumpToLog(WebEngineContext ctx) {
        log.debug("Thymeleaf context: {}", formatThisUpNicely(ctx));
    }

    // ... etc
}

Where formatThisUpNicely can use ctx.getVariableNames(), put the results into a SortedMap, export to json, whatever.  Don't forget those three 'special' variables!
Then expose an instance of it as a @ModelAttribute in a Controller or a ControllerAdvice:
@ControllerAdvice
public class SomeControllerAdvice {

    @Autowired
    private ThymeleafDumper thymeleafDumper;

    @ModelAttribute("dumper")
    public ThymeleafDumper dumper() {
        return this.thymeleafDumper;
    }
}

Then in my template run:

A: Thymeleaf 3.0:
To put it short, try the following:

When a @Controller returns some value stored in a Spring Model, the values are actually stored as request parameters, which is accessible using:
request.getParameter("paramName");
Thymeleaf provides a similar functionality: "Web context namespaces for request/session attributes", the syntax is as stated.
The Thymeleaf built-in ${param} kewords returns an  WebRequestParamsVariablesMap extends VariablesMap<String,String[]> object,
whose keySet() method returns a String[], which contains those variable names within a httprequest.


text:
Q: Flutter custom radio widget with images I am trying to create a custom radio widget with images. Question: Let's say I need an image from a group to change when the user clicks on it to show that this particular button is activated. How can I implement this?
class _RadioWidgetState extends State<RadioWidget> {
  int _radioValue = 0;
  void _handleRadio(int value) {
    setState(() {
      _radioValue = value;
      switch (_radioValue) {
        case 0:
        break;
        case 1:
          break;
        case 0:
          break;
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Row(mainAxisAlignment: MainAxisAlignment.center, children: [
      Expanded(
        child: GestureDetector(
          onTap: () => setState(() {
            _radioValue = 0;
            print(_radioValue);
            _handleRadio(0);
          }),
          child: Container(child: Image.asset('assets/images/asset1.png')),
        ),
      ),
      Expanded(
        child: GestureDetector(
          onTap: () => setState(() {
            _radioValue = 1;
            print(_radioValue);
          }),
          child: Container(child: Image.asset('assets/images/asset2.png')),
        ),
      ),
      Expanded(
        child: GestureDetector(
          onTap: () => setState(() {
            _radioValue = 2;
            print(_radioValue);
          }),
          child: Container(child: Image.asset('assets/images/asset3.png')),
        ),
      ),
    ]);
  }
}

A: use the _radioValue to change the image
child: Container(child: Image.asset(_radioValue == 0
  ? 'assets/images/asset1_selected.png'
  : 'assets/images/asset1.png')
),


text:
Q: Locking popup position to element, or faking a popup with layers for in-place editing in an ItemsControl What I am trying to achieve is essentially in-place editing of a databound object inside an ItemsControl in wpf.
my ItemsControl is a horizontal WrapPanel containing multiple instances of a usercontrol (NameControl) which displays as a little pink Glyph with a person's name. It looks like this

With a popup I am able to show an editor for this "Name" (Other properties of the bound object things like Address,Gender etc.) and this works absoluttely fine. My XAML at this point would be along the lines of
<Style x:Key="NamesStyle" TargetType="{x:Type ItemsControl}">
    <Setter Property="ItemsPanel">
        <Setter.Value>
            <ItemsPanelTemplate>
                <WrapPanel Orientation="Horizontal" />
            </ItemsPanelTemplate>
        </Setter.Value>
    </Setter>
    <Setter Property="ItemTemplate">
        <Setter.Value>
            <DataTemplate>
            <StackPanel>
                <Button Command="{Binding EditName}" BorderThickness="0" Background="Transparent" Panel.ZIndex="1">
                    <widgets:NameControl />
                </Button>
                <Popup IsOpen="{Binding IsEditMode}"
                            PlacementTarget="{Binding ElementName=button}"
                            Margin="0 5 0 0" Placement="Relative" AllowsTransparency="True" >

                <Border Background="White" BorderBrush="DarkOrchid" BorderThickness="1,1,1,1" CornerRadius="5,5,5,5"
                        Panel.ZIndex="100">
                    <Grid ShowGridLines="False" Margin="5" Background="White" Width="300">
                        <!-- Grid Content - just editor fields/button etc -->
                    </Grid>
                </Border>
                </Popup>
            </StackPanel>
        </DataTemplate>
        </Setter.Value>
    </Setter>
</Style>

Giving an output when I click a Name looking like

With this look im quite happy (apart from my awful choice of colours!!) except that the popup does not move with the widow (resize/minimize/maximize) and that popup is above everything even other windows.
So one way to solve part of that is to "attach" or lock the popup position to the element. I have not found a good/easy/xaml way to do that. Ive come across a few code-based solutions but im not sure I like that. It just has a bit of a smell about it.
Another solution ive tried to achieve is to ditch the popup and try to emulate the behaviour of a layer/panel that sits above the other names but is position over (or below, im not fussy) the associated name control.
Ive tried a few different things, mainly around setting Panel.ZIndex on controls within a PanelControl (The Grid, the WrapPanel, a DockPanel on the very top of my MainWindow) with little success. I have implemented a simple BoolToVisibilityConverter to bind my editor Grid's Visibility property to my IsEditMode view model property and that works fine, but I cant for the life of me arrange my elements in the ItemsControl to show the editor grid over the names.
To do what is described above I simply commented out the Popup and added the following binding to the Border which contains the editor grid Visibility="{Binding IsEditMode, Converter={StaticResource boolToVisibility}}".
All that does is this:

It just shows the popup under the name but not over the others.
Any help? What am I doing wrong?

A: Sounds like a job for the AdornerLayer to me.
My implementation will just display one 'popup' at a time, and you can hide it by clicking the button another time. But you could also add a small close button to the ContactAdorner, or stick with your OK button, or fill the AdornerLayer behind the ContactAdorner with an element that IsHitTestVisible and reacts on click by hiding the open Adorner (so clicking anywhere outside closes the popup).
Edit: Added the small close button at your request. Changes in ContactAdorner and the ContactDetailsTemplate.
Another thing that you might want to add is repositioning of the adorner once it is clipped from the bottom (I only check for clipping from the right).

Xaml:
<UserControl x:Class="WpfApplication1.ItemsControlAdorner"
                 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
                 xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
                 xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
                 mc:Ignorable="d"
                 xmlns:local="clr-namespace:WpfApplication1"
                 d:DesignHeight="300" d:DesignWidth="300">

    <UserControl.DataContext>
        <local:ViewModel />
    </UserControl.DataContext>

    <UserControl.Resources>
        <local:EnumToBooleanConverter x:Key="EnumToBooleanConverter" />

        <!-- Template for the Adorner -->
        <DataTemplate x:Key="ContactDetailsTemplate" DataType="{x:Type local:MyContact}" >
            <Border Background="#BBFFFFFF" BorderBrush="DarkOrchid" BorderThickness="1" CornerRadius="5" TextElement.Foreground="DarkOrchid" >
                <Grid Margin="5" Width="300">
                    <Grid.RowDefinitions>
                        <RowDefinition Height="Auto" />
                        <RowDefinition Height="Auto" />
                        <RowDefinition Height="Auto" />
                        <RowDefinition Height="Auto" />
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="*"/>
                        <ColumnDefinition Width="*"/>
                        <ColumnDefinition Width="Auto"/>
                    </Grid.ColumnDefinitions>
                    <TextBlock Text="Full name" />
                    <TextBox Grid.Row="1" Text="{Binding FullName, UpdateSourceTrigger=PropertyChanged}" />
                    <TextBlock  Grid.Row="2" Text="Address" />
                    <TextBox Grid.Row="3" Grid.ColumnSpan="2" Text="{Binding Address}" />
                    <TextBlock Grid.Column="1" Text="Gender" />
                    <StackPanel Orientation="Horizontal" Grid.Column="1" Grid.Row="1" >
                        <RadioButton Content="Male" IsChecked="{Binding Gender, Converter={StaticResource EnumToBooleanConverter}, ConverterParameter={x:Static local:Gender.Male}}" />
                        <RadioButton Content="Female" IsChecked="{Binding Gender, Converter={StaticResource EnumToBooleanConverter}, ConverterParameter={x:Static local:Gender.Female}}" />
                    </StackPanel>
                    <Button x:Name="PART_CloseButton" Grid.Column="2" Height="16">
                        <Button.Template>
                            <ControlTemplate>
                                <Border Background="#01FFFFFF" Padding="3" >
                                    <Path Stretch="Uniform" ClipToBounds="True" Stroke="DarkOrchid" StrokeThickness="2.5" Data="M 85.364473,6.9977109 6.0640998,86.29808 6.5333398,85.76586 M 6.9926698,7.4977169 86.293043,86.79809 85.760823,86.32885"  />
                                </Border>
                            </ControlTemplate>
                        </Button.Template>
                    </Button>
                </Grid>
            </Border>
        </DataTemplate>

        <!-- Button/Item style -->
        <Style x:Key="ButtonStyle1" TargetType="{x:Type Button}" >
            <Setter Property="Foreground" Value="White" />
            <Setter Property="FontFamily" Value="Times New Roman" />
            <Setter Property="Background" Value="#CC99E6" />
            <Setter Property="BorderThickness" Value="0" />
            <Setter Property="MinHeight" Value="24" />
            <Setter Property="Margin" Value="3,2" />
            <Setter Property="Padding" Value="3,2" />
            <Setter Property="Border.CornerRadius" Value="8" />
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="Button">
                        <Border CornerRadius="{TemplateBinding Border.CornerRadius}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Padding="{TemplateBinding Padding}" Margin="{TemplateBinding Margin}" >
                            <ContentPresenter VerticalAlignment="Center" HorizontalAlignment="Center" />
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

        <!-- ItemsControl style -->
        <Style x:Key="NamesStyle" TargetType="{x:Type ItemsControl}">
            <Setter Property="ItemsPanel">
                <Setter.Value>
                    <ItemsPanelTemplate>
                        <WrapPanel Orientation="Horizontal" />
                    </ItemsPanelTemplate>
                </Setter.Value>
            </Setter>
            <Setter Property="ItemTemplate">
                <Setter.Value>
                    <DataTemplate>
                        <Button x:Name="button" Style="{StaticResource ButtonStyle1}" Content="{Binding FullName}" >
                            <i:Interaction.Behaviors>
                                <local:ShowAdornerBehavior DataTemplate="{StaticResource ContactDetailsTemplate}" />
                            </i:Interaction.Behaviors>
                        </Button>
                    </DataTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </UserControl.Resources>

    <Grid>
        <ItemsControl ItemsSource="{Binding MyContacts}" Style="{StaticResource NamesStyle}" />
    </Grid>

</UserControl>

ShowAdornerBehavior, ContactAdorner, EnumToBooleanConverter:
using System.Windows;
using System.Linq;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Interactivity;
using System.Windows.Media;
using System.Windows.Data;
using System;
namespace WpfApplication1
{
    public class ShowAdornerBehavior : Behavior<Button>
    {
        public DataTemplate DataTemplate { get; set; }

        protected override void OnAttached()
        {
            this.AssociatedObject.Click += AssociatedObject_Click;
            base.OnAttached();
        }

        void AssociatedObject_Click(object sender, RoutedEventArgs e)
        {
            var adornerLayer = AdornerLayer.GetAdornerLayer(this.AssociatedObject);
            var contactAdorner = new ContactAdorner(this.AssociatedObject, adornerLayer, this.AssociatedObject.DataContext, this.DataTemplate);
        }
    }

    public class ContactAdorner : Adorner
    {
        private ContentPresenter _contentPresenter;
        private AdornerLayer _adornerLayer;
        private static Button _btn;
        private VisualCollection _visualChildren;

        private double _marginRight = 5;
        private double _adornerDistance = 5;
        private PointCollection _points;

        private static ContactAdorner _currentInstance;

        public ContactAdorner(Button adornedElement, AdornerLayer adornerLayer, object data, DataTemplate dataTemplate)
            : base(adornedElement)
        {
            if (_currentInstance != null)
                _currentInstance.Hide(); // hides other adorners of the same type

            if (_btn != null && _btn == adornedElement)
            {
                _currentInstance.Hide(); // hides the adorner of this button (toggle)
                _btn = null;
            }
            else
            {
                _adornerLayer = adornerLayer;
                _btn = adornedElement;

                // adjust position if sizes change
                _adornerLayer.SizeChanged += (s, e) => { UpdatePosition(); };
                _btn.SizeChanged += (s, e) => { UpdatePosition(); };

                _contentPresenter = new ContentPresenter() { Content = data, ContentTemplate = dataTemplate };

                // apply template explicitly: http://stackoverflow.com/questions/5679648/why-would-this-contenttemplate-findname-throw-an-invalidoperationexception-on
                _contentPresenter.ApplyTemplate();

                // get close button from datatemplate
                Button closeBtn = _contentPresenter.ContentTemplate.FindName("PART_CloseButton", _contentPresenter) as Button;
                if (closeBtn != null)
                    closeBtn.Click += (s, e) => { this.Hide(); _btn = null; };

                _visualChildren = new VisualCollection(this); // this is needed for user interaction with the adorner layer
                _visualChildren.Add(_contentPresenter);

                _adornerLayer.Add(this);

                _currentInstance = this;

                UpdatePosition(); // position adorner
            }
        }

        /// <summary>
        /// Positioning is a bit fiddly.
        /// Also, this method is only dealing with the right clip, not yet with the bottom clip.
        /// </summary>
        private void UpdatePosition()
        {
            double marginLeft = 0;
            _contentPresenter.Margin = new Thickness(marginLeft, 0, _marginRight, 0); // "reset" margin to get a good measure pass
            _contentPresenter.Measure(_adornerLayer.RenderSize); // measure the contentpresenter to get a DesiredSize
            var contentRect = new Rect(_contentPresenter.DesiredSize);
            double right = _btn.TranslatePoint(new Point(contentRect.Width, 0), _adornerLayer).X; // this does not work with the contentpresenter, so use _adornedElement

            if (right > _adornerLayer.ActualWidth) // if adorner is clipped by right window border, move it to the left
                marginLeft = _adornerLayer.ActualWidth - right;

            _contentPresenter.Margin = new Thickness(marginLeft, _btn.ActualHeight + _adornerDistance, _marginRight, 0); // position adorner

            DrawArrow();
        }

        private void DrawArrow()
        {
            Point bottomMiddleButton = new Point(_btn.ActualWidth / 2, _btn.ActualHeight - _btn.Margin.Bottom);
            Point topLeftAdorner = new Point(_btn.ActualWidth / 2 - 10, _contentPresenter.Margin.Top);
            Point topRightAdorner = new Point(_btn.ActualWidth / 2 + 10, _contentPresenter.Margin.Top);

            PointCollection points = new PointCollection();
            points.Add(bottomMiddleButton);
            points.Add(topLeftAdorner);
            points.Add(topRightAdorner);

            _points = points; // actual drawing executed in OnRender
        }

        protected override void OnRender(DrawingContext drawingContext)
        {
            // Drawing the arrow
            StreamGeometry streamGeometry = new StreamGeometry();
            using (StreamGeometryContext geometryContext = streamGeometry.Open())
            {
                if (_points != null && _points.Any())
                {
                    geometryContext.BeginFigure(_points[0], true, true);
                    geometryContext.PolyLineTo(_points.Where(p => _points.IndexOf(p) > 0).ToList(), true, true);
                }
            }

            // Draw the polygon visual
            drawingContext.DrawGeometry(Brushes.DarkOrchid, new Pen(_btn.Background, 0.5), streamGeometry);

            base.OnRender(drawingContext);
        }

        private void Hide()
        {
            _adornerLayer.Remove(this);
        }

        protected override Size MeasureOverride(Size constraint)
        {
            _contentPresenter.Measure(constraint);
            return _contentPresenter.DesiredSize;
        }

        protected override Size ArrangeOverride(Size finalSize)
        {
            _contentPresenter.Arrange(new Rect(finalSize));
            return finalSize;
        }

        protected override Visual GetVisualChild(int index)
        {
            return _visualChildren[index];
        }

        protected override int VisualChildrenCount
        {
            get { return _visualChildren.Count; }
        }
    }

    // http://stackoverflow.com/questions/397556/how-to-bind-radiobuttons-to-an-enum
    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;
        }
    }
}

ViewModel, MyContact:
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows.Input;
namespace WpfApplication1
{
    public class ViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }

        private ObservableCollection<MyContact> _myContacts = new ObservableCollection<MyContact>();
        public ObservableCollection<MyContact> MyContacts { get { return _myContacts; } set { _myContacts = value; OnPropertyChanged("MyContacts"); } }

        public ViewModel()
        {
            MyContacts = new ObservableCollection<MyContact>()
            {
                new MyContact() { FullName = "Sigmund Freud", Gender = Gender.Male },
                new MyContact() { FullName = "Abraham Lincoln", Gender = Gender.Male },
                new MyContact() { FullName = "Joan Of Arc", Gender = Gender.Female },
                new MyContact() { FullName = "Bob the Khann", Gender = Gender.Male, Address = "Mongolia" },
                new MyContact() { FullName = "Freddy Mercury", Gender = Gender.Male },
                new MyContact() { FullName = "Giordano Bruno", Gender = Gender.Male },
                new MyContact() { FullName = "Socrates", Gender = Gender.Male },
                new MyContact() { FullName = "Marie Curie", Gender = Gender.Female }
            };
        }
    }

    public class MyContact : INotifyPropertyChanged
    {
        private string _fullName;
        public string FullName { get { return _fullName; } set { _fullName = value; OnPropertyChanged("FullName"); } }

        private string _address;
        public string Address { get { return _address; } set { _address = value; OnPropertyChanged("Address"); } }

        private Gender _gender;
        public Gender Gender { get { return _gender; } set { _gender = value; OnPropertyChanged("Gender"); } }

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

    public enum Gender
    {
        Male,
        Female
    }

A: Personally I hate WPF's built in Popup control for exactly those reasons, and my workaround is to use a Custom Popup UserControl
Basically I'll put the Popup in a panel that allows it's children to overlap, such as a Grid or a Canvas, and position it on top of whatever content it's supposed to be on top of.
It includes DependencyProperties to specify it's parent panel and if it's open or not, and is part of the normal VisualTree so it will move around with your Window and act the same way any regular UI element would.
Typical usage would look like this:
<Grid x:Name="ParentPanel">
    <ItemsControl ... />

    <local:PopupPanel Content="{Binding PopupContent}"
        local:PopupPanel.PopupParent="{Binding ElementName=ParentPanel}"
        local:PopupPanel.IsPopupVisible="{Binding IsPopupVisible}" />
</Grid>

The code for the UserControl can be found on my blog along with a downloadable example of its use, but I'll also post a copy of it here.
The XAML for the UserControl is:
<UserControl x:Class="PopupPanelSample.PopupPanel"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:PopupPanelSample"
             FocusManager.IsFocusScope="True"
             >

    <UserControl.Template>
        <ControlTemplate TargetType="{x:Type local:PopupPanel}">
            <ControlTemplate.Resources>
                <!-- Converter to get Popup Positioning -->
                <local:ValueDividedByParameterConverter x:Key="ValueDividedByParameterConverter" />

                <!-- Popup Visibility -->
                <BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" />
                <Style x:Key="PopupPanelContentStyle" TargetType="{x:Type Grid}">
                    <Setter Property="Grid.Visibility" Value="{Binding Path=IsPopupVisible,
                        RelativeSource={RelativeSource AncestorType={x:Type local:PopupPanel}},
                        Converter={StaticResource BooleanToVisibilityConverter}}"/>
                </Style>
            </ControlTemplate.Resources>

            <Grid x:Name="PopupPanelContent" Style="{StaticResource PopupPanelContentStyle}">
                <Grid.Resources>
                    <!-- Storyboard to show Content -->
                    <Storyboard x:Key="ShowEditPanelStoryboard" SpeedRatio="5">
                        <DoubleAnimation
                            Storyboard.TargetName="PopupPanelContent"
                            Storyboard.TargetProperty="RenderTransform.(ScaleTransform.ScaleX)"
                            From="0.00" To="1.00" Duration="00:00:01"
                            />
                        <DoubleAnimation
                            Storyboard.TargetName="PopupPanelContent"
                            Storyboard.TargetProperty="RenderTransform.(ScaleTransform.ScaleY)"
                            From="0.00" To="1.00" Duration="00:00:01"
                            />
                    </Storyboard>
                </Grid.Resources>

                <!-- Setting up RenderTransform for Popup Animation -->
                <Grid.RenderTransform>
                    <ScaleTransform
                        CenterX="{Binding Path=PopupParent.ActualWidth, Converter={StaticResource ValueDividedByParameterConverter}, ConverterParameter=2, RelativeSource={RelativeSource AncestorType={x:Type local:PopupPanel}}}"
                        CenterY="{Binding Path=PopupParent.ActualHeight, Converter={StaticResource ValueDividedByParameterConverter}, ConverterParameter=2, RelativeSource={RelativeSource AncestorType={x:Type local:PopupPanel}}}"
                        />
                </Grid.RenderTransform>

                <!-- Grayscale background & prevents mouse input -->
                <Rectangle
                    Fill="Gray"
                    Opacity="{Binding Path=BackgroundOpacity, RelativeSource={RelativeSource AncestorType={x:Type local:PopupPanel}}}"
                    Height="{Binding RelativeSource={RelativeSource AncestorType={x:Type local:PopupPanel}}, Path=Height}"
                    Width="{Binding RelativeSource={RelativeSource AncestorType={x:Type local:PopupPanel}}, Path=Width}"
                    />

                <!-- Popup Content -->
                <ContentControl x:Name="PopupContentControl"
                                KeyboardNavigation.TabNavigation="Cycle"
                                PreviewKeyDown="PopupPanel_PreviewKeyDown"
                                PreviewLostKeyboardFocus="PopupPanel_LostFocus"
                                IsVisibleChanged="PopupPanel_IsVisibleChanged"
                                HorizontalAlignment="Center" VerticalAlignment="Center"
                                >
                    <ContentPresenter Content="{TemplateBinding Content}" />
                </ContentControl>
            </Grid>
        </ControlTemplate>
    </UserControl.Template>
</UserControl>

And the code-behind the UserControl looks like this:
using System;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Threading;

namespace PopupPanelSample
{
    /// <summary>
    /// Panel for handling Popups:
    /// - Control with name PART_DefaultFocusControl will have default focus
    /// - Can define PopupParent to determine if this popup should be hosted in a parent panel or not
    /// - Can define the property EnterKeyCommand to specifify what command to run when the Enter key is pressed
    /// - Can define the property EscapeKeyCommand to specify what command to run when the Escape key is pressed
    /// - Can define BackgroundOpacity to specify how opaque the background will be. Value is between 0 and 1.
    /// </summary>
    public partial class PopupPanel : UserControl
    {
        #region Fields

        bool _isLoading = false;                    // Flag to tell identify when DataContext changes
        private UIElement _lastFocusControl;        // Last control that had focus when popup visibility changes, but isn't closed

        #endregion // Fields

        #region Constructors

        public PopupPanel()
        {
            InitializeComponent();
            this.DataContextChanged += Popup_DataContextChanged;

            // Register a PropertyChanged event on IsPopupVisible
            DependencyPropertyDescriptor dpd = DependencyPropertyDescriptor.FromProperty(PopupPanel.IsPopupVisibleProperty, typeof(PopupPanel));
            if (dpd != null) dpd.AddValueChanged(this, delegate { IsPopupVisible_Changed(); });

            dpd = DependencyPropertyDescriptor.FromProperty(PopupPanel.ContentProperty, typeof(PopupPanel));
            if (dpd != null) dpd.AddValueChanged(this, delegate { Content_Changed(); });

        }

        #endregion // Constructors

        #region Events

        #region Property Change Events

        // When DataContext changes
        private void Popup_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            DisableAnimationWhileLoading();
        }

        // When Content Property changes
        private void Content_Changed()
        {
            DisableAnimationWhileLoading();
        }

        // Sets an IsLoading flag so storyboard doesn't run while loading
        private void DisableAnimationWhileLoading()
        {
            _isLoading = true;
            this.Dispatcher.BeginInvoke(DispatcherPriority.Render,
                new Action(delegate() { _isLoading = false; }));
        }

        // Run storyboard when IsPopupVisible property changes to true
        private void IsPopupVisible_Changed()
        {
            bool isShown = GetIsPopupVisible(this);

            if (isShown && !_isLoading)
            {
                FrameworkElement panel = FindChild<FrameworkElement>(this, "PopupPanelContent");
                if (panel != null)
                {
                    // Run Storyboard
                    Storyboard animation = (Storyboard)panel.FindResource("ShowEditPanelStoryboard");
                    animation.Begin();
                }
            }

            // When hiding popup, clear the LastFocusControl
            if (!isShown)
            {
                _lastFocusControl = null;
            }
        }

        #endregion // Change Events

        #region Popup Events

        // When visibility is changed, set the default focus
        void PopupPanel_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            if ((bool)e.NewValue)
            {
                ContentControl popupControl = FindChild<ContentControl>(this, "PopupContentControl");
                this.Dispatcher.BeginInvoke(DispatcherPriority.Render,
                    new Action(delegate()
                    {
                        // Verify object really is visible because sometimes it's not once we switch to Render
                        if (!GetIsPopupVisible(this))
                        {
                            return;
                        }

                        if (_lastFocusControl != null && _lastFocusControl.Focusable)
                        {
                            _lastFocusControl.Focus();
                        }
                        else
                        {
                            _lastFocusControl = FindChild<UIElement>(popupControl, "PART_DefaultFocusControl") as UIElement;

                            // If we can find the part named PART_DefaultFocusControl, set focus to it
                            if (_lastFocusControl != null && _lastFocusControl.Focusable)
                            {
                                _lastFocusControl.Focus();
                            }
                            else
                            {
                                _lastFocusControl = FindFirstFocusableChild(popupControl);

                                // If no DefaultFocusControl found, try and set focus to the first focusable element found in popup
                                if (_lastFocusControl != null)
                                {
                                    _lastFocusControl.Focus();
                                }
                                else
                                {
                                    // Just give the Popup UserControl focus so it can handle keyboard input
                                    popupControl.Focus();
                                }
                            }
                        }
                    }
                    )
                );
            }
        }

        // When popup loses focus but isn't hidden, store the last element that had focus so we can put it back later
        void PopupPanel_LostFocus(object sender, RoutedEventArgs e)
        {
            DependencyObject focusScope = FocusManager.GetFocusScope(this);
            _lastFocusControl = FocusManager.GetFocusedElement(focusScope) as UIElement;
        }

        // Keyboard Events
        private void PopupPanel_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Escape)
            {
                PopupPanel popup = FindAncester<PopupPanel>((DependencyObject)sender);
                ICommand cmd = GetPopupEscapeKeyCommand(popup);
                if (cmd != null && cmd.CanExecute(null))
                {
                    cmd.Execute(null);
                    e.Handled = true;
                }
                else
                {
                    // By default the Escape Key closes the popup when pressed
                    var expression = this.GetBindingExpression(PopupPanel.IsPopupVisibleProperty);
                    var dataType = expression.DataItem.GetType();
                    dataType.GetProperties().Single(x => x.Name == expression.ParentBinding.Path.Path)
                        .SetValue(expression.DataItem, false, null);
                }
            }
            else if (e.Key == Key.Enter)
            {
                // Don't want to run Enter command if focus is in a TextBox with AcceptsReturn = True
                if (!(e.KeyboardDevice.FocusedElement is TextBox &&
                     (e.KeyboardDevice.FocusedElement as TextBox).AcceptsReturn == true))
                {
                    PopupPanel popup = FindAncester<PopupPanel>((DependencyObject)sender);
                    ICommand cmd = GetPopupEnterKeyCommand(popup);
                    if (cmd != null && cmd.CanExecute(null))
                    {
                        cmd.Execute(null);
                        e.Handled = true;
                    }
                }

            }
        }

        #endregion // Popup Events

        #endregion // Events

        #region Dependency Properties

        // Parent for Popup
        #region PopupParent

        public static readonly DependencyProperty PopupParentProperty =
            DependencyProperty.Register("PopupParent", typeof(FrameworkElement),
            typeof(PopupPanel), new PropertyMetadata(null, null, CoercePopupParent));

        private static object CoercePopupParent(DependencyObject obj, object value)
        {
            // If PopupParent is null, return the Window object
            return (value ?? FindAncester<Window>(obj));
        }

        public FrameworkElement PopupParent
        {
            get { return (FrameworkElement)this.GetValue(PopupParentProperty); }
            set { this.SetValue(PopupParentProperty, value); }
        }

        // Providing Get/Set methods makes them show up in the XAML designer
        public static FrameworkElement GetPopupParent(DependencyObject obj)
        {
            return (FrameworkElement)obj.GetValue(PopupParentProperty);
        }

        public static void SetPopupParent(DependencyObject obj, FrameworkElement value)
        {
            obj.SetValue(PopupParentProperty, value);
        }

        #endregion

        // Popup Visibility - If popup is shown or not
        #region IsPopupVisibleProperty

        public static readonly DependencyProperty IsPopupVisibleProperty =
            DependencyProperty.Register("IsPopupVisible", typeof(bool),
            typeof(PopupPanel), new PropertyMetadata(false, null));

        public static bool GetIsPopupVisible(DependencyObject obj)
        {
            return (bool)obj.GetValue(IsPopupVisibleProperty);
        }

        public static void SetIsPopupVisible(DependencyObject obj, bool value)
        {
            obj.SetValue(IsPopupVisibleProperty, value);
        }

        #endregion // IsPopupVisibleProperty

        // Transparency level for the background filler outside the popup
        #region BackgroundOpacityProperty

        public static readonly DependencyProperty BackgroundOpacityProperty =
            DependencyProperty.Register("BackgroundOpacity", typeof(double),
            typeof(PopupPanel), new PropertyMetadata(.5, null));

        public static double GetBackgroundOpacity(DependencyObject obj)
        {
            return (double)obj.GetValue(BackgroundOpacityProperty);
        }

        public static void SetBackgroundOpacity(DependencyObject obj, double value)
        {
            obj.SetValue(BackgroundOpacityProperty, value);
        }

        #endregion ShowBackgroundProperty

        // Command to execute when Enter key is pressed
        #region PopupEnterKeyCommandProperty

        public static readonly DependencyProperty PopupEnterKeyCommandProperty =
            DependencyProperty.RegisterAttached("PopupEnterKeyCommand", typeof(ICommand),
            typeof(PopupPanel), new PropertyMetadata(null, null));

        public static ICommand GetPopupEnterKeyCommand(DependencyObject obj)
        {
            return (ICommand)obj.GetValue(PopupEnterKeyCommandProperty);
        }

        public static void SetPopupEnterKeyCommand(DependencyObject obj, ICommand value)
        {
            obj.SetValue(PopupEnterKeyCommandProperty, value);
        }

        #endregion PopupEnterKeyCommandProperty

        // Command to execute when Enter key is pressed
        #region PopupEscapeKeyCommandProperty

        public static readonly DependencyProperty PopupEscapeKeyCommandProperty =
            DependencyProperty.RegisterAttached("PopupEscapeKeyCommand", typeof(ICommand),
            typeof(PopupPanel), new PropertyMetadata(null, null));

        public static ICommand GetPopupEscapeKeyCommand(DependencyObject obj)
        {
            return (ICommand)obj.GetValue(PopupEscapeKeyCommandProperty);
        }

        public static void SetPopupEscapeKeyCommand(DependencyObject obj, ICommand value)
        {
            obj.SetValue(PopupEscapeKeyCommandProperty, value);
        }

        #endregion PopupEscapeKeyCommandProperty

        #endregion Dependency Properties

        #region Visual Tree Helpers

        public static UIElement FindFirstFocusableChild(DependencyObject parent)
        {
            // Confirm parent is valid.
            if (parent == null) return null;

            UIElement foundChild = null;

            int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
            for (int i = 0; i < childrenCount; i++)
            {
                UIElement child = VisualTreeHelper.GetChild(parent, i) as UIElement;

                // This is returning me things like ContentControls, so for now filtering to buttons/textboxes only
                if (child != null && child.Focusable && child.IsVisible)
                {
                    foundChild = child;
                    break;
                }
                // recursively drill down the tree
                foundChild = FindFirstFocusableChild(child);

                // If the child is found, break so we do not overwrite the found child.
                if (foundChild != null) break;
            }
            return foundChild;
        }

        public static T FindAncester<T>(DependencyObject current)
        where T : DependencyObject
        {
            // Need this call to avoid returning current object if it is the same type as parent we are looking for
            current = VisualTreeHelper.GetParent(current);

            while (current != null)
            {
                if (current is T)
                {
                    return (T)current;
                }
                current = VisualTreeHelper.GetParent(current);
            };
            return null;
        }

        /// <summary>
        /// Looks for a child control within a parent by name
        /// </summary>
        public static T FindChild<T>(DependencyObject parent, string childName)
        where T : DependencyObject
        {
            // Confirm parent and childName are valid.
            if (parent == null) return null;

            T foundChild = null;

            int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
            for (int i = 0; i < childrenCount; i++)
            {
                var child = VisualTreeHelper.GetChild(parent, i);
                // If the child is not of the request child type child
                T childType = child as T;
                if (childType == null)
                {
                    // recursively drill down the tree
                    foundChild = FindChild<T>(child, childName);

                    // If the child is found, break so we do not overwrite the found child.
                    if (foundChild != null) break;
                }
                else if (!string.IsNullOrEmpty(childName))
                {
                    var frameworkElement = child as FrameworkElement;
                    // If the child's name is set for search
                    if (frameworkElement != null && frameworkElement.Name == childName)
                    {
                        // if the child's name is of the request name
                        foundChild = (T)child;
                        break;
                    }
                    else
                    {
                        // recursively drill down the tree
                        foundChild = FindChild<T>(child, childName);

                        // If the child is found, break so we do not overwrite the found child.
                        if (foundChild != null) break;
                    }
                }
                else
                {
                    // child element found.
                    foundChild = (T)child;
                    break;
                }
            }

            return foundChild;
        }

        #endregion

    }

    // Converter for Popup positioning
    public class ValueDividedByParameterConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            double n, d;
            if (double.TryParse(value.ToString(), out n)
                && double.TryParse(parameter.ToString(), out d)
                && d != 0)
            {
                return n / d;
            }

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


text:
Q: How to remove a PV from a VG without losing the data on it? I want to detach a PV from a VG, but with preserving the data on it, with the possibility of a re-attach in the future.
The LVs are completely separated on it (no LV has LEs on both the PV to separate, and on the rest).
Doing this would be easy with losing the data on the PV (pvmove, vgreduce), but this would be the opposite what I want.
Is it somehow possible?

A: As @frostschutz explained, in this case the vgsplit tool can be used to split a PV from a VG, and convert it to another, single-PV VG:
vgsplit yourvg newvgname /dev/sdx

It removes the PV /dev/sdx from the VG yourvg, and converts it to a new, single-PV VG named newvgname.
For vgsplit, all the LVs on the PV /dev/sdx should be offline, what can be reached by the command vgchange -an /dev/yourvg/lvname aften unmounting them.
Later the VGs can be re-joined by the vgmerge command.


text:
Q: How to sort object by Date in Dart Want to sort this object by date in dart

I try use build in method .sort but it's not correct

A: For this you have to convert date string into Datetime.
To sort in ascending order you can use:
list_name.sort((a, b) => (DateFormat('yyyy-MMM').parse(a).compareTo(DateFormat('yyyy-MMM').parse(b))));

To sort in descending order use - in this:
l.sort((a, b) => -(DateFormat('yyyy-MMM').parse(a).compareTo(DateFormat('yyyy-MMM').parse(b))));


text:
Q: How to use curl to print certain parts of webpage I am trying to get certain parts of a page to be shown in the output.
<?php //right wing - up to ages 22 - potential range of 84 to 99
$ch = curl_init("https://sofifa.com/players?
aeh=22&ptl=84&pth=99&pn=27&pn=25&pn=23");// This will do
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
$output = curl_exec($ch);
echo $output;
curl_close($ch);
?>

The code above prints the whole html of the URL. I want certain parts to show, such as the players name. Image below shows the whole page being outputted. I am trying to only get the players name to be shown, as well as their rating, age and potential.. So for example the page should output : L SANE : AGE: 21 OV : 84 : PO 92.
Is there any way i can do this?
Image of page

A: you don't use curl to display parts of the page, you use it to fetch the page. then, once you got the page, you must use something else to parse out the part of the page that you're interested in. the page is written in HTML, check this answer for a list of HTML parsing utilities for PHP.
as for how to parse out the specific info from this specific page, there's only 1 tbody tag in the page, and each player has their own dedicated tr tag, that is a direct child of that tbody tag, so you can iterate the tr children of the tbody tag to iterate through the players. each of these tr tags has td children containing the info you want. the text content of the 2nd td tag has their name, the 3rd has the age, the 4th has the rating, and the 5th has the potential.
an example using the DOMDocument parser:
<?php
declare(strict_types = 1);
$ch = curl_init ( "https://sofifa.com/players?aeh=22&ptl=84&pth=99&pn=27&pn=25&pn=23" );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
$output = curl_exec ( $ch );
curl_close ( $ch );
$domd = @DOMDocument::loadHTML ( $output );
foreach ( $domd->getElementsByTagName ( "tbody" )->item ( 0 )->getElementsByTagName ( "tr" ) as $tr ) {
    $tds = $tr->getElementsByTagName ( "td" );
    $player = array (
            'name' => trim ( $tds->item ( 1 )->textContent ),
            'age' => trim ( $tds->item ( 2 )->textContent ),
            'rating' => trim ( $tds->item ( 3 )->textContent ),
            'potential' => trim ( $tds->item ( 4 )->textContent )
    );
    print_r ( $player );
}


text:
Q: Algorithm for pseudo-random function with certain characteristics Over view
I am trying to create a game that would need a pseudo-random function of the following characteristics:

*

*Each player would be allotted a variable (of type float) for their money, the products (of type int*) they own and would want to sell and another variable to show what place they are in.

*Each player would have the right to sell any of their products they own to any other player; and in addition the game involves a computer player which represents the other citizen population of that place who would want to buy the products or sell certain products.

*Each player would have a different place value and each place would have different different cost for each products and the "transport cost" between different places also differs as a function of time.
A brief data structure of a player's profile would is as follows:
typedef struct PLAYER{
    char *name;
    int place;
    int *products;
    int noOfProducts;
    float money;
    PLAYER();
    PLAYER(&ply);
        .
        .
        .
}*ptrPLAYER;

Now I need a pseudo-random function that sets the rate of each product, rate of transport from one place to the other, and the function should also determine what products should the "citizens" player buy or sell and at what rate. The values provided by this function should follow a particular trend for some time and change its trend completely, but the variance should not be high. characteristics of the pseudo function:

*

*Should be the function of the previous values generated and time.

*Should show a gradual change following some trend up to some point.
The question:
The random function should have the following properties:

*

*The variance should be low.

*If we define the function as int *randomFnc( int previousResult[]) the function should follow some trend being very difficult to crack and at the same time, it should not reach a saturation point where beyond that point, the randomFnc(.) provides the same result.

*The random function should generate a set of values (for example 100 values) which are directly dependent upon the previously generated values in some unique way.

A: You can model your process. As a starting point you can choose autoregressive model of type AR(1):
y_t = a_0 + a_1 * y_(t-1) + e_t    (1)

where y is your variable of interest, e_t is gaussian white noise with mean 0 and variance sigma_e_t^2 and a0, a1 are constants.

*

*should be the function of the previous values generated and time.

You can generate number of N of white noise assuming you will need N values of y. Then as you can see, value of y in time t is directly dependent on previous value y_(t-1) and you can always switch between two based on your array of e_t and relation (1).

the variance should be low.

The unconditional variance of y_t is
var(y_t) = sigma_e_t^2 / ( 1 - a_1^2)  if a_1^2 < 1

so you can make it as small as you would like ( in range [sigma_e_t^2, +inf)) .
This process may looks like

You can add trend to make it y_t = a_0 + a_1 * t + a_2 * y_(t-1) + e_t and it will looks something like

More details are needed to be added in your question in order to advise you how to adjust this process further being subjected to other restrictions.


text:
Q: Covering space of a compact connected surface without boundary is a compact surface without boundary Let $p: X' \rightarrow X$ be an n-sheeted cover of $X$. I proved that $X$ being compact implies that $X'$ is compact in the standard way. I started with an open cover of $X'$, projected it under $p$, used compactification to get a finite subset that covers $X$, and then took the inverse image of those subsets to get a finite sub collection of the original open cover.
How can I use this local information in conjunction with compactness of $X'$ and $X$ to show that $X'$ does not have a boundary?
Also, how can I show that $E(X')=nE(X)$ where $E$ is the Euler characteristic.

A: Let $x'\in X'$. Write $p(x')=x$. Let $U$ an open subset which is a chart of $X$ and which contains $x$ such that $p^{-1}(U)=V_1,...,V_n$ such that the restriction $p:V_i\rightarrow U$ is a diffeomorphism. Suppose $x'\in V_{i_0}$. Since $U$ is an open subset of $\mathbb{R}^2$  (the domain of a chart) so is $V_{i_0}$, we deduce that $x'$ has an open neighborhood diffeomorphic to an open subset of $\mathbb{R}^2$ and that the boundary of $X'$ is empty.


text:
Q: Issue due to scope of variable - the value is not changing out the while loop ScriptPath=$(dirname $0)
Userlist=${ScriptPath}/Config_Userlist.csv

user="hive"
export flag=0
sed 1d $Userlist | while read user_list
do

if [[ "$user_list" != "$user" ]]; then
flag=1
fi
done

echo $flag

If the condition passes flag value becomes 1. However when I am getting that variable after the while loop it's again zero. It's not updating the changed value.

A: Pipes create subshells and subshells cannot modify the variables in their parents.
Instead of using sed and piping it to while if your shell supports process substitution you could rewrite it as
while read user_list do;
    ... # all the same stuff you have in your loop
done < <(sed 1d "$Userlist")

and then the while will run in the original shell and you can set flag


text:
Q: Puppeteer - Click on button by class name?  A. Consistency is all over the place; running !headless, I watch it sometimes work, sometimes it doesn't (like types in wrong data), it's really 50/50. How can my code be optimized for 100% reliability?
Update:
Fixed inconsistencies by implementing a promise delay function & delaying actions.
How can I click on a button that is not a submit type nor has a name nor id?
<button class="sb-frap" data-e2e="sendGift">Send gift</button>

JS Path:
document.querySelector("#js-content > div > div:nth-child(6) > span > div > div.absolute.bg-white.overflow-auto.content___2_l5Q > div > div > div > div > div.invisible.base___3dWsJ.alwaysRelative___3FHV5 > div > span > div > button")

await Promise.all([
 await page.waitForSelector(".sb-frap"),
 await page.click('button[class=".sb-frap"]'),
  ]);
})();

Any help will greatly appreciated!

A: Solution = Inspect Element -> Right click -> Copy -> Copy Selector
  await Promise.all([
      await page.click( paste selector here )
    ]);


text:
Q: too much space between two environment create with tcolorbox i want write a maple book, see this example code in that book:
\documentclass{article}
\usepackage{tcolorbox,fancyvrb}
\tcbuselibrary{skins,breakable}

%-------------------------------------------------- Code Environment
\newenvironment{code}
 {\VerbatimEnvironment
  \begin{tcolorbox}[
    breakable,
    colback=red!5!white,
    colframe=red!75!black,
  ]%
  \begin{Verbatim}}
 {\end{Verbatim}\end{tcolorbox}}

\newenvironment{outc}
 {\begin{tcolorbox}[
    breakable,
    left=0mm,right=0mm,top=0mm,bottom=0mm,
%    boxsep=0mm,
    colback=white,
    coltext=blue,
    colframe=gray!50,
  ]}%
 {\end{tcolorbox}}

%\newenvironment{outcode}
% {\begin{outc}\begin{equation}}
% {\end{equation}\end{outc}}
\newenvironment{outcode}
 {\begin{outc}\[}
 {\]\end{outc}}
%-------------------------------------------------- Code Environment

\begin{document}

In this example, we see too much space between this two environment \textbf{code} and \textbf{outcode}:

\begin{code}
> 2+3;
\end{code}
\begin{outcode}
5
\end{outcode}

\end{document}

output is:

question is:
How can i write output below the maple code with two different color for background and text,and separate those with, for example \tcblower command in tcolorbox?
In tcolorbox-example.tex file in c:\texlive\2013\texmf-dist\doc\latex\tcolorbox folder,
use environment tcblisting for the setting the box
displays the source code and shows the output in other part below like this:
\begin{tcblisting}{colback=red!5!white,colframe=red!75!black}
This is a \LaTeX\ example:
\begin{equation}
\sum\limits_{i=1}^n i = \frac{n(n+1)}{2}.
\end{equation}
\end{tcblisting}

output is:

A: Instead of two separate tcolorboxes, use just one with the listing and comment option; in this way, the upper part of the box will be used for the listing and the lower part, for the "comment", which can be almost anything, in particular, the output of the code; the bicolor skin allows you to control the color for both parts (upper and lower) independently:
\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage{tcolorbox}
\tcbuselibrary{most}

\newtcblisting{codeoutput}[1]{
breakable,
listing and comment,
bicolor,
lower separated=true,
colback=red!5,
colframe=red!75!black,
colbacklower=white,
collower=blue,
comment=#1,
overlay={
  \draw[dashed,red!80!black] (segmentation.west)--(segmentation.east);
  },
listing options={
  language={Matlab},
  aboveskip=0pt,
  belowskip=0pt,
  basicstyle=\ttfamily,
  }
}

\begin{document}

\begin{codeoutput}{5}
> 2+3; nnnnn
\end{codeoutput}

\end{document}

Another option:
\documentclass[dvipsnames]{article}
\usepackage[T1]{fontenc}
\usepackage{tcolorbox}
\tcbuselibrary{most}

\newtcblisting{codeoutput}[1]{
breakable,
listing and comment,
bicolor,
frame style={
  draw=black,
  color=Maroon
  },
colback=black,
colbacklower=Dandelion!15,
colupper=white,
collower=Maroon,
comment=#1,
listing options={
  language={Matlab},
  aboveskip=0pt,
  belowskip=0pt,
  basicstyle=\ttfamily,
  }
}

\begin{document}

\begin{codeoutput}{5}
> 2+3; nnnnn
\end{codeoutput}

\end{document}


text:
Q: Expression grammar with exponentiation operator AND unary negation operator using Boost Spirit There are many examples online how to implement a calculator with Boost Spirit. There are also answered questions on how to add an exponentiation operator to it, for example this one.
But, when it comes to a combination of exponentiation operator AND unary negation operator, these examples fail.
Consider the following expressions:

-4^2
-(12/3)^2

What do you think the answers should be? Any sane mathematician will answer -16. Because exponentiation operation has a precedence over unary negation operation.
But the calculators implementing grammatical rules from the examples shared on the web will answer 16.
But, even more remarkable, try to enter these formula in Microsoft Excel. What you will get is 16! (exclamation mark, not a factorial). There is even a note in Wikipedia about this Microsoft's "exception" of the rule.
But to us, developers building engineering applications, it is unacceptable of course. It has to be -16, or planes will start falling apart. So, the question is how to tweak the example grammar rules to follow it.
Here is our version of the calculator using Boost Spirit "Classic":
     definition(calculator const & self ) {
        expression
           =  factor
           >> *( ('+' >> factor)[self.add_op]
               | ('-' >> factor)[self.sub_op]
               )
           ;

        factor
           =  powerterm
           >> *( ('*' >> powerterm)[self.mult_op]
               | ('/' >> powerterm)[self.div_op]
               )
           ;

           powerterm
           =  term
           >> *( ('^' >> powerterm)[self.exp_op]
               | ("**" >> powerterm)[self.exp_op]
               )
           ;

        term
           =  boost::spirit::classic::real_p[self.real_op]
           |  '(' >> expression >> ')'
           |  ('-' >> term)[self.neg_op]
           |  ('+' >> term)
           ;
     }

The output it generates, while matches Excel, is unacceptable:
info = parse("-4^2", calc, scspirit::space_p);
// generates PUSH(-4);PUSH(2);EXPONENTIATE;  which is 16

info = parse("-(12/3)^2", calc, scspirit::space_p);
// generates PUSH(12);PUSH(3);DIVIDE;NEGATE;PUSH(2);EXPONENTIATE; which is 16

A: Couple things must be done to the original code.
First, when expressing "term", the negative (and positive) operation should apply not to "term", but to "factor".
Second, instead of using boost::spirit::classic::real_p, use boost::spirit::classic::ureal_p, the unsigned variant.
        term
           =  boost::spirit::classic::ureal_p[self.real_op]
           |  '(' >> expression >> ')'
           |  ('-' >> factor)[self.neg_op]
           |  ('+' >> factor)
           ;

Now, the output is proper:
info = parse("-4^2", calc, scspirit::space_p);
// generates PUSH(4);PUSH(2);EXPONENTIATE;NEGATE;  which is -16

info = parse("-(12/3)^2", calc, scspirit::space_p);
// generates PUSH(12);PUSH(3);DIVIDE;PUSH(2);EXPONENTIATE;NEGATE; which is -16

Sanity is restored.
Here is a formal grammar:
expression  ::= expression [{ ('+'|'-') factor}];
factor  ::= powerterm [{ ('*'|'/') factor}];
powerterm   ::= powerterm [{('^'|'**') powerterm}];
term    ::= number | '(' expression ')' | '-' factor | '+' factor;

where 'number' is a positive number
Of course, Excel is still a problem, and since it is widely used in the financial sector, our economy is a mess.


text:
Q: Webpack on the backend: missing exports I'm trying to use webpack on the backend to transpile this code (called sub.js):
export const foo1 = () => {
  console.log("I'm foo1");
};

console.log('loaded');

I can compile it and then import it fine. On import (require) I see the 'loaded', but the imported object is empty and in particular has no function foo1.
This is my webpack.config.js:
const path = require('path');
const webpack = require('webpack');

module.exports = {
  entry: `./sub.js`,
  module: {
    rules: [{
      test: /\.(js|jsx)$/,
      exclude: /node_modules/,
      loader: 'babel-loader',
      options: {
        plugins: [
          '@babel/plugin-proposal-class-properties'
        ]
      },
    }],
  },
  resolve: {
    extensions: ['*', '.js', '.jsx'],
  },
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'backend.js'
  },
  mode: 'production',
};

My package.json:
{
  "name": "sub",
  "version": "1.0.0",
  "description": "",
  "main": "dist/backend.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.13.8",
    "@babel/plugin-proposal-class-properties": "^7.13.0",
    "@babel/preset-env": "^7.13.9",
    "@babel/preset-react": "^7.12.10",
    "babel-loader": "^8.2.2",
    "webpack": "^5.65.0",
    "webpack-cli": "^4.9.1"
  }
}

I test using:
> npx webpack && node --eval "r = require('./dist/backend.js'); console.log(r);"
asset backend.js 45 bytes [emitted] [minimized] (name: main)
runtime modules 396 bytes 2 modules
./sub.js 204 bytes [built] [code generated]
webpack 5.65.0 compiled successfully in 250 ms
loaded
{}

I was expecting to see:
loaded
{foo1: [Function]}

or similar.

A: Found the issue. Apparently you need to explicitly declare exported libraries in the output. Now that I've added this:
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'backend.js',
    library: {
        type: 'commonjs-module',
    },
  },

I get:
> npx webpack && node --eval "r = require('./dist/backend.js'); console.log(r);"
asset backend.js 192 bytes [emitted] [minimized] (name: main)
./sub.js 323 bytes [built] [code generated]
webpack 5.65.0 compiled successfully in 275 ms
loaded
{ foo1: [Function] }

as expected.
For reference https://webpack.js.org/configuration/output/#outputlibrary.


text:
Q: How to select by using custom date I have a custom date (dynamic build/input) as like '2013-5-13'
but my mysql database store as '2013-05-13'
so where i try to retrieve it out as like
SELECT * FROM TBL WHERE XDATE='2013-5-13' >>> it return me ZERO result

but
SELECT * FROM TBL WHERE XDATE='2013-05-13' >>> it return me CORRECT result

so how to solve this one directly in mysql statement?

A: use this %c in DATE_FORMAT
     select *  from TBL WHERE DATE_FORMAT(`XDATE`,'%Y-%c-%d') = '2013-5-13'

DEMO HERE

A: Use DATE_FORMAT
DATE_FORMAT(`XDATE`,'%Y-%c-%d')

Query
SELECT * FROM TBL WHERE DATE_FORMAT(`XDATE`, '%Y-%c-%d') = '2013-5-13'

MySql  DATE_FORMAT Documentation
%c  Month, numeric (0..12)

A: Before querying the database just use strtotime() to set correctly...
 $date = "2013-5-16";
 $date = date("Y-m-d",strtotime($date));

 $sql = "SELECT * FROM TBL WHERE XDATE='".$date."'";

A: use strtotime function to convert both dates and then check.

A: This answer works only if your input is always in the format "year-month-day"
$date = '2013-5-13';
$parts = explode('-', $date);
$year = $parts[0];
$month = $parts[1];
$day = $parts[2];
//i assume that $year is always valid. Possible checks are left to the reader
//(lol i've always dreamed to write that sentence somewhere)
$month = str_pad($month, 2, "0", STR_PAD_RIGHT);
$day = str_pad($day, 2, "0", STR_PAD_RIGHT);

$clean_date = "$year-$month-$date"; //note the quotes

Now you can use $clean_date in your query.

A: You can format the date:
SELECT DATE_FORMAT('2013-5-13', '%Y-%m-%d');

in the WHERE part:
SELECT * FROM TBL WHERE XDATE=DATE_FORMAT('2013-5-13', '%Y-%m-%d')

MySQL docs

A: I think the cleanest way would be to use the MySQL DATE() function:
SELECT * FROM TABLE WHERE DATE(date_col) = DATE("2013-5-01")

MySQL docs

A: use this query :-
SELECT * FROM TBL WHERE UNIX_TIMESTAMP(XDATE)=strtotime('2013-5-13')


text:
Q: Command to edit files listed submitted changelist? Is there a command to open for edit all files found in a previously submitted changelist at their latest version?
I don't want to rollback a changelist; I'm looking for a shortcut to open all the files for edit instead of resorting to finding all of the files and opening them one by one.
The best I can do is format the output of p4 describe and pipe it into p4 edit.

A: There is an example of this on the perforce public depot...
http://public.perforce.com/wiki/Perforce_Command_Line_Recipes
Look for    Open all the files in a submitted changelist for edit
There are a few flavours of this on that page, but the basic shell command is
p4 files ...@<change num>,<change num> | sed s/\#.*// | p4 -x - edit

Disclaimer: I've not actually tried this


text:
Q: Why don't my parameters get sent in my SLRequest? I'm working with Twitter's API, and the parameters I try to send along an SLRequest seem to be ignored:
SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodGET URL:[NSURL URLWithString:@"https://api.twitter.com/1.1/statuses/home_timeline.json"] parameters:@{@"count":@50}];
[request setAccount:self.twitterAccount];
[request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {...}];

Here, although I give it a count=50 argument, I receive only 20 tweets. When I look at the connection using Charles Proxy, I don't see this argument sent anywhere in the request. Why doesn't SLRequest take my parameters into account?

A: It turns out the only type of parameters SLRequest accepts is NSString. So I should have sent @{@"count":@"50"} instead of @{@"count":@50}.


text:
Q: load store with parameter selected on another grid I have this code :
Ext.define('MyDesktop.Opport', {
extend: 'Ext.ux.desktop.Module',
requires: [
    'Ext.data.ArrayStore',
    'Ext.util.Format',
    'Ext.grid.Panel',
    'Ext.grid.RowNumberer',
/***********************/
    'Ext.grid.*',
    'Ext.data.*',
    'Ext.panel.*'
/***********************/
],

id:'opp',
createWindow : function(){
    var storeop = Ext.create('Ext.data.JsonStore', {
        proxy: {
            type: 'ajax',
            url: 'PHP/afficherop.php',
            reader: {
                type: 'json',               // format fichier : JSON
                root: 'enregistrements',    // D?but des donn?es
                idProperty: 'id'            // cl? primaire
            }
        },
        fields: ['id','date','infos','idProd','idcl']
    });

    var storecl = Ext.create('Ext.data.JsonStore', {
        proxy: {
            type: 'ajax',

            url: 'PHP/afficher.php',
            reader: {
                type: 'json',               // format fichier : JSON
                root: 'enregistrements',    // D?but des donn?es
                idProperty: 'id'            // cl? primaire
            }
        },
        fields: ['id','type','nom','prenom','mat']
    });

    storecl.load();
    var desktop = this.app.getDesktop();
    var win = desktop.getWindow('opp');
    /*******************/
    if(!win){
        win = desktop.createWindow({
            id: 'opp',
            title:'Opportunités',
            width:500,
            height:480,
            iconCls: 'bogus',
            animCollapse:false,
            constrainHeader:true,
            layout: 'border',
            align: 'center',

            items: [
                {
                    xtype: 'grid',
                    flex: 1,
                    split: true,
                    border: true,
                    region: 'center',
                    store: storecl,

                    title: 'Client',
                    columns: [
                       // new Ext.grid.RowNumberer(),
                        {text: 'ID',dataIndex: 'id'},
                        { text: 'type',align: 'center',dataIndex: 'type'},
                        { text: 'nom',align: 'center',dataIndex: 'nom'},
                        { text: 'Prénom',align: 'center',dataIndex: 'prenom'},
                        { text: 'Matricule',align: 'center',dataIndex: 'mat'}
                    ],
                    listeners: {itemdblclick: function(grid ,record){
                    var rr = grid.getSelectionModel();
                    var rs = rr.getSelection();
                        var idc = rs[0].get('id');
                        Ext.Ajax.request({
                            url: 'PHP/op.php',
                            params: {
                                idcl: idc
                            }
                             });
                        storeop.load({params:{idcl: idc}});
                }}
                },{
                    xtype: 'grid',
                    flex: 1,
                    region: 'south',
                    border: true,
                    store: storeop,
                    title: 'Liste des opportunités',
                    columns: [
                        // new Ext.grid.RowNumberer(),
                        {text: 'ID',dataIndex: 'id'},
                        { text: 'Date',align: 'center',dataIndex: 'date'},
                        { text: 'Info',align: 'center',dataIndex: 'infos'},
                        { text: 'Produit',align: 'center',dataIndex: 'idProd'},
                        { text: 'CLient',align: 'center',dataIndex: 'idcl'}
                    ]
                }
            ]
        })
    }
    return win;
}
});

I want the second grid to dsiplay the records loaded from the store storeop with parameters selected from the first grid. Any help?

A: You need a second Store instance for your second grid. Do not use the same store for both grids.

A: you can get the selected row from the first grid:
var selectedRecord = firstGrid.getSelectionModel().getSelection()[0];

here, i assume that you have a single selection model. To load this selectedRecord to your second grid, you have to loadData to its store.
list.push(selectedRecord.data);
secondGrid.store.loadData(list, false);

take note that you have to use different store for each grid.


text:
Q: Can a view inside a navigation controller (inside a popover) use a flip transition? I'm not sure it's possible to do this. I have an iPad popover that hosts a navigation controller. I'd like to do an iPhone-standard flip-to-backside for something in that view, and have the contents of the popover flip horizontally to reveal a backside. I tried a couple different things here, but was unable to get just the internal part of the popover to flip.
Can this be done?
Thanks.


text:
Q: How to Debug Karma & Jasmine in Intellij 2016? I got an angular application that I need to unit test/debug.
Running the app works.
Running the tests with Karma & Jasmine from console works.
Running the tests with Karma & Jasmine from Intellij "run Configuration" works.
Putting a breakpoint in my tests and launching tests in debug fails.
I configured the latest Chrome as my test browser, installed JetBrains IDE Support extension, configured ok.
The karma server starts, Starts a new Chrome, which gets detected by the output of the Karma server but nothing else happens. Breakpoints are not hit.
Repeating the same process sometimes (!!) work, without changing anything.
Does someone managed to debug a unit test in karma using Jasmine (Mocha runner would work since it is provided in the default configurations of Intellij, but we use Jasmine here.)
Thanks !


text:
Q: Search Bar results add image next to text is it possible to add an image to my search bar results?  I'm able to add text using the following:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(self.identifier) as! UITableViewCell

var text: String?
    if tableView == self.searchResultsController?.tableView {
        if let results = self.results {
            text = self.results!.objectAtIndex(indexPath.row) as? String
        }
    } else {
      //  text = MyVariables.users[indexPath.row] as? String
    }

    cell.textLabel!.text = text

    return cell
}

A: You just need to add a UIImage to your cell.
cell.imageView?.image = UIImage(named: "YourImageNameGoesHere")

The imageView property of UITableViewCell is placed on the left.

[...] If an image is set, it appears on the left
  side of the cell, before any label. [...]

https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITableViewCell_Class/#//apple_ref/occ/instp/UITableViewCell/imageView
Hope this helps.


text:
Q: JavaScript - Cannot Update Array Object Properties Inside Nested For Loops I have the following nested loops:
for(var i = 0; i < availabilities.length; i++){
    if(availabilities[i].round === 1){
        //  Return the indices of all objects which share the same event_team_user_id property
        var indices = helperService.findArrayIndices(availabilities, 'event_team_user_id', availabilities[i].event_team_user_id);
        for(var x = 1; x < indices.length; x++){
            availabilities[x].status = availabilities[i].status;
            console.log(availabilities[x]);
        }
    }
}
console.log(availabiities);

The above should find all array objects associated with a particular round (in this case round 1) and then update all other array objects' status property to match the first round's status if those array objects have the same event_team_user_id property.
console.log(availabilities[x]); nested within the two loops correctly outputs the array object, but console.log(availabiities); returns an array object where the changes made in the for loops to the status property aren't reflected.
Why are the updated properties in the array objects not being saved?

A: If we assume availabiities is a typo from typing out the question since you already mentioned it printed something, it appears your second for loop may have some issues.  You aren't using the indices returned from your helperService.  You should be doing indices[x] to access the correct index of availabilities and x should start at 0.

let availabilities = [
  {
    round: 1,
    event_team_user_id: 1,
    status: 'shouldmatch'
  },
  {
    round: 2,
    event_team_user_id: 2,
    status: 'shouldnotchange'
  },
  {
    round: 3,
    event_team_user_id: 1,
    status: 'shouldchange',
  },
  {
    round: 4,
    event_team_user_id: 3,
    status: 'shouldnotchange',
  },
  {
    round: 5,
    event_team_user_id: 1,
    status: 'shouldchange'
  }
];

for(var i = 0; i < availabilities.length; i++){
    if(availabilities[i].round === 1){
        //  Return the indices of all objects which share the same event_team_user_id property
        var indices = [2, 4];
        for(var x = 0; x < indices.length; x++){
            const curr = indices[x];
            availabilities[curr].status = availabilities[i].status;
        }
    }
}
console.log(availabilities);

A: Looks like you got wrong typo
before
console.log(availabiities);

after
console.log(availabilities);


text:
Q: How do I disable showing the "Activities overview" forever? With two monitors connected, the "Activities overview" is very annoying me when every time I click the applications button on Ubuntu 18.04.

A: You may use a GNOME shell extension called Hide Activities Button. This extension hides the Activities button from the top bar.
Note that you'll still be able access the Activities overview by pressing the Super key (usually the key with Windows logo).
Similar extension: Hide Activities Button (same name, different extension)

A: The activities overview is core to Gnome Shell, so can as such not be disabled. You can, however, configure Gnome Shell to make access to the overview much less immediate.
1) Replace or hide the Activities button
Replace the Activities button by a traditional menu: Install "Applications Menu" or "Arc Menu" to see your Activities button replaced by a button that opens a classical menu.
Hide the Activities button: Install the extension "Hide Activities" to hide the button. In that case, you will want to install an alternative launcher program, for example ULauncher, Albert or Rofi.
2) Disable the Super key and other shortcut keys
Issue following commands to disable 1) the Super key 2) the Super+S, 3) the Alt+F1 key and the 4) Super+A shortcut keys, which open either the Activities or the Applications overview.
gsettings set org.gnome.mutter overlay-key ''
gsettings set org.gnome.desktop.wm.keybindings panel-main-menu "[]"
gsettings set org.gnome.shell.keybindings toggle-overview "['']"
gsettings set org.gnome.shell.keybindings toggle-application-view "['']"

3) Disable hot corner
Not needed on stock Ubuntu, because it is already disabled by default. If you need to disable it, you can do so using Gnome Tweaks or with the command
gsettings set org.gnome.desktop.interface enable-hot-corners false

This will largely place the overview out of your view.
Installing the extensions:
All mentioned extensions are available in the official Ubuntu software sources. You can install them from Snap Center or with the terminal command sudo apt install <packagename>. After installing them, you need to enable them on a per user basis, using Gnome Tweaks, or, on more recent Ubuntu versions, the "Extensions" tool. The latter is available through the package gnome-shell-extension-prefs, the former in gnome-tweaks.
"Applications Menu" can be installed through the package gnome-shell-extensions. This package also contains all other officially supported Gnome Shell extensions.
"Arc Menu" can be installed through the package gnome-shell-extension-arc-menu.
"Hide Activities" is available through the package gnome-shell-extension-hide-activities
Undo the settings
To undo the settings, you can reset to default by issuing similar commands, where you replace set by reset and omit the last argument.


text:
Q: SQLDeveloper will not launch I've just installed Oracle 11g on Windows, but I can't seem to launch SQLDeveloper. I get the following error: "Windows is searching for SQLDEVELOPER.BAT". To locate the file yourself, click Browse".
I've looked for SQLDEVELOPER.BAT but I can't find it.
I've also tried to launch sqldeveloper.exe directly, but it asks for the path to java.exe. When I browse and select C:\Program Files (x86)\Java\jre7\bin\java.exe, but then I get the error: Cannot find a J2SE SDK installed at path: C:\Program Files (x86)\Java\jre7
When I select C:\app\mbergeron\product\11.2.0\dbhome_1\jre\1.5.0\bin\java.exe I get the same error (Cannot find a J2SE SDK)
When I select C:\app\mbergeron\product\11.2.0\dbhome_1\jdk\bin\java.exe, I get no error. It just goes back to the dialog asking for java.exe
I've tried launching sqldeveloper.exe from the console, but I'm not getting error messages in the console.

A: -All you have to do is install Gitbash or any Shell interpreter on your windows PC.
Then you have to change the target of the shortcut in the start menu.
Start Menu > Oracle - OraDb11g_home1 > Application Development > SQL Developper -> Properties
CHANGE "Target" By : C:\app\ORACLE_HOME\product\11.2.0\dbhome_1\sqldeveloper\sqldeveloper.sh
CHANGE "Start In" By : C:\app\ORACLE_HOME\product\11.2.0\dbhome_1\sqldeveloper
You can now access SQL Developer, with a direct link from your start menu.

A: Hit this:
Type the full pathname of a J2SE installation (or Ctrl-C to quit), the path will be stored in ~/.sqldeveloper/jdk

A: You don't need the .bat for execution!
On older SQL-Developer Versions (don't know when it changed, but around 4.x), you had to setup the path to jdk at first startup.
Either by editing the product.conf file (Usually under %APPDATA%\sqldeveloper*\product.conf)
or by starting sqldeveloper.exe via commandline. It will ask you then about the path within commandline, and not via GUI. This is the reason, why you should try it via commandline.
Same situation is on UNIX/LINUX.
With newer releases, it has been changed and shouldn't be required anymore.

A: Or you could just point SQLdeveloper to the java in the oracle folder: (ORACLE_HOME)/jdk/bin/Java.exe


text:
Q: qgis2web can't create map w/ large dataset, and potentially utilizing GeoServer I have a very large dataset (about 120k records) and about a dozen layers, all focused on California for the moment. That is, all the shapes like zips, census tracts, counties etc. are selected using the query builder to narrow to just this state.
My issue is when I try to export a qgis2web map on my Win7, what ends up happening is my computer disk space gets maxed out to whatever I have available (currently 65GB) as there is a .tif file being created (ostensibly by the qgis2web plugin but, I'm not certain it's not a setting or another plugin conflict). Is that the norm and am I simply supposed to provide more disk space for such a gigantic image file?
I'm also using a hosted GeoServer to host my shapefiles and have my data in a postgres/postGIS-extended database. My belief is it's somewhat foolish to parse all that data in QGIS to create a map when in effect the data and shapes for the map I end up making (in OpenLayers or Leaflet) will be called from GeoServer.
Is there a way to minimize the load on QGIS w/ qgis2web so that it can do it's job more efficiently and I load the GeoJSON file with the 112k data records manually?
QGIS 2.16.1 | qgis2web v1.13.1 | GeoServer 2.9.0 | Postgres 9.5.4 | PostGIS 2.2.2r14797

A: For your Geoserver layers, make sure you don't check "Encode to JSON". That should leave the layers as remote WFS layers. However, they will still load fully - I need to find out whether I can implement viewport bbox loading.
TIFFs are created if you have raster layers - disable any you have, I guess, since you imply that you don't expect to have any raster output.


text:
Q: Reusable React component with same actions & reducers I want to reuse a react component and share common actions & reducers. My app dashboard has 3 Lists, where each List is fetched with different query param.
All 3 List components have the same props because all 3 of them are being re-rendered once I receive props from reducer.
Is there an dynamic way to display Lists based on query parameter? What I was thinking is to call different reducer in the action file based on the query param. Is there a better way?
Dashboard.js
 const Dashboard = () => {
      return(

          <List query={QUERY1} />
          <List query={QUERY2} />
          <List query={QUERY3} />

      )
    }

List.js
class List extends Component {

  constructor(props) {
    super(props);
    this.state = {
      items: []
    };
  }

  componentWillMount() {
    const { query } = this.props;
    this.props.onLoad(query);
  }

  componentWillReceiveProps() {
    const { items } = this.props;
    this.setState({ items });
  }

  render() {

    return (

          {
            this.state.items.map((item, index) =>
              <Item data={item} key={index}/>
            )
          }

    )
  }
}

function mapStateToProps(state) {
  const { items } = state.item;
  return {
    items
  }
}

function mapDispatchToProps(dispatch) {
  return {
    onLoad: bindActionCreators(actions.load, dispatch)
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(List);

action.js
export function load(query) {
  return function (dispatch) {
    fetch(`//api.example.com/list?type=${query}&limit=10`)
      .then((response) => response.json())
      .then((data) => {
        dispatch(setItems(data));
      });
  };
}

reducer.js
export default function(state = [], action) {
  switch (action.type) {
    case actionTypes.ITEMS_SET:
      return setItems(state, action);
  }
  return state;
}

function setItems(state, action) {
  const { items } = action;
  return { ...state, items };
}

A: Note I am a contributor on redux-subpace
redux-subspace came around to solve this problem of having the same component displayed on the page, without crossing over the store values.
It has a feature called namespacing that will allow you to isolate your load actions and components from each other.
const Dashboard = () => {
  return(

      <SubspaceProvider mapState={state => state.list1}, namespace='list1'>
        <List query={QUERY1} />
      </SubspaceProvider>
      <SubspaceProvider mapState={state => state.list2}, namespace='list'>
        <List query={QUERY2} />
      </SubspaceProvider>
      <SubspaceProvider mapState={state => state.list3}, namespace='list3'>
        <List query={QUERY3} />
      </SubspaceProvider>

  )
}

You'll also need to namespace your reducers, you can see how to do that here.


text:
Q: nca_connect_server: cannot communicate with host in LoadRunner 12.53 I'm currently testing HP LoadRunner 12.53 with Oracle EBS R12.2.5.
I created a simple script using both Oracle Apps, and Oracle NCA + Http protocol (Log in, bring up a form and close/log out) and replayed but run into below error. (same error for both scripts)
nca_connect_server: cannot communicate with host
icx_ticket is correlated and works OK as it is picked and replaced in the parameter.
No need to correlate JSessionIDForms as EBS is running on socket mode.
It is s just simple script with single correlation but can't find any clue for the error.
What could be the root cause of the error?
Where should I look at for a clue? How to make the error / log more verbose and detailed
Thanks in advance

A: Record it twice.  If the value shifts, then correlate it.

A: Please ensure that you have properly set up the environment before recording, Below steps need to be taken for setting up the environment
1.Set "record = names" flag for specific user profile in Oracle EBS Application** via administrator login  (search google how to achieve this or simply ask your application team to do it for you)
2.Run Time Settings and Default.cfg file changes
Run Time Settings
Keep the below values to high limit to avoid replay timeout errors

*

*Run-Time Settings > Internet Protocol >Preferences > Options>

*Step Download Limit

*HTTP-request connect timeout:

*HTTP-receive receive timeout:

*Keep-Alive timeout:

*Run-Time Settings >Browser>Browser Emulation>

*1)   Simulate a new user on each iteration – checked
3. default.cfg file inside script directory
"RelativeURL={NCAJServSessionId}" statement  in the default.cfg file rolls back each time we run the script so we need to check that it is

*

*/forms/lservlet;JsessionIDForms={NCAJServSessionId} -- R12 Version or

*/forms/formservlet?JServSessionIdforms={NCAJServSessionId}  -- EBS 11
i Version
4. Correlation - Last but not the least
Ensure correct correlation of each and every parameter, The best way to achieve this is by recording the script 2 times and comparing them using a suitable tool, Correlate each value which might be changing each time you replay the script
Note :- The Oracle EBS is not fully supported by Loadrunner please download the loadrunner compatability matrix and check if your version is supported by Loadrunner.


text:
Q: JavaScript - Get true length of emoji at end of String I have a string in JavaScript like so:
var string = " Hello  world!"; // Length of emoji at end: 2 characters ("".length = 2)

Or:
var string = " Hello world! "; // Length of emoji at end: 8 characters ("".length = 8)

Or a string without an emoji:
var string = " Hello world!"; // No emoji at end

I need to find the out following:

*

*Is there an emoji at the end of the string?

*How many characters does it consist of?

I came as far as detecting two-character emojis with the following code:
var emoji = new RegExp('\\p{Extended_Pictographic}', 'u');
var isEmoji = emoji.test(string.slice(-2)); // true for the first string

However, this obviously does not detect the length (e.g.  = 8). If anyone has experience with emojis in JavaScript and could point me in the right direction it would be very much appreciated.

A: The rule is that every emoji that consists of several unicode characters is simply a combination of several emojis, so if you divide the entire string into an array by using the spread operator, then if the last element was an emoji, no matter what its length... then now the last element in the array must also be Emoji

var string1 = " Hello world! ";
var string2 = " Hello world! !";
var string3 = " Hello  world!";
var string4 = " Hello  world!!";
var emoji = new RegExp('\\p{Extended_Pictographic}', 'u');
var isEmoji1 = emoji.test([...string1].at(-1));
var isEmoji2 = emoji.test([...string2].at(-1));
var isEmoji3 = emoji.test([...string3].at(-1));
var isEmoji4 = emoji.test([...string4].at(-1));

console.log(isEmoji1)
console.log(isEmoji2)
console.log(isEmoji3)
console.log(isEmoji4)


text:
Q: Return a structured row in Dask apply I am applying a function on all the rows in a Dask dataframe. In PySpark I'm able to return a spark.sql.Row object with named parameters in order to create a structured row for the resulting DataFrame. How do I return a similarly structured row (with columns and types) when applying a function on the rows in a dask dataframe?
I am looking for something along these lines:
# df is a dask.dataframe with a JSON blob in the `data` column

def process(row):
    json_data = json.loads(row.data)
    return Row(a=json_data["a"], b=json_data["b")

result = df.apply(
    process,
    axis=1,
).compute()

result

I see that the rows are themselves pd.Series, so I tried process returning a Series but I get this error
AttributeError: 'Series' object has no attribute 'columns'

The documentation suggests I can use the meta parameter in apply:

meta: An empty pd.DataFrame or pd.Series that matches the dtypes and column names of the output ... [Inputs like] iterable of (name, dtype) can be provided (note that the order of the names should match the order of the columns)

However when I use an iterable of meta tuples, as suggested
result = df.apply(
    process,
    axis=1,
    meta=[("a", "int")]
).compute()

it's expecting a DataFrame object and returns this error
AttributeError: 'DataFrame' object has no attribute 'name'

A: This is a dask wrapper around a pandas function developed here:
# see unutbu's answer here: https://stackoverflow.com/a/25512372/10693596
import json
def json_to_series(text):
    keys, values = zip(*[item for dct in json.loads(text) for item in dct.items()])
    return pd.Series(values, index=keys)

def process_chunk(df):
    _tmp = df['data'].apply(json_to_series)
    return pd.concat([df, _tmp], axis=1)

result = df.map_partitions(process_chunk).compute()