text:
Q: WPF Adorner for Control User resizable I created a simple adorner for the TextBlock element which allows the user to change its size. You can change the size in four corners of the block, that is, two sizes change at once(upper left thumb, upper right thumb, lower left thumb, lower right thumb). Everything works well, you can see it on the first gif:

Also, I want to add the ability to resize proportionally with the shift key held down. The result of this you can see on the second gif:

As you can see, the upper-left thumb and lower-right thumb allow you to change the dimensions correctly. However, the other two thumb elements don't work, I don't understand how made it.
XAML:
<Window x:Class="BagControlResize.MainWindow"
        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:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Canvas x:Name="canvas">
        <TextBlock x:Name="testBlock" Canvas.Left="250" Canvas.Top="120" Width="300" Height="200" Background="Green"/>
    </Canvas>
</Window>

CREATE ADORNER:
using System.Windows;
using System.Windows.Documents;

namespace BagControlResize
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            Loaded += (sender, e) =>
            {
                var adorner = AdornerLayer.GetAdornerLayer(canvas);
                adorner.Add(new TextBlockAdorner(testBlock));
            };
        }

    }
}

ADORNER:
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;

namespace BagControlResize
{
    public class TextBlockAdorner : Adorner
    {
        private double angle = 0.0;
        private Point transformOrigin = new Point(0, 0);
        private TextBlock childElement;
        private VisualCollection visualChilderns;
        private Thumb leftTop, rightTop, leftBottom, rightBottom;

        public TextBlockAdorner(UIElement element) : base(element)
        {
            visualChilderns = new VisualCollection(this);
            childElement = element as TextBlock;
            CreateThumbPart(ref leftTop);
            leftTop.DragDelta += (sender, e) =>
            {
                double hor = e.HorizontalChange;
                double vert = e.VerticalChange;
                if (Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift))
                {
                    double _max = hor > vert ? hor : vert;
                    hor = _max;
                    vert = _max;
                }
                ResizeX(hor);
                ResizeY(vert);
                e.Handled = true;
            };
            CreateThumbPart(ref rightTop);
            rightTop.DragDelta += (sender, e) =>
            {
                double hor = e.HorizontalChange;
                double vert = e.VerticalChange;
                if (Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift))
                {
                    // THIS: NO WORKED
                    double _max = Math.Abs(hor) > Math.Abs(vert) ? Math.Abs(hor) : Math.Abs(vert);
                    if (hor >= 0 && vert <= 0)
                    {
                        hor = _max;
                        vert = -_max;
                    }
                    else
                    {
                        hor = -_max;
                        vert = _max;
                    }
                }
                ResizeWidth(hor);
                ResizeY(vert);
                e.Handled = true;
            };
            CreateThumbPart(ref leftBottom);
            leftBottom.DragDelta += (sender, e) =>
            {
                double hor = e.HorizontalChange;
                double vert = e.VerticalChange;
                if (Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift))
                {
                    // THIS: NO WORKED
                    double _max = Math.Abs(hor) > Math.Abs(vert) ? Math.Abs(hor) : Math.Abs(vert);
                    if (hor <= 0 && vert >= 0)
                    {
                        hor = -_max;
                        vert = _max;
                    }
                    else
                    {
                        hor = _max;
                        vert = -_max;
                    }
                }
                ResizeX(hor);
                ResizeHeight(vert);
                e.Handled = true;
            };
            CreateThumbPart(ref rightBottom);
            rightBottom.DragDelta += (sender, e) =>
            {
                double hor = e.HorizontalChange;
                double vert = e.VerticalChange;
                if (Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift))
                {
                    double _max = hor > vert ? hor : vert;
                    hor = _max;
                    vert = _max;
                }
                ResizeWidth(hor);
                ResizeHeight(vert);
                e.Handled = true;
            };
        }
        private void ResizeWidth(double e)
        {
            double deltaHorizontal = Math.Min(-e, childElement.ActualWidth - childElement.MinWidth);
            Canvas.SetTop(childElement, Canvas.GetTop(childElement) - transformOrigin.X * deltaHorizontal * Math.Sin(angle));
            Canvas.SetLeft(childElement, Canvas.GetLeft(childElement) + (deltaHorizontal * transformOrigin.X * (1 - Math.Cos(angle))));
            childElement.Width -= deltaHorizontal;
        }
        private void ResizeX(double e)
        {
            double deltaHorizontal = Math.Min(e, childElement.ActualWidth - childElement.MinWidth);
            Canvas.SetTop(childElement, Canvas.GetTop(childElement) + deltaHorizontal * Math.Sin(angle) - transformOrigin.X * deltaHorizontal * Math.Sin(angle));
            Canvas.SetLeft(childElement, Canvas.GetLeft(childElement) + deltaHorizontal * Math.Cos(angle) + (transformOrigin.X * deltaHorizontal * (1 - Math.Cos(angle))));
            childElement.Width -= deltaHorizontal;
        }
        private void ResizeHeight(double e)
        {
            double deltaVertical = Math.Min(-e, childElement.ActualHeight - childElement.MinHeight);
            Canvas.SetTop(childElement, Canvas.GetTop(childElement) + (transformOrigin.Y * deltaVertical * (1 - Math.Cos(-angle))));
            Canvas.SetLeft(childElement, Canvas.GetLeft(childElement) - deltaVertical * transformOrigin.Y * Math.Sin(-angle));
            childElement.Height -= deltaVertical;
        }
        private void ResizeY(double e)
        {
            double deltaVertical = Math.Min(e, childElement.ActualHeight - childElement.MinHeight);
            Canvas.SetTop(childElement, Canvas.GetTop(childElement) + deltaVertical * Math.Cos(-angle) + (transformOrigin.Y * deltaVertical * (1 - Math.Cos(-angle))));
            Canvas.SetLeft(childElement, Canvas.GetLeft(childElement) + deltaVertical * Math.Sin(-angle) - (transformOrigin.Y * deltaVertical * Math.Sin(-angle)));
            childElement.Height -= deltaVertical;
        }
        public void CreateThumbPart(ref Thumb cornerThumb)
        {
            cornerThumb = new Thumb { Width = 25, Height = 25, Background= Brushes.Black };
            visualChilderns.Add(cornerThumb);
        }
        public void EnforceSize(FrameworkElement element)
        {
            if (element.Width.Equals(Double.NaN))
                element.Width = element.DesiredSize.Width;
            if (element.Height.Equals(Double.NaN))
                element.Height = element.DesiredSize.Height;
            FrameworkElement parent = element.Parent as FrameworkElement;
            if (parent != null)
            {
                element.MaxHeight = parent.ActualHeight;
                element.MaxWidth = parent.ActualWidth;
            }
        }
        protected override Size ArrangeOverride(Size finalSize)
        {
            base.ArrangeOverride(finalSize);
            double desireWidth = AdornedElement.DesiredSize.Width;
            double desireHeight = AdornedElement.DesiredSize.Height;
            double adornerWidth = this.DesiredSize.Width;
            double adornerHeight = this.DesiredSize.Height;
            leftTop.Arrange(new Rect(-adornerWidth / 2 - 15, -adornerHeight / 2 - 15, adornerWidth, adornerHeight));
            rightTop.Arrange(new Rect(desireWidth - adornerWidth / 2 + 15, -adornerHeight / 2 - 15, adornerWidth, adornerHeight));
            leftBottom.Arrange(new Rect(-adornerWidth / 2 - 15, desireHeight - adornerHeight / 2 + 15, adornerWidth, adornerHeight));
            rightBottom.Arrange(new Rect(desireWidth - adornerWidth / 2 + 15, desireHeight - adornerHeight / 2 + 15, adornerWidth, adornerHeight));
            return finalSize;
        }
        protected override int VisualChildrenCount => visualChilderns.Count;
        protected override Visual GetVisualChild(int index) => visualChilderns[index];
        protected override void OnRender(DrawingContext drawingContext) => base.OnRender(drawingContext);
    }
}

I show the minimum a self-sufficient example so that you can see exactly what I'm doing. The code is easily compiled. I marked two places in the code where I was stuck.
Thanks
UPD 1:

A: @Frenchy's solution helps, but there are still problems with the code.  Try shift-clicking the top left or the bottom left and immediately dragging directly up, or dragging top right very slowly at a constant speed to the left.
The issue is caused by calculating the proportional drag direction in every call to DragDelta, based on the direction of the biggest move.  The code can easily change direction and get confused, or not even know which way it's meant to be going correctly.
One way around this is to decide the drag direction when the proportional drag starts, and carry on with that until it ends.  This seems to work better, and fixes the issues above.  The code is below.
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;

namespace BagControlResize
{
    public class TextBlockAdorner : Adorner
    {
        private double angle = 0.0;
        private Point transformOrigin = new Point(0, 0);
        private TextBlock childElement;
        private VisualCollection visualChilderns;
        public Thumb leftTop, rightTop, leftBottom, rightBottom;
        private bool dragStarted = false;
        private bool isHorizontalDrag = false;

        public TextBlockAdorner(UIElement element) : base(element)
        {
            visualChilderns = new VisualCollection(this);
            childElement = element as TextBlock;
            CreateThumbPart(ref leftTop);
            leftTop.DragDelta += (sender, e) =>
            {
                double hor = e.HorizontalChange;
                double vert = e.VerticalChange;
                if (Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift))
                {
                    if (dragStarted) isHorizontalDrag = Math.Abs(hor) > Math.Abs(vert);
                    if (isHorizontalDrag) vert = hor; else hor = vert;
                }
                ResizeX(hor);
                ResizeY(vert);
                dragStarted = false;
                e.Handled = true;
            };
            CreateThumbPart(ref rightTop);
            rightTop.DragDelta += (sender, e) =>
            {
                double hor = e.HorizontalChange;
                double vert = e.VerticalChange;
                System.Diagnostics.Debug.WriteLine(hor + "," + vert + "," + (Math.Abs(hor) > Math.Abs(vert)) + "," + childElement.Height + "," + childElement.Width + "," + dragStarted + "," + isHorizontalDrag);
                if (Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift))
                {
                    if (dragStarted) isHorizontalDrag = Math.Abs(hor) > Math.Abs(vert);
                    if (isHorizontalDrag) vert = -hor; else hor = -vert;
                }
                ResizeWidth(hor);
                ResizeY(vert);
                dragStarted = false;
                e.Handled = true;
            };
            CreateThumbPart(ref leftBottom);
            leftBottom.DragDelta += (sender, e) =>
            {
                double hor = e.HorizontalChange;
                double vert = e.VerticalChange;
                System.Diagnostics.Debug.WriteLine(hor + "," + vert + "," + (Math.Abs(hor) > Math.Abs(vert)) + "," + childElement.Height + "," + childElement.Width + "," + dragStarted + "," + isHorizontalDrag);
                if (Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift))
                {
                    if (dragStarted) isHorizontalDrag = Math.Abs(hor) > Math.Abs(vert);
                    if (isHorizontalDrag) vert = -hor; else hor = -vert;
                }
                ResizeX(hor);
                ResizeHeight(vert);
                dragStarted = false;
                e.Handled = true;
            };
            CreateThumbPart(ref rightBottom);
            rightBottom.DragDelta += (sender, e) =>
            {
                double hor = e.HorizontalChange;
                double vert = e.VerticalChange;
                if (Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift))
                {
                    if (dragStarted) isHorizontalDrag = Math.Abs(hor) > Math.Abs(vert);
                    if (isHorizontalDrag) vert = hor; else hor = vert;
                }
                ResizeWidth(hor);
                ResizeHeight(vert);
                dragStarted = false;
                e.Handled = true;
            };
        }
        public void CreateThumbPart(ref Thumb cornerThumb)
        {
            cornerThumb = new Thumb { Width = 25, Height = 25, Background = Brushes.Black };
            cornerThumb.DragStarted += (object sender, DragStartedEventArgs e) => dragStarted = true;
            visualChilderns.Add(cornerThumb);
        }

        private void ResizeWidth(double e)
        {
            double deltaHorizontal = Math.Min(-e, childElement.ActualWidth - childElement.MinWidth);
            Canvas.SetTop(childElement, Canvas.GetTop(childElement) - transformOrigin.X * deltaHorizontal * Math.Sin(angle));
            Canvas.SetLeft(childElement, Canvas.GetLeft(childElement) + (deltaHorizontal * transformOrigin.X * (1 - Math.Cos(angle))));
            childElement.Width -= deltaHorizontal;
        }
        private void ResizeX(double e)
        {
            double deltaHorizontal = Math.Min(e, childElement.ActualWidth - childElement.MinWidth);
            Canvas.SetTop(childElement, Canvas.GetTop(childElement) + deltaHorizontal * Math.Sin(angle) - transformOrigin.X * deltaHorizontal * Math.Sin(angle));
            Canvas.SetLeft(childElement, Canvas.GetLeft(childElement) + deltaHorizontal * Math.Cos(angle) + (transformOrigin.X * deltaHorizontal * (1 - Math.Cos(angle))));
            childElement.Width -= deltaHorizontal;
        }
        private void ResizeHeight(double e)
        {
            double deltaVertical = Math.Min(-e, childElement.ActualHeight - childElement.MinHeight);
            Canvas.SetTop(childElement, Canvas.GetTop(childElement) + (transformOrigin.Y * deltaVertical * (1 - Math.Cos(-angle))));
            Canvas.SetLeft(childElement, Canvas.GetLeft(childElement) - deltaVertical * transformOrigin.Y * Math.Sin(-angle));
            childElement.Height -= deltaVertical;
        }
        private void ResizeY(double e)
        {
            double deltaVertical = Math.Min(e, childElement.ActualHeight - childElement.MinHeight);
            Canvas.SetTop(childElement, Canvas.GetTop(childElement) + deltaVertical * Math.Cos(-angle) + (transformOrigin.Y * deltaVertical * (1 - Math.Cos(-angle))));
            Canvas.SetLeft(childElement, Canvas.GetLeft(childElement) + deltaVertical * Math.Sin(-angle) - (transformOrigin.Y * deltaVertical * Math.Sin(-angle)));
            childElement.Height -= deltaVertical;
        }
        //public void EnforceSize(FrameworkElement element)
        //{
        //    if (element.Width.Equals(Double.NaN))
        //        element.Width = element.DesiredSize.Width;
        //    if (element.Height.Equals(Double.NaN))
        //        element.Height = element.DesiredSize.Height;
        //    FrameworkElement parent = element.Parent as FrameworkElement;
        //    if (parent != null)
        //    {
        //        element.MaxHeight = parent.ActualHeight;
        //        element.MaxWidth = parent.ActualWidth;
        //    }
        //}
        protected override Size ArrangeOverride(Size finalSize)
        {
            base.ArrangeOverride(finalSize);
            double desireWidth = AdornedElement.DesiredSize.Width;
            double desireHeight = AdornedElement.DesiredSize.Height;
            double adornerWidth = this.DesiredSize.Width;
            double adornerHeight = this.DesiredSize.Height;
            leftTop.Arrange(new Rect(-adornerWidth / 2 - 15, -adornerHeight / 2 - 15, adornerWidth, adornerHeight));
            rightTop.Arrange(new Rect(desireWidth - adornerWidth / 2 + 15, -adornerHeight / 2 - 15, adornerWidth, adornerHeight));
            leftBottom.Arrange(new Rect(-adornerWidth / 2 - 15, desireHeight - adornerHeight / 2 + 15, adornerWidth, adornerHeight));
            rightBottom.Arrange(new Rect(desireWidth - adornerWidth / 2 + 15, desireHeight - adornerHeight / 2 + 15, adornerWidth, adornerHeight));
            return finalSize;
        }
        protected override int VisualChildrenCount => visualChilderns.Count;
        protected override Visual GetVisualChild(int index) => visualChilderns[index];
        //protected override void OnRender(DrawingContext drawingContext) => base.OnRender(drawingContext);
    }
}

A: your tests when key shift is down are not correct, i have modified that:
you have to keep only two tests when hor and vert have opposed sign, the others tests have to be discarded.
        rightTop.DragDelta += (sender, e) =>
        {
            double hor = e.HorizontalChange;
            double vert = e.VerticalChange;

            if (Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift))
            {

                double _max = Math.Abs(hor) > Math.Abs(vert) ? Math.Abs(hor) : Math.Abs(vert);
                if( _max >50)return;//if distance of mouse from thumb is > 50pixel, no action
                if (hor >= 0 && vert <= 0)    // review the tests
                {
                    hor = _max;
                    vert = -_max;
                }
                else if(hor <= 0 && vert >=0)
                {
                    hor = -_max;
                    vert = _max;
                }
                else
                {
                    return;
                }
            }
            ResizeWidth(hor);
            ResizeY(vert);
            e.Handled = true;
        };
        CreateThumbPart(ref leftBottom);
        leftBottom.DragDelta += (sender, e) =>
        {
            double hor = e.HorizontalChange;
            double vert = e.VerticalChange;

            if (Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift))
            {
                double _max = Math.Abs(hor) > Math.Abs(vert) ? Math.Abs(hor) : Math.Abs(vert);
                if( _max >50)return;
                if (hor <= 0 && vert >= 0)  //same things
                {
                    hor = -_max;
                    vert = _max;
                }
                else if (hor >= 0 && vert <= 0)
                {
                    hor = _max;
                    vert = -_max;
                }
                else
                {
                    return;
                }
            }
            ResizeX(hor);
            ResizeHeight(vert);
            e.Handled = true;
        };


text:
Q: How to animate an object depending on page scroll position I am currently using the following code to display/hide content based on the current scroll position:
$(window).scroll(function () {
    if ($(window).scrollTop() >= 409) {
        $('.cliocont').fadeTo('slow', 1.0);
    } else if ($(window).scrollTop() <= 409) {
        $('.cliocont').fadeTo('slow', 0.5);
    }
});

Is there a reason why this code does not seem to work? Whenever the else if statement the code works, but whenever it is added the content doesn't appear or hide.
Thanks,
Nathan Niamehr

A: Added .stop() to prevent animation fade errors and a boolean flag var io to prevent unnecessary animations:
jsBin demo
var $cc = $('.cliocont'),
    io  = false; // flag // compare booleans

$(window).scroll(function () {

   var is409 = $(window).scrollTop() >= 409; // boolean
   if (io != is409){
      io = is409;
      $cc.stop().fadeTo(800, is409?1.0:0.5);
   }

});

is409 ? 1.0 : 0.5 is a Conditional Operator and
it's a shorthand for the if statement;
boolean ? ifTrue : else ;

A: I would say this is more proper, this includes the time locks for two animations -- do remove the console.log(...) calls:
            <script type="text/javascript">

            var animateTrainer1 = true;
            var animateTrainer2 = true;
            $(window).scroll(function () {

                var scrollTop = $(window).scrollTop();

                if (scrollTop > 500 && animateTrainer1) {
                    animateTrainer1 = false;
                    console.log("animated trainer 1");
                    Animations.toPosition("#trainer1", 0, -100, 4000);
                }

                if (scrollTop > 800 && animateTrainer2) {
                    animateTrainer2 = false;
                    console.log("animated trainer 2");
                    Animations.toPosition("#trainer2", 100, 340, 4000);
                }

            });

        </script>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Convergence in $L^1$ implies Convergence in measure using Chebyshev's Inequality Let $\{f_n\}$ be a sequence of Lebesgue integrable functions that converges to $f$ in $L^1$. Then, I have to show that $\{f_n\}$ converges in measure.
Here is my approach:
So Claim: $\mu(x:|f_n(x)-f(x)|\geq\epsilon) \to 0$
for any $\epsilon >0$, by Chebyshev's Inequality, we have
Case 1:
 Consider $\mu(x:|f_n(x)-f(x)|> \epsilon)<\frac{1}{\epsilon}\int{|f_n(x)-f(x)|d\mu} \to0$ (as $f_n \to f$ in $L^1)$
Case 2: Consider $\mu(x:|f_n(x)-f(x)|=\epsilon)=\mu(x:-\epsilon +f(x)\leq f_n(x)\leq\epsilon+f(x)) \to 0(???)$ for any arbitrary $\epsilon$.
I am not sure about Case 2.
Thanks for any help!!

A: There's not really any reason to have case 2, because Chebyshev's inequality also works with $\le$ replacing $<$. If you're dead set on using it, then you haven't got the setup quite right (your first equality is wrong). The relevant estimate would be that
$$\mu\{x : g(x) = \lambda\} = \frac 1 {\lambda} \int_{\{x : g(x) = \lambda\}} g\, d\mu \le \frac{1}{\lambda} \int g \, d\mu$$
for positive $g$.

Alternatively, notice that
$$\mu\{|f_n - f| \ge \epsilon\} \le \mu\left\{|f_n - f| > \frac{\epsilon}{2}\right\}$$
and apply Case $1$.


text:
Q: Joining tables on two fields I always have confusion when it comes into JOINING tables.
So, I have a table that stores the user details called tblUsers having the following fields(for the sake of simplicity, I am including only the required fields here while posting):
user_id
first_name

And I have another table which stores the messages called tblMessages:
msg_id
sender_id
recipient_id
msg_body

Now what am trying to do is to fetch all messages, with the user names too. What I have tried is this:
SELECT
    `msg_id`,
    (SELECT `first_name` FROM `tblUsers` WHERE `tblUsers`.`user_id` = `tblMessages`.`sender_id`) AS `sender_name`,
    (SELECT `first_name` FROM `tblUsers` WHERE `tblUsers`.`user_id` = `tblMessages`.`recipient_id`) AS `recipient_name`,
    `msg_body`
FROM `tblMessages`

It seems to be working at the moment. But is this the correct way for attaining my goal? Or will JOINing the tables will be better? The tblMessages can grow to a large number of rows probably. If we are going to do the JOIN, then we will do 2 LEFT JOINs? First, on the sender_id of tblMessages with user_id of tblUsers and again recipient_id of tblMessages with user_id of tblUsers. Is that correct?
Let me know your suggestions or corrections on my approach.

A: This is going to be your best query (It will run queries once, and then join tables on their indices):
SELECT m.`msg_id`, su.`first_name` AS `sender_name`, ru.`first_name` AS `recipient_name`, m.`msg_body`
FROM `tblMessages` m
LEFT JOIN `tblUsers` su ON m.`sender_id` = su.`user_id`
LEFT JOIN `tblUsers` ru ON m.`recipient_id` = ru.`user_id`;

When in doubt, use EXPLAIN right before your query to determine what indexes it's going to use, and how efficient it's going to be. Check out these sqlfiddles containing the EXPLAIN's for each query.
You can read a bit about the reasoning for choosing this query over yours here and straight from the docs here. EXPLAIN is also a helpful tool that can help you understand where your bottlenecks are and what is causing performance issues on your database (This likely isn't going to impact it very much, but you can always do some performance tests when your database reaches a healthy size.

A: You should JOIN the same table twice, using two different aliases for example s and r:
SELECT
  m.msg_id,
  m.sender_id,
  s.first_name,
  m.recipient_id,
  r.first_name,
  m.msg_body
FROM
  tblMessages AS m
  LEFT JOIN tblUsers AS s ON m.sender_id=s.user_id
  LEFT JOIN tblUsers AS r ON m.recipient_id=r.user_id

but your approach is not wrong, it works and with proper indexes shouldn't be much slower.


text:
Q: Reading Openoffice Calc (.ods) programmatically using c#? I want to know if it is possible to read OpenOffice Calc spreadsheet programatically with c#, I can do this for Excel(.xls and .xlsx) but unable to find a solution for reading calc spreadsheet.
Help me if anyone has solution.

A: ODF .NET - It works for c# and you can read and write.
Says like this on there page:

ODF .NET allows you to write applications to create, modify and parse
  text documents and spreadsheets. Supports all versions of .NET
  Framework, .NET Compact Framework and Mono.

A: If you want to work directly against a headless OpenOffice/LibreOffice instance to manipulate the spread sheets, you are going to need to use OpenOffice/LibreOffice component interface UNO.  This is a bit of a pain because of the casts that are required in strongly typed languages (UNO has bindings for many languages), deny you of the tooling you would expect unless you find a C# OpenOffice set of wrapper classes. There are other frameworks to manipulate the document but to work with it via OpenOffice directly this is the only way.
Here is some example code of someone creating an xls spread sheet with c#: Use OpenOffice Uno CLI with C# to create a spreadsheet
Here is the OpenOffice UNO reference: http://www.openoffice.org/api/docs/java/ref/overview-summary.html

A: You should have a look at the GemBox.Spreadsheet component from GemBox that supports XLSX, XLS, CSV, ODS or HTML file format.
There's both a free and a paid version of it.


text:
Q: What's the proper way to generate a manifest with DS and maven-bundle-plugin? I am using today maven-bundle-plugin to generate the manifest of my projects. Due to others constraints, my modules use the "jar" packaging (i can't use the "bundle" packaging), and currently, my pom look like this :
<plugin>
    <artifactId>maven-jar-plugin</artifactId>
    <configuration>
      <archive>
        <manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
      </archive>
   </configuration>
</plugin>
<plugin>
  <groupId>org.apache.felix</groupId>
  <artifactId>maven-bundle-plugin</artifactId>
  <executions>
    <execution>
      <id>bundle-manifest</id>
      <phase>process-classes</phase>
      <goals>
        <goal>manifest</goal>
      </goals>
      <configuration>
        <instructions>
         ...
        </instructions>
      </configuration>
    </execution>
  </executions>
</plugin>

I'd like now to generate a 'Service-Component' header and the DS xml descriptor from my annotated components, but adding "<_dsannotations>*</_dsannotations>" is not working :

*

*Service-Component header is correctly generated, but the xml are not present in the jar

*If i rebuild my maven project without a clean goal, then the 'Service-Component' header have duplicates references : After digging in the code, the plugin use the old generated manifest from target/classes/META-INF/MANIFEST.MF and merge it with the new generated one. The 'Service-Component' is then concatened

So, how should i configure my pom for this to work ? For now, i use the 'unpackBundle' option (in order to have the xml in my bundle) and an empty src/main/resource/MANIFEST.MF (in order to bypass the merge of the old manifest) : it looks ugly :-)
Moreover, the 'bnd-maven-plugin' work as intended, but the integration with maven are maybe too light (or not documented?), as 'global configuration' in a parent pom, generation of the Bundle-SymbolicName or Bundle-Name, etc.
Thanks!

A: There is a newer plugin for maven that is closer to both bnd and maven. This plugin does not take over the jar target and properly follows the maven phases.
Take a look at http://njbartlett.name/2015/03/27/announcing-bnd-maven-plugin.html


text:
Q: Access the number of users to spawn in locustfile I'd like to be able to get access to the value of the -u parameter inside my locust file.
The Runner class gives me the number of concurrently running users but I want to know the value passed to locust via -u.
Update:  Got it
@events.init.add_listener
def _(environment, **kwargs):
    print(environment.parsed_options.num_users)


text:
Q: How to center SliverGrid? I want to center a fixed width GridView in CustomScrollView horizontally.
But I couldn't find a way to align as sliver. How can I do this?
Maybe I can use SliverToBoxAdapter to use Center but is there no performance penalty?
The following is pseudo code for this.
CustomScrollView(
  slivers: [
    SliverToBoxAdapter(
      Center(child: Text('I can do it'))
    ),
    SliverAlign?(
      alignment: Alignment.topCenter,
      child: SliverSizedBox?(
        width: 600,
        sliver: SliverGrid.count(
          crossAxisCount: 2,
          mainAxisSpacing: 24,
          childAspectRatio: 0.9,
          crossAxisSpacing: 8,
          children: [
            Text('SliverAlign and SliverSizedBox does not exist')
          ],
    ))),
]);


text:
Q: Return doesn't work with float or int, but does work with string? First, let me apologize if this is the world's stupidest question.  But, I'm stumped and I've done a bunch of searching both here and on Google.  I'm teaching myself C++, so it's possible I just don't have to vocabulary necessary to know what to search for.
I'm trying to write a Finite State Machine to parse equations.  I know it's been done before, but I'm trying to learn.  To that end, I want to be able to take a string, recognize numbers, and convert them to doubles or floats.  (I'll entertain any advice you have on which format to use.)
I have a function to convert a string to a double:
    double convertToDouble(string value)
{
    /* -- From http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.2
        Using stringstream, convert a string to a double by treating it like a stream
    */
    istringstream stream(value);
    double doubleValue;
    stream >> doubleValue;
    return doubleValue;
}

And I have a function to look for the next numeric value in a string:
string evaluateNextValue (int operatorPosition, string equation)
{
    /* -- Find the next value
        My idea is that, since I'm using spaces as my dividers, we'll look for
        the first number and then, using insert to put the individual numbers
        into a string until a space is found again. Then, the numbers--now
        in the correct order--can be converted to a double and returned
    */
    bool digitFound = false;
    string workingNumbers;
    for (int pos = operatorPosition; pos < equation.size(); pos ++)
    {
        if (equation.at(pos) == ' ' && digitFound == true)
        {
            double result = convertToDouble(workingNumbers);
            cout << "Converting a string to " << result << endl;
            cout << "The result plus one is: " << result +1 << endl;
            return workingNumbers;
        } else if (equation.at(pos) == ' ' && digitFound == false)
        {
            cout << "Skipping a blank space." << endl;
            continue;
        } else
        {
            if (digitFound == false)
            {
                digitFound = true;
                cout << "First digit found." << endl;
            }
            cout << "Adding " << equation.at(pos) << " to the string." << endl;
            workingNumbers.insert(workingNumbers.end(),equation.at(pos));
        }
    }
}

And this is the main() I'm using to call them both as a sort of test.
int main()
{
    string dataInput;
    cout << "Insert a number" << endl;
    getline(cin, dataInput);
    cout << "You entered: " << dataInput << endl;
    double numberValue = convertToDouble(evaluateNextValue(0, dataInput));

    cout << "Adding ten: " << numberValue + 10;
    return 0;
}

Here's the thing: as it is now, with the evaluateNextValue() returning a string, it works.  It seems a bit ungainly to me (may it all seems ungainly to you), but it works.
When I have the code manipulate the variable result in the function, it works fine.  I just convert the string to a double and I can work with it.
BUT, when I convert the string to a double and try to return the double. . . the double works fine in the function itself.  But it's nan when it arrives in main().  Even weirder (or just as weird, at any rate) is the fact that trying to return an int DOES return an int, but never anything remotely connected to the value I enter.
I'd appreciate any help you care to offer.  And, as this is my first post here, I'm open to any style pointers.

A: The return value is undefined if evaluateNextValue arrives at the end of the string due to the for loop condition (because you have no return statement there). This triggers undefined behaviour, which can include returning NaN values.
You should enable your compiler's warnings to catch such errors.


text:
Q: TypeScript React Native property 'target' does not exist on type 'string' I'm making input component in typescript for my mobile app. I'm trying to handle change of the text in text input with useState hook, so I created this:
const [password, setPassword] = useState('');
now I have a input component:
<TextInput value={password} onChangeText={(e) => setPassword(e.target.value)} />, and I get an error which says: "property 'target' does not exist on type 'string"

A: onChangeText prop takes as a parameter the input text value, so you don't need to access e.target.value. Just use it like this:
<TextInput value={password} onChangeText={(text) => setPassword(text)} />


text:
Q: Sequencial chracterisation of $\limsup f(x)$ I am trying to understand the definition of $\limsup_{x\to a}f(x)$. There is a Wikipedia article that gives quite a few definitions. One of them is:

I think I understand it more or less. However, I came across the following post definition of limsup of a function. There it is said that $\limsup f(x)$ can be characterised in terms of sequences in the following way:

I tried to prove it, but I got stuck. I also tried to find a book that explains it, but I could't find a single book that covers $\limsup_{x\to a}f(x)$.Does anybody have any books that talk about it?
Many thanks in advance!

A: DEFINITION
Suppose $X$ is a metric space, $E\subset X$, $f$ maps $E$ into $\mathbb{R}^1$,
and $p$ is a limit point of $E$.
Define a set $L$ of extended real numbers as follows: If $\{p_n\}$ is a sequence
in $E$ converging to $p$ with $p_n\not=p$, and if $f(p_{n_k})\rightarrow l$
for some subsequence $\{p_{n_k}\}$, then $l\in L$.
Put
$$\limsup_{x\rightarrow p}f(x)=\sup L$$
and
$$\liminf_{x\rightarrow p}f(x)=\inf L\mbox{.}$$
In other words, $\limsup\limits_{x\rightarrow p}f(x)$ is defined to be the supremum of the set consisting of $\limsup\limits_{n\rightarrow\infty}f(p_n)$, where $p_n\rightarrow p$, $p_n\not=p$. (Note that $\sup\bigcup\limits_{\alpha\in A}E_\alpha=\sup\{\sup E_\alpha:\alpha\in A\}$.)
THEOREM 1
(a) If $y>\limsup_{x\rightarrow p}f(x)$, then there exists $\delta>0$ such that
$f(x)<y$ whenever $0<d(x,p)<\delta$, $x\in E$.
(b) If $y<\lim\sup_{x\rightarrow p}f(x)$, then for every $\delta>0$, there exists
$x\in E$ with $0<d(x,p)<\delta$, such that $f(x)>y\mbox{.}$
A similar result is valid for $\liminf$.
PROOF
(a) Suppose to every $\delta>0$ corresponds $x\in E$ such that $0<d(x,p)<\delta$
and $f(x)\geq y$. Take $\delta=\frac{1}{n}$, $n=1,2,3...$. We then obtain a sequence
$x_n\rightarrow p$, $x_n\not=p$ such that
$$f(x_n)\geq y\mbox{.}$$
Letting $n\rightarrow\infty$, we get
$$\limsup_{x\rightarrow p}f(x)\geq \limsup_{n\rightarrow\infty}f(x_n)\geq y\mbox{.}$$
This proves (a).
(b) Since $y<\sup L$, $l>y$ for some $l\in L$, which means that there exists a sequence
$x_n\rightarrow p$, $x_n\not=p$ such that $f(x_n)\rightarrow l$. Since $l>y$, $f(x_n)>y$
for all $n$ from some definite index $N$ onwards. For any $\delta>0$, there exists $n>N$
such that $0<d(p,x_n)<\delta$, since $x_n\rightarrow p$. Evidently, $f(x_n)>y$. $\square$
THEOREM 2
If $\liminf_{x\rightarrow p}f(x)=\limsup_{x\rightarrow p}f(x)=l$, then $f(x)\rightarrow l$
as $x\rightarrow p$.
PROOF
This follows immediately from Theorem 1(a).
THEOREM 3
If $g$ is another mapping of $E$ into $\mathbb{R}^1$, and if there exists $\delta>0$ such
that $0<d(p,x)<\delta$, $x\in E$ imply that
$$\tag{1}f(x)\leq g(x)\mbox{,}$$
then
$$\tag{2}\liminf f(x)\leq\liminf g(x)\mbox{,}$$
$$\tag{3}\limsup f(x)\leq\limsup g(x)\mbox{,}$$
as $x\rightarrow p$.
PROOF
We show (3). If $\limsup f(x)>y>\limsup g(x)$, then, by Theorem 1, there exist $\delta>\delta'>0$
such that
$$\tag{4}g(x)<y\quad(x\in E,0<d(x,p)<\delta')\mbox{;}$$
also, there exists $\xi\in E$ with $0<d(\xi,p)<\delta'$ such that
$$\tag{5}f(\xi)>y\mbox{.}$$
(4) and (5) contradict (1).
THEOREM 4
If $\lim\limits_{x\rightarrow p}f(x)=l$, then
$$\tag{6}\limsup\limits_{x\rightarrow p}f(x)=\limsup\limits_{x\rightarrow p}f(x)=l\mbox{.}$$
PROOF
Let $p_n\rightarrow p$ with $p_n\not=p$. Then $f(p_n)\rightarrow l$, so that
$$\limsup\limits_{n\rightarrow\infty}f(p_n)=\liminf\limits_{n\rightarrow\infty}f(p_n)=l\mbox{.}$$
Since $\{p_n\}$ is arbitrary, (6) follows.


text:
Q: What is a wrapper for an instance when using AppDomain.CreateInstance? May be a basic question:
I went through this,
secondDomain.CreateInstance("AssemblyA", "AssemblyA.Demo", true,
    System.Reflection.BindingFlags.CreateInstance, null,
    new object[] { 7, 3 }, null, null);

And looked at the explanation in form of comments.
   // Returns:
    //     An object that is a wrapper for the new instance specified by typeName. The
    //     return value needs to be unwrapped to access the real object.

MSDN: AppDomain.CreateInstance Method.
What is wrapper for object in this context? Why is this used? How to unwrap this?

A: You can see a wrapper as a 'c' or 'c++' pointer to another object.
You can unwrap it using the Unwrap method:
MyType testObj = (MyType) obj.Unwrap();

See this link for more info.


text:
Q: Getting an error writing R function with gsub Tried copying an old working code which substituted 2 values instead of 3. This isn't working though. Here it is:
Names <- c("Robert", "Mandy", "Mordecai")

Search <-function(find,relace,type){

gsub("find","relace",type)

}

Search("o","ooo", Names) #getting Names vector but no replacements

A: You need to remove the "'s from the line with the gsub call. Try:
gsub(find,relace,type)


text:
Q: Where are iptables rules fetched from while running command 'service iptables save'? I have created my own file- /etc/sysconfig/iptables-config.
On service iptables save my rules are successfully updated and that updates the /etc/sysconfig/iptables file as well.
Now even after i delete the /etc/sysconfig/iptables-config file, and make changes to /etc/sysconfig/iptables file, it will always return to the original one on service iptables save command.
Can you please explain from which file are these rules loaded, on running iptables save command.
Also, if I delete my INPUT chain rules, those are not getting updated on iptables save or restart. How do I update the iptables rules to take the value from iptables file or iptables-config file.


text:
Q: Google App Script - WRITE FROM GOOGLE SHEETS TO CLOUD SQL I'm trying to write data from a column in google sheets to a table in cloud sql.
Error is:
"Exception: The parameters (String) don't match the method signature for Jdbc.JdbcPreparedStatement.setString."
On line
stmt.setString('' + CopyData[i][0]);

I'm very new to google app script and have VERY limited knowledge of mySQL. Done a web development course in college about 10 years ago and havent looked at it since.
The code I'm trying to use is:
function WriteToDB() {

  var connectionName = 'xxx';
  var user = 'xxx';
  var userPwd = 'xxx1';
  var db = 'TestDB';
  var instanceUrl = 'jdbc:google:mysql://' + connectionName;
  var dbUrl = instanceUrl + '/' + db;
  var conn = Jdbc.getCloudSqlConnection(dbUrl, user, userPwd);
      conn.setAutoCommit(false);

  var SS_File = SpreadsheetApp.getActiveSpreadsheet();
  var SourceSheet = SS_File.getSheetByName("WorkSheet1");

  var headerRowNumber = 1;
  var CopyData = SourceSheet.getDataRange().offset(headerRowNumber, 0, SourceSheet.getLastRow() - headerRowNumber).getValues();

 var stmt = conn.prepareStatement('INSERT INTO TestTable ' +  '(TestColumn) VALUES (?)');

 for (var i = 0; i < CopyData.length; i++) {
  stmt.setString('' + CopyData[i][0]);
  stmt.addBatch();
}

  var batch = stmt.executeBatch();
  conn.comit();
  conn.close();

  var end = new Date();
  Logger.log('Time elapsed: %s ms for %s rows.', end - start, batch.length);
}

The connection is OK, I can create table etc through app script. Just can't write this data.
The data is in column A on the spreadsheet, header row is 1.
Can anyone help with this?
Thanks!
Ive tried
 for (var i = 0; i < CopyData.length; i++) {
  stmt.setObject(i, CopyData[i][0]);
  stmt.addBatch();

Error: "Exception: Parameter index out of range (0 < 1 )"
&
 for (var i = 0; i < CopyData.length; i++) {
  stmt.setObject(i+1, CopyData[i][0]);
  stmt.addBatch();

Error: "Exception: Parameter index out of range (2 > number of parameters, which is 1)"
&
 for (var i = 0; i < CopyData.length; i++) {
  stmt.setObject(i, CopyData[i]);
  stmt.addBatch();

Error: "Exception: Invalid argument value: java.sql.SQLException"
Stuck.

A: !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
WORKING CODE FOR ANYBODY TO USE IN THE FUTURE.
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
ONLY PROBLEM I HAVE IS THAT CLOUD SQL TIME-OUT RESTRICTIONS. - Working to resolve this, will provide solution once I solve the problem.
NOTE: MAKE SURE VALUES IN SOURCE SHEET ARE STRINGS, NO FORMULAS.
I had to copy values to another sheets using copy.to(xxx, {contentsonly:true}).
function WriteToDB() {

var connectionName = 'YOUR_CONNECTION_NAME';
var user = 'YOUR_USERNAME';
var userPwd = 'YOUR_PASSWORD';
var db = 'YOUR_DATABASE';
var instanceUrl = 'jdbc:google:mysql://' + connectionName;
var dbUrl = instanceUrl + '/' + db;

  var conn = Jdbc.getCloudSqlConnection(dbUrl, user, userPwd);
  conn.setAutoCommit(false);

  var SS_File = SpreadsheetApp.getActiveSpreadsheet();
  var SourceSheet = SS_File.getSheetByName("YOUR_SHEET_NAME");

  var headerRowNumber = 1; // HOW MANY ROWS TO MISS
  var CopyData = SourceSheet.getDataRange().offset(headerRowNumber, 0, SourceSheet.getLastRow() - headerRowNumber).getValues();

 var stmt = conn.prepareStatement("INSERT INTO YOUR_TABLE_NAME " +  "(YOUR_COLUMN_NAME) VALUES (?)");
    for (var i = 0; i < CopyData.Length; i++) {
        stmt.setString(1, CopyData[i][0]);
        stmt.addBatch();
    }
  var batch = stmt.executeBatch();
  conn.commit();
  conn.close();
}

A: I think I tried using batches and had no success so I go row by row and performance is still good.
I start by build the basic string:
var stmtStr = "INSERT INTO TestTable (TestColumn) VALUES (";

Then work with a copy of the basic string in the loop:
for (var i = 0; i < CopyData.length; i++) {
   query = stmtStr + CopyData[i][0] + ")";
   stmt = conn.createStatement();
   iUpdate = stmt.executeUpdate(query);
   if (i==0) {
     console.log(query, iUpdate, CopyData[i][0]);
   }
}


text:
Q: PHP Gmail IMAP Sent Items I got the sent items from gamil but how could we exclude those messages which are already fetched?? Basically, I am adding these emails to the database and want to exclude those messages which are already added to the database.
Here is a small piece of my code
$imapPath = '{imap.gmail.com:993/ssl}[Gmail]/Sent Mail';
$inbox = imap_open($imapPath, $username, $password) or die('Cannot connect to Gmail: ' . imap_last_error());

$emails = imap_search($inbox, 'BODY "Ticket #" SINCE "'.date("j F Y", strtotime('yesterday')).'"');
$output = '';
$count = 0;
if (is_array($emails) || is_object($emails)) {
    $ticket_no = array();
    foreach ($emails as $mail) {
        $overview = imap_fetch_overview($inbox, $mail, 0);

        $message = imap_body($inbox, $mail, FT_PEEK);

        list($text,$ticketno) = explode("#",$message);

        $message = strstr($message, 'charset="UTF-8"');
        $message = substr($message, 16, -83);

        $message = substr($message, 0, strpos($message, "Stay well and wash those paws!"));

        $ticketno = substr($ticketno, 0, strpos($ticketno, "*"));
        $ticketno = (int)$ticketno;
    }
}

A: Got it fixed by adding msg no in the database and check on each id.


text:
Q: how to store two classes inherit same interface in a SQL database I'm having trouble figuring out How should this be stored in a sql database
public interface IProduct {
    string Name { get; set; }
    decimal DoSomething();
}
public class Product1 : IProduct {
    public string Name { get; set; }
    //some other properties
    //.....
    public decimal DoSomething(){...}
}
public class Product2 : IProduct {
    public string Name { get; set; }
    //some other properties
    //.....
    public decimal DoSomething(){...}
}

if each product concrete class has its own table how to apply a get all products method?
Or should I have a BaseProduct table to store the names with a productType column and each product concrete class has its own details in another table? if that is the right way should those types be an enum in my library or there is a better way?


text:
Q: Easiest Way to get id or link and updated date from a RSS feed? I tried to use linq but failed because i have no xml knowledge.
What is the easiest way to get the id or link and updated from an rss feed? (an example feed -> https://stackoverflow.com/feeds/question/1926343)
I have no idea how to skip all elements until the first entry element. I also dont know how to pull each link and data from each elements from within the entry element

A: Here's a minimal example of how to do this:
var url = "http://stackoverflow.com/feeds/question/1926343";
var rss = new WebClient().DownloadString(url);
var doc = XDocument.Parse(rss);
var mgr = new XmlNamespaceManager(new NameTable());
var ns = "http://www.w3.org/2005/Atom";
mgr.AddNamespace("atom", ns);

foreach (var entry in doc.XPathSelectElements("/atom:feed/atom:entry", mgr))
{
    var id = entry.Element(XName.Get("id", ns)).Value;
    var link = entry.Element(XName.Get("link", ns)).Attribute("href").Value;
    var updated = entry.Element(XName.Get("updated", ns)).Value;
    Console.WriteLine(id);
    Console.WriteLine("\tLink: " + link);
    Console.WriteLine("\tUpdated: " + updated);
}

And here's the output that it generates:
http://stackoverflow.com/questions/1926343/alternative-to-thead-sleep-in-c
    Link: http://stackoverflow.com/questions/1926343/alternative-to-thead-sleep-in-c
    Updated: 2009-12-18T05:21:53Z
http://stackoverflow.com/questions/1926343/alternative-to-thead-sleep-in-c/1926359#1926359
    Link: http://stackoverflow.com/questions/1926343/alternative-to-thead-sleep-in-c/1926359#1926359
    Updated: 2009-12-18T04:56:01Z
http://stackoverflow.com/questions/1926343/alternative-to-thead-sleep-in-c/1926361#1926361
    Link: http://stackoverflow.com/questions/1926343/alternative-to-thead-sleep-in-c/1926361#1926361
    Updated: 2009-12-18T04:56:06Z
http://stackoverflow.com/questions/1926343/alternative-to-thead-sleep-in-c/1926365#1926365
    Link: http://stackoverflow.com/questions/1926343/alternative-to-thead-sleep-in-c/1926365#1926365
    Updated: 2009-12-18T04:58:08Z
http://stackoverflow.com/questions/1926343/alternative-to-thead-sleep-in-c/1926446#1926446
    Link: http://stackoverflow.com/questions/1926343/alternative-to-thead-sleep-in-c/1926446#1926446
    Updated: 2009-12-18T05:21:53Z


text:
Q: Have Concourse only build new docker containers on file diff not on commit So I have a pipeline that builds multiple docker containers from a single git repo.  It looks something like this:
---
resources:
- name: resource-docker
  type: git
  source:
    uri: https://github.com/$MYUSER/$MYREPO.git
    branch: master

# docker-image resources
- name: first-container
  type: docker-image
  source:
    repository: $MYUSER/first-container

- name: second-container
  type: docker-image
  source:
    repository: $MYUSER/second-container

jobs:
# image-update jobs
- name: first-container-image-update
  public: true
  serial_groups:
    - serial_lock
  plan:
  - get: resource-docker
    serial: true
  - put: first-container
    params:
      build: resource-docker/first-container-path

- name: second-container-image-update
  public: true
  serial_groups:
    - serial_lock
  plan:
  - get: resource-docker
    serial: true
  - put: second-container
    params:
      build: resource-docker/second-container-path

The problem is that running a resource-docker task is taking up a significant portion of system resources and rebuilding the containers from scratch on each commit to the master (which contains more code than just the docker containers).
I would like to make these tasks instead compare the old and new files used to build the containers, and only rebuild a container if there is a diff in the files.
Note: that separating the files out into different repos is an option I want to avoid.

A: your resource can be configured to trigger new builds only with changes to specific files in the repo:
- name: resource-docker
  type: git
  source:
    uri: https://github.com/$MYUSER/$MYREPO.git
    branch: master
    paths:
      - <path/to/Dockerfile/or/whatever>
      - <path/to/other/triggering/diffs>

A: In case Quintana's answer isn't totally clear, the idea is you can define multiple Git resources which point at the same Git repository. Each resource can use paths / ignore_paths to specify which filed to look at.


text:
Q: In firefox is it possible to find where javascript function runs? I want to know which function runs when we click on an anchor on a site.
I am having an issue that when we click on an anchor, a function runs to retrive data from ajax. I want to find out where the ajax is called.
I am using jquery.
Are there any plugins for the task ?
EDITED
I am not able to figure out the function from the source. There are MANY minified scripts, with no selector to the required event.
Plugins are just an option. I am open to any alternatives to find the correct solution.

A: Firefox has an option to inspect JavaScript function like html inspecting.
You'll find it near or after your element after inspecting source code as a ev sign.
Just click on the ev sign and you'll get what functions are working when you click on the anchor.
Here's an screenshot and documentation from FireFox Doc


text:
Q: Relationship between energy and temperature in ideal gas I have encountered this old question and since I was bored I figured I use statisical mechanics to derive the relationship $E=\frac{3}{2}kT$ for a single particle in an ideal gas without using outside help. As a disclaimer, it has been a while since I had statistical mechanics courses, so I am a bit rusty. I have encountered some strange results I cannot explain and am curious about.
The problem: Using microcanonical ensemble for a single particle gives $E=(1/2)kT$. Using canonical ensemble for a single particle gives $E=(3/2)kT$.
Using canonical enseble for $N$ particles, the energy per particle $E/N$ is $E/N=(3/2)kT$. Using microcanonical ensemble for $N$ particles, the energy per particles is $E/N=(3/2-1/N)kT$. Clearly the latter goes to $(3/2)kT$ in the $N\rightarrow\infty$ limit.
Questions:

*

*An ideal gas is noninteracting, so there should be no difference between using a single-particle ensemble and a multiparticle ensemble, right? Why is it that the canonical ensemble gives the same results in both cases, but the microcanonical is different?

*Why do the microcanonical and canonical ensembles give different results, aside from the $N\rightarrow\infty$ limit? In particular, the microcanonical ensemble, while probably the furtherst removed from experiment, is the "purest" ensemble from a theoretical standpoint, the one that comes directly from the postulates of statistical mechanics. Is the formula $E=(3/2)kT$ valid only when $T$ is fixed? Or what?
The calculations I have used are presented below:

Ideal gas using microcanonical ensemble:
Assume we have an ideal gas in a box of volume $V$, at energy $E$ (at an uncertainty $(E,E+\delta E)$), and since the particles of an ideal gas are noninteracting anyways, we consider $N=1$.
The number of microstates is taken to be the phase volume between $E$ and $E+\delta E$, where $\delta E$ is a first-order "infinitesimal".
This can be calculated by calculating $\Omega(E'<E)$ the number of microstates whose energy is less than $E$. This is the following phase volume: $$ \Omega(E'<E)=\int_Vd^3x\int_Bd^3p, $$ where $B$ is the ball in momentum space given by $B=\{(p_x,p_y,p_z):\ p^2<2mE\}$, so $$ \Omega(E'<E)=Vg(2mE)^{3/2}, $$ where $g$ is an irrelevant constant. The number of microstates (of energy $E$) is then $$ \Omega(E,E+\delta E)=\frac{\partial}{\partial E}\Omega(E'<E)\delta E=\frac{3}{2}gV(2mE)^{1/2}2m\delta E=3gVm(2mE)^{1/2}\delta E. $$
The entropy is $S=k\ln\Omega$ so $$ S=k\left[\ln(3gVm\delta E)+\frac{1}{2}\ln(2m)+\frac{1}{2}\ln E\right], $$ the reciprocal of temperature is then $$ \frac{1}{T}=\frac{\partial S}{\partial E}=\frac{k}{2}\frac{1}{E}, $$ from which we get $$ E=\frac{1}{2}kT. $$
This is missing a factor of 3. Using a canonical ensemble on the other hand gives the proper answer:
Ideal gas using canonical ensemble:
We now consider the ideal gas fixed at temperature $T$, at volume $V$ and at particle number $N=1$.
The canonical partition function is $$ Z=V\left(\frac{2m\pi}{\beta}\right)^{3/2}, $$ the expectation value of energy is $$ E=-\frac{\partial}{\partial\beta}\ln Z=\frac{\partial}{\partial\beta}\frac{3}{2}\ln\beta=\frac{3}{2}\frac{1}{\beta}=\frac{3}{2}kT, $$ which is the result I expect.
Now, I have no idea why the microcanonical ensemble gives only the third of the expected result but I considered using an $N$-particle gas instead of a single particle gas. The canonical ensemble gave $E=(3N/2)kT$, so the energy of a single particle is $E/N=(3/2)kT$, the same as before, so I will not do this calculation here. The microcanonical ensemble was different however.
$N$-particle ideal gas using microcanonical ensemble:
The number of microstates whose energy is less than $E$ is now given as $$\Omega(E'<E)=V^Ng(2mE)^{3N/2},$$ where $g$ is a different constant, but still irrelevant. The number of microstates (of energy $E$) is then $$\Omega(E,E+\delta E)=\frac{\partial\Omega(E'<E)}{\partial E}\delta E=3NmgV^N(2mE)^{(3N/2)-1}\delta E,$$ the entropy is $$S=k\ln\Omega=k\left[\left(\frac{3N}{2}-1\right)\ln(2mE)+c\right],$$ the reciprocal temperature is $$\frac{1}{T}=\frac{\partial S}{\partial E}=k\left(\frac{3N}{2}-1\right)\frac{1}{E}, $$ $$ E=\left(\frac{3N}{2}-1\right)kT. $$ The energy for a single particle is then $$ \frac{E}{N}=\left(\frac{3}{2}-\frac{1}{N}\right)kT. $$ In the limit $N\rightarrow\infty$, this reduces to $E=(3/2)kT$.

A: You cannot use the microcanonical ensemble one particle at a time.  The reason is that the energies of the particles are not independent; if one particle has some of the energy, it lowers the total energy available to the other particles.  (The canonical ensemble exists to get around this complication.)  Moreover, while the particles are "noninteracting" in an ideal sense, there must be some weak interactions in order for the distributions of velocities to thermalize.
As a further illustration of the failure of applying the microcanonical ensemble one particle at a time, note that it predicts that the average energy is in fact the exact energy for every particle.  This is clearly not a description of the correct distribution function.


text: Q: Extract array of limbs from mpf_class (GMP) Given an mpf_class variable how exactly do I extract the array of limbs associated to the mantissa? For example I want to do some bitwise operations on one of the limbs. I tried reading the GMP documentation however I ended up a bit confused.


text:
Q: Nested pages in Array - PHP I'm retrieving all the pages in my database for a custom CMS. The pages are nested and have parent_id to find the children of parent pages.
The code to retrieve the code is :
public function get_nested ()
{
    $pages = $this->db->get( 'pages' )->result_array();

    $array = array();
    foreach ( $pages as $page )
    {
        if ( !$page['parent_id'] )
        {
            $array[$page['id']] = $page;
        }
        else
        {
            $array[$page['parent_id']]['children'][] = $page;
        }
    }

    return $array;
}

For some reason the else condition isn't working with $array[$page['parent_id']].
A dump of $pages gives me
Array
(
    [0] => Array
        (
            [id] => 1
            [title] => Homepage
            [slug] => /
            [order] => 1
            [body] => Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do     eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat.
            [parent_id] => 0
        )

    [1] => Array
        (
            [id] => 3
            [title] => Contact
            [slug] => contact
            [order] => 0
            [body] =>
This is my contact page.

            [parent_id] => 4
        )

    [2] => Array
        (
            [id] => 4
            [title] => About
            [slug] => about
            [order] => 0
            [body] =>
All about our company.

            [parent_id] => 0
        )

)

So I am expecting contact to appear in the else part of the condition. I've tried just echoing 'parent' and 'child' in the conditions and it works but when writing $array[$page['parent_id']] nothing is appearing, not even a block saying that it's empty.
The response I'm currently getting is:
Array
(
    [1] => Array
        (
            [id] => 1
            [title] => Homepage
            [slug] => /
            [order] => 1
            [body] => Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do     eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat.
            [parent_id] => 0
        )

    [4] => Array
        (
            [id] => 4
            [title] => About
            [slug] => about
            [order] => 0
            [body] =>
All about our company.

            [parent_id] => 0
        )

)

Does anyone know why $array[$page['parent_id']] isn't doing anything? I thought it would give me a children array inside [4] but nothing is there. I've checked the type of the parent_id inside the database and it's INT(11) so that shouldn't be creating the problem.
Thanks in advance.

A: It will set the children in your array.. But this code has one bug. When the children appears before it's parent, it's gonna set children first but you are overwriting the the $array when parent appears after children in following condition ..
if ( !$page['parent_id'] )
{
    $array[$page['id']] = $page;
}

So it will not preserve already set children.
You have to do something like this:
if ( !$page['parent_id'] )
{
    if(!isset($array[$page['id']]))
        $array[$page['id']] = $page;
    else
       $array[$page['id']] = array_merge($page,$array[$page['id']]);
}

It will preserve the children then. Let me know if that works.

Update: I just tried to run your program with above condition... Its giving output like this:
array
  1 =>
    array
      'id' => int 1
      'title' => string 'homepage' (length=8)
      'parent_id' => int 0
  4 =>
    array
      'id' => int 4
      'title' => string 'about' (length=5)
      'parent_id' => int 0
      'children' =>
        array
          0 =>
            array
              'id' => int 3
              'title' => string 'contact' (length=7)
              'parent_id' => int 4


text:
Q: How to decide what database configuration should be built for various applications like OLTP, Reporting, High Availability, etc in sybase ASE I am trying to figure out how to set up different labs configurations for Sybase ASE depending upon the applications for which it's going to be used like OLTP, OLAP, Reporting or High Availability.
I am okay to involve using the Sybase IQ, Sybase Replication if there is a need.
Could anyone have any vision or way to explore it?

A: I think you should search in sybase technical white papers.
F.e.
HA -
Managing Workloads with ASE: Techniques for OLTP Scaling and Performance Management with Large SMP and Shared Disk Clusters
http://www.sybase.com/detail?id=1091630
Sybase CEP High Availability
http://www.sybase.com/detail?id=1086848
DWH and REP
Sybase Replication Server Real — Time Loading into Sybase IQ
http://www.sybase.com/detail?id=1089003


text:
Q: How to SUMIF contains a partial string in Pandas I have a data frame which contains a list of items I want to sum if they are a partial match to another list. What I want to do is the following:

*

*Look through each item in list 1.

*Find all the items in list 2 which are a partial match to 1.

*Sum all those elements and insert into new column (i.e. sum of cost).

There is an implementation of this in excel I want to replicate in Pandas.
=sumif(b7:b32,"*"&b3&"*",c7:32)

https://www.webanalyticsworld.net/2014/07/using-ngrams-to-analyse-keyword-performance.html
import pandas as pd
import numpy as np
import re

sqr = pd.read_csv('Search terms report (7).csv', encoding='utf-8', skiprows=2, skipfooter=2, engine='python')

search_terms = sqr['Search term']

required_ngrams = 2

ngram_holder = []

ngrams = []

def generate_ngrams(s, n):
    s = s.lower()
    s = re.sub(r'[^a-zA-Z0-9\s]', ' ', s)
    tokens = [token for token in s.split(" ") if token != ""]
    ngrams = zip(*[tokens[i:] for i in range(n)])
    return [" ".join(ngram) for ngram in ngrams]

for x in search_terms:
    if len(x) > 0:
        ngram_holder.append(generate_ngrams(x, required_ngrams))

for x in ngram_holder:
    if x:
        for y in x:
            ngrams.append(y)

df = pd.DataFrame(ngrams)

df = df.drop_duplicates()
df.columns = ['Search term ngram']
sqr = sqr[['Search term','Cost','Clicks','orders','Online Sales']]

sqr

This code products 2 lists. One containing the list of keywords and the other containing the search terms along with the data.
What I want to do is sumif on the first list and pull in all items which are a partial match to the keywords in list2.


text:
Q: Debug highlighting missing in VSCode Somehow, after a vscode update my debug line-highlighting line is gone. Debugging works normal, but I never see the correct debugging line. The grey highliting in the screen below is just the cursor-line highlighting.
In the picture below, current debug position is line 147 - but no yellow debug line.
When i press F5, the next line gets highlighted grey, because the cursor switches there. But still no yellow highlight for my currently debuged line. When i click on on another line in the code the grey line switches to that position, leaving the current debug line without any highlighting.
I have a skin installed, "Solarized Express Soda", but deactivation does not fix this.
Is it possible to switch vscode versions back to test this further? Or to deactivate all extentions at once to have a vanilla vscode to approach the problem via elimination process?
VScode Version 1.46.1,
Node Version 10.21.0

A: Actually, i solved the problem now.
I installed a previous version of vscode, january 1.42.1 - Now it works again properly. I think i will report this issue on the vscode forums.  Pherhaps an issue in correlation with my many extentions & old node version 10.21.0(which is still in need - thats another topic)
But perhaps, someone can tell me what I've done wrong, actually, i cant see anything wrong on my side here...


text:
Q: event handler hooking point and mobile safari highlight box I have a set of clickable divs inside a container div.
I want to handle the click event of all of them in a single handler on the container div.
however this causes mobile safari to highlight the the container div when one of the inner divs is clicked.
Is there a way to maintain the single event handler and yet tell it somehow what is the right child node to highlight?


text:
Q: Using Postsharp to introduce a constructor I have some dependencies inside of my aspects, and I'd like use an IoC container to manage the lifecycle of these dependencies.
My first thought is that introducing a constructor which takes one more argument than the most specific constructor in the type would be a good way to solve this.
I can't seem to find a way to do this however, and I was wondering if A) this is possible, and B) Whether there are better solutions to this problem.

A: You need to use Introduction. See the following tutorials.
http://www.sharpcrafters.com/blog/post/PostSharp-Principals-Day-14-e28093-Introducing-members-and-interfaces-Part-1.aspx
http://www.sharpcrafters.com/blog/post/PostSharp-Principals-Day-15-e28093-Introducing-members-and-interfaces-Part-2.aspx


text:
Q: What can I do to stop a character's movement upon hitting an object? I want my controlled character to completely stop moving when he hits a specific object (and not regain control until he answers the question correctly.) But I can't seem to figure out how to make him stop and remove control from the user, removing the key functions that allow character movement only works for the first instance of this and afterwards only stops the character if he falls onto the object rather than touch it (basically keeps moving the character if he touches the object horizontally in every instance afterwards). The current code for the hitTest is below if it helps.
addEventListener(Event.ENTER_FRAME, information);
function information(e:Event)
{
if (player.hitTestObject(folder))
{
    removeChild(folder);
    myInfo.alpha=100;
    myInfo.gotoAndStop("folder1");
    myInfo.x=player.x;
    myInfo.y=player.y-50;
    stage.addEventListener(KeyboardEvent.KEY_DOWN,kU);
    //stops player movement
    myInfo.myA.addEventListener(MouseEvent.CLICK, answerA);
    function answerA(event:MouseEvent)
    {
    trace("answer A");
    myInfo.alpha=0;
    stage.removeEventListener(KeyboardEvent.KEY_DOWN, kU);
    }

the "kU" function is the function that checks whether a key is not being pressed and doesn't seem to work when i switch it with the "key down function" I have. the code for movement is below.
function loop(e:Event)
{
if (kLeft)
{
    speedX=-15;
}
if (kRight)
{
    speedX=15;
}
else
{
    speedX*=0.5;
}

A: You can use a boolean value and set it to true when the object hits  the specific object you want , then if the boolean value is true you disable the movement code , but when it becomes say false you can activate it again ...
So basically the movement code depends on the boolean value ...
Regards

A: Nullifying the "kLeft" variable and the "kRight" variable effectively stops the character upon the hitTest. The reason nothing else would work is because the Movement is in a seperate function than the hitTest (so i guess it would constantly detect movement and count that instead). Anyways, the code i used was
kLeft = null;
kRight = null;


text:
Q: Hard delete the associated records for which soft delete is enabled in rails I have a user model and no soft deletion is enabled for the user model. For one it's associated model(has_many association) say posts, soft deletion is enabled. What I want is to hard delete all the associated posts when a user is deleted.
In User.rb
has_many :posts, dependent: :destroy

Which just soft deletes the associated records. So the exception will be raised when deleting the user. Is there any option to hard delete the associated records in the model level?. Or have to do something in before_destroy callback to achieve this?
Note: Have used paranoia gem for soft deletion

A: If you want to hard-delete the associated posts, you can use dependent: :delete_all. This will go directly to the database to delete the records and bypass the before_destroy callbacks registered by the paranoia gem.


text:
Q: Shell script as default action for downloads in Firefox Is it possible to have a shell script as default download action in Firefox? In the manual (https://support.mozilla.org/en-US/kb/change-firefox-behavior-when-open-file) only GUI programs are discussed.
I want zip files automatically passed to unzip , so they are automatically unextracted instead of having to choose extract options in my GUI program. The "Use other" option in Firefox only allows me to pass a program without any parameters. When I tried to use a shell script it didn't get executed at all, instead the file was saved to "Downloads" only.
I am running Firefox 64 on Linux.

A: It actually worked the second time. One has to make sure the script is executable. The script I used for automatically unpacking zip archives is:
#!/usr/bin/bash

filename=$(basename -- "$1")
filename="${filename%.*}"

unzip $1 -d "$HOME/Downloads/$filename/"

For extraction of filename without extension: https://stackoverflow.com/questions/965053/extract-filename-and-extension-in-bash


text:
Q: Prestashop 1.7 Webservice Authetication Error In Prestashop 1.7 I'm trying to interact with webservice using prestapyt.
from prestapyt import PrestaShopWebServiceDict
prestashop = PrestaShopWebServiceDict('http:\\hostname.ext\api', 'APIKEY')
ps = prestashop.search('addresses')

I get this error
prestapyt.prestapyt.PrestaShopAuthenticationError: 'Unauthorized'

To try to understand if is an error of the library, I've tryied to connect at the API via browser.
Connecting at http:\hostname.ext\api I get a login request.
Inserting in the username filed the APIKEY and leaving the password field blank as indicated here I get the Unauthorized error again.
The authetication works only setting the APIKEY as querystring
http:\\hostname.ext\api?&ws_key=APIKEY

But this method is not available in prestapyt that user session authetication.
There's some setting on Prestashop that I missed or a way to understand this problem?
Thank you

A: Found the problem and solved the case in this way.
The problem is not releted to Prestashop or prestapyt but relative to the server configuration (Apache + PHP).
Considering that in my case I'm working in a managed cloud service, I don't have in depth information about that.
But the result of this configuration is that the Authorization header does not appear in the $_SERVER variable. The same behavior reported here:
Why are $_SERVER["PHP_AUTH_USER"] and $_SERVER["PHP_AUTH_PW"] not set?

I solved adding this statement to the .htaccess file in my Prestashop installation:
SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1

As suggested here.
I hope to help others Prestashop users that incur in the same problem.


text:
Q: functional iteration convergence
functional iteration sequence $x_{n+1} = 2 - (1+c)x_n + cx_{n}^3$ will converge for some values of c to $ \alpha = 1$ for what values of c this sequence will converge?

My attempt to solve this was using contractive mapping theorem First finding a closed set $ D = [1-a, 1+b] $ and show that $ f: D \rightarrow D $ and also $ |f^{'}(x)| < 1$ then by the contractive mapping theorem this series will converge to a unique fixed point in $D$ which is 1.
$f^{'}(x) = -1 - c + 3cx^2$ is for some values of c always less than 1 but for some values not. I'm not sure how to define c value.

A: You get as progression of the distance to the fixed point
$$
\frac{x_{n+1}-1}{x_n-1}=c(x_n^2+x_n)-1.
$$
To get convergence you need the right side to be smaller than $1$ in absolute value. This gives
$$
0<c(x^2+x)\le 2\iff \frac14<\left(x+\frac12\right)^2<\frac2c+\frac14
$$
To get $x=α=1$ inside the contracting interval one needs $0<c<1$. The interval is then
$$
0<x<\sqrt{\frac2c+\frac14}-\frac12=1+\frac{4(1-c)}{\sqrt{8c+c^2}+3c}
$$

A: Except when $c=0$, the convergence depends largely on the initial value $x_0$.
For example, if $c \ne 0$ and $|x_0|> \max(100/|c|,5)$, you can prove easily that by induction that:
$$|x_{n+1}|>2|x_n|$$
which means the sequence doesn't converge.

A: When $c=0$ then $x_{n+1}=2-x_n$ and except when $x_0=1$ the sequence will alternate between values $\{x_0,2-x_0\}$ and won't be convergent.
So let assume $c\neq 0$ and study $f'(x)=3cx^2-1-c$

*

*$f'(x)<1\implies 3cx^2-1-c<1\implies c<\dfrac{2}{3x^2-1}=1-3(x-1)+o(x-1)$
Remember that we want also that $x$ belongs to a neighbourhood of $1$, therefore $c\le 1$

*

*$f'(x)>-1\implies 3cx^2-1-c>-1\implies (3x^2-1)c>0\implies c>0$
So at least for $f$ to be contractive we need $c\in(0,1]$.
https://www.desmos.com/calculator/g8fqi7qo0y
But as Paresseux noticed, the choice of $x_0$ is also very prominent, indeed the conditions above can be expressed in term of $x$:

*

*$f'(x)<1\implies x^2<\frac{c+2}{3c}$

*$f'(x)>-1\implies x^2>\frac{1}{3}$
Which you can verify are the regions in orange on the diagram.
If some $x_{n0}$ falls in this region then convergence is ensured for the following terms, but still there are some $x_0$ outside this region for which it is possible that a subsequent term falls in the region and the sequence will converge anyway.
Try for instance $c=0.4$ and $x_0=0.2$
f(0.2);    1.7232
f(%);      1.634280604
f(%);      1.457989590
f(%);      1.198533584
f(%);      1.010722110
f(%);      0.997994028
f(%);      1.000406020

And this is a much difficult issue to predict for which initial values $x_0(c)$ the sequence will always be convergent.


text:
Q: Allow guest read/write access to Netatalk AFP share I am running Netatalk 3.14dev on Ubuntu 14.04. This box is being used as a webserver and we already have a Samba share pointed at the /var/www folder to allow our developers to work on sites hosted on the server.
The Samba share is configured to allow full guest read/write access, and files created / edited via the share are forced to be written as "www-data" so that Apache can use them.
How do we mirror this set up using Netatalk to allow Macs to connect via AFP? There are some permissions / locking issues with Samba and I'm trying AFP as a solution. I can configure the share using Netatalk but cannot allow guest write access - it is currently read only.
I have this in /usr/local/etc/afp.conf:
[Global]
; Global server settings
log file = /var/log/netatalk.log
uam list = uams_guest.so

[PHP Sites]
path = /var/www
file perm = 0664
directory perm = 0775
guest account = www-data

A: guest account should be defined inside [Global] section.
After fixing that, it should work.


text:
Q: How to exclude an element from an array? I have a v-for to display all my categories. I would like to exclude a category, this category has an id = 1. So basically how can I remove by Id ? or maybe how can I exclude the first element of the array ? what do I do ?

A: You can use v-if.

  <template v-if="category.id === 1">
    ...

A: Use computed property component option.

computed: {
    filteredCategories: function(){
       //example ids to ignore
       var ignore = [1, 10];
        return this.categories.filter(cat => ignore.indexOf(cat.id) === -1);
    }
}

A: To get all categories with an id greater than 1, the cleanest way would be to have a filteredCategories computed:

computed: {
  filteredCategories: {
    return this.Categories.filter(cat => cat.id > 1);
  }
}

Vue.config.devtools = false;
Vue.config.productionTip = false;
new Vue({
  el: '#app',
  data: () => ({
    Categories: [
      {id: 1, name: 'I won\'t get rendered!'},
      {id: 2, name: 'Second category'},
      {id: 3, name: 'Third category'},
      {id: 4, name: 'Fourth category'},
      {id: 0, name: 'I won\'t get rendered, either. My id is `0`'}
    ]
  }),
  computed: {
    filteredCategories() {
      return this.Categories.filter(cat => cat.id > 1);
    }
  }
})

    {{category.id}} - {{ category.name }}

The advantages are:

*

*the initial Categories array is not mutated, so if you use it anywhere else in the component it will still contain all categories (which is not true if you filter using .splice)

*the filtering is done based on the value of id, not on the category position in the array.

Here's how to get the Categories from the api:
data: () => ({
  Categories: []
}),
computed: {
  filteredCategories() {
    return this.Categories.filter(cat => cat.id > 1);
  }
},
mounted() {
  axios.get("path/to/your/api")
    .then(response => this.Categories = response.data);
}


text:
Q: Geometry Dash: Having Problems I am having several problems with geometry dash (update 2.0). The game starts up just fine, and I don't have limited access to the game, but whenever I tap the profile button, it always says "something went wrong...". If I hit the refresh button, then weird stats will come up. They are: 88 Stars, 20 Secret Coins, 0 User Coins, 0 Demon Levels, and the basic icons with red and blue. What's wrong, and what can I do to fix it?
Also, a while back I made an account. The problem was when I posted a level, the last letter was cut off. So, I changed my username, but my shown username was still the same. Any idea why?
I know I'm asking for a lot, but I would be grateful for any help. Thanks in advance!

A: I know the answer only for the not changing name.
It happened also to me, and I think it is normal. You have just to wait a bit (2 - 3 weeks) and it will fix itself. That means you probably already have your name fixed. If not, then I don't know any other solutions.


text:
Q: NSURLErrorDomain code=-1005 from GKLeaderboard loadScoresWithCompletionHandler: I am receiving the following error in a callback to loadScoresWithCompletionHandler:
Error Domain=NSURLErrorDomain Code=-1005
"The operation couldn't be completed. (NSURLErrorDomain error -1005.)"

Other calls to Game Center both before and afterwards succeed. (They operate on various threads). If have initialized the leaderboard request as follows:
GKLeaderboard *leaderboard = [[GKLeaderboard alloc] init];

leaderboard.identifier  = leaderboardIdentifier; // valid identifier
leaderboard.playerScope = GKLeaderboardPlayerScopeFriendsOnly;
leaderboard.range       = NSMakeRange(1, 100); // max. allowed range.
leaderboard.timeScope   = GKLeaderboardTimeScopeAllTime;

[leaderboard loadScoresWithCompletionHandler:^(NSArray *scores, NSError *error) {
    // ...
}];

What is going on here and how can I overcome this problem?
The calls to loadScoresWithCompletionHandler: are made from an operation on an NSOperationQueue whose task it is to issue requests for scores (I am interested in each localPlayerScore) to several leaderboards and wait for all responses. The first response already carries the error.
UPDATE -1005 denotes kCFURLErrorNetworkConnectionLost; the underlying cause is still unclear.
UPDATE If I send only a single request (instead of as so far typically 6 in parallel) I receive error NSURLErrorDomain -1001, which denotes kCFURLErrorTimedOut, or GKErrorDomain 3 ...

A: For some reason this alternative call does not lead to errors:
GKLeaderboard *leaderboard =
    [[GKLeaderboard alloc] initWithPlayers:@[ GKLocalPlayer.localPlayer ]];

leaderboard.identifier = leaderboardIdentifier;
leaderboard.timeScope  = GKLeaderboardTimeScopeAllTime;

[leaderboard loadScoresWithCompletionHandler:^(NSArray *scores, NSError *error) {
    // ...
}];

Problem solved.


text:
Q: SQL Server won't recognize \r? Simple query :
UPDATE [WebERP].[dbo].[Users]
   SET
       [ActiveDirectoryUser] = null

WHERE ActiveDirectoryUser='xxx\royin'

Error :

Msg 512, Level 16, State 1, Procedure Users_Update, Line 17
  Subquery returned more than 1 value. This is not permitted when the subquery
  follows =, !=, <, <= , >, >= or when the subquery is used as an
  expression. The statement has been terminated.

I guess the problem is here :

it treats it as carriage return.
(if I change \r to \b it's ok.)
How can I fix it ?

A: I think your error in fact lies elsewhere - I assume you've given us a much simplified query which in fact doesn't reproduce the original error, or you've only given us one part of a bigger query.
For one thing - it says the error occurs in a subquery - your example doesn't contain one.
The code you've provided works fine on my adventureworks database:
update SalesLT.Address
set AddressLine2 = 'abc\nd'
where AddressID = 9

Does exactly as expected.


text:
Q: How to override AddAllFields() method in Sitecore with Sitecore.ContentSearch We are upgrading Sitecore from 6.6 version to 8.1. Every thing is going as expected but facing issue in custom Lucene search migration which need to migrate into Solr - 6.1.0.
Actually, we implemented custom search like as below code and index configuration:
namespace BusinessModules
{
    public class PeopleIndexer : Sitecore.Search.Crawlers.DatabaseCrawler
    {
        public class PeopleIndexer : Sitecore.Search.Crawlers.DatabaseCrawler
        {
            protected override void AddAllFields(Document document, Item item, bool versionSpecific)
            {
                //People

                //FirstName
                if (item.Fields["FirstName"] != null)
                {
                    string fName = item.Fields["FirstName"].GetValue(false).Trim().Replace("-", string.Empty);
                    if (!string.IsNullOrEmpty(fName))
                    {
                        document.Add(new Field("FirstName", fName.ToLower(), Field.Store.YES, Field.Index.ANALYZED));
                    }
                }
                .........................
                .........................
                .........................
            }
        }
    }
}

<index id="PeopleIndex" type="Sitecore.Search.Index, Sitecore.Kernel">
    <param desc="name">$(id)</param>
    <param desc="folder">__people</param>
    <Analyzer ref="search/analyzer"/>
    <locations hint="list:AddCrawler">
      <customSearch type="BusinessModules.PeopleIndexer,BusinessModules">
        <Database>web</Database>
        <Root>/sitecore/content/Global Content/People</Root>
        <Tags>people</Tags>
        <Boost>2.0</Boost>
        <IndexAllFields>false</IndexAllFields>
        <include hint="list:IncludeTemplate">
          <includeTemplate>{EB65BFA3-5122-43F4-A1B0-02F430F645CA}</includeTemplate>
          <!--Person-->
        </include>
        <fieldTypes hint="list:AddTextFieldType">
          <fieldType>single-line text</fieldType>
          <fieldType>multilist</fieldType>
          <fieldType>treelist</fieldType>
          <fieldType>treelistex</fieldType>
          <fieldType>checklist</fieldType>
        </fieldTypes>
        <fieldTypes hint="list:RemoveTextFieldType">
          <fieldType>multi-line text</fieldType>
          <fieldType>word document</fieldType>
          <fieldType>html</fieldType>
          <fieldType>rich text</fieldType>
          <fieldType>memo</fieldType>
        </fieldTypes>
      </customSearch>
    </locations>
</index>

Is there any way to implement as it's code (or need minimal change ) in Sitecore Solr with Sitecore.ContentSearch?


text:
Q: Getting Perforce client workspace handling automated I am trying to automate access to Perforce via it's command line utility.
Creating a new client workspace with p4 client and syncing works ok.
Now I am allowing users to overwrite user, host, port, stream, revision.
From the docs it is not clear to me when I have to execute which commands to get the client workspace files in sync with an edited client workspace spec.
What I currently do is once p4 client is through search for
Client mymachine not changed

in stdout and do a p4 sync -f should the message not appear.
Is there a better or more sane way to do this?
I tried executing e.g. p4 sync -s in hope that it would fail should local data be deleted but it seems that I misunderstood the option?

A: It is not clear to me how this relates to your question about workspaces:

Now I am allowing users to overwrite user, host, port, stream,
  revision.

since only one of those is a property of a workspace.  I'm going to disregard that statement for now but if it was significant I'd encourage you to post a follow-up clarifying what you mean by "overwriting" each of these properties.
To your question:

From the docs it is not clear to me when I have to execute which
  commands to get the client workspace files in sync with an edited
  client workspace spec.

If the client View is updated, all you need to do is:
p4 sync

If the client Root is updated, or any of the other options that globally affect how files are written to the workspace, such as allwrite or modtime, you will need to re-sync the entire client.  Ideally this is done by doing:
p4 sync #none

prior to changing the workspace in one of these ways.  The other option would be to do something like the following sequence:
p4 sync #none
p4 sync
p4 clean

to make sure that everything is rewritten, and that any stragglers (e.g. anything that the "sync #none" couldn't locate because the Root had changed but that are still mapped in the client view) are removed from the workspace.

I tried executing e.g. p4 sync -s in hope that it would fail should
  local data be deleted but it seems that I misunderstood the option?

Deleting local data is a separate issue from editing the client spec, but for that the command you want is p4 clean rather than p4 sync -- you use sync to tell the server you want it to send you new revisions, you use clean to bring your workspace back in line with what the server already sent you.
The recommended/supported workflow is to always use p4 commands to manipulate the read-only files in your workspace -- so if you want to delete a local file, use either p4 sync FILE#none (to remove it from your workspace but not affect the depot) or p4 delete FILE (to open it for delete so that it will be deleted for everyone when you submit).


text:
Q: Hiding (not eliminating) duplicates in ColdFusion array We have a three-panel display in which Panel One shows a list of countries, Panel Two shows a list of organizations, and Panel Three shows a list of aircraft. If you click a country, both the organizations and aircraft are filtered by that country, using IDs for each.
This is all working fine, but the list of aircraft comes from a "linking table" -- each record contains aircraft ID and name, and operator ID and name. Any given type of aircraft can be listed multiple times, depending on how many organizations operate it. For example, "AW159 Wildcat" is listed twice, once for Army Air Corps and once for Royal Navy. The way it works right now, "AW159" is listed in Panel Three twice when the page initially loads.
I would like any given aircraft to be displayed only once on initial page load, regardless of how many times it may be listed in this linking table. But, I want all the "duplicates" available to be shown, if somebody filters on the operating organization.
Is there a way to loop over all the aircraft but somehow hide duplicates of aircraft ID? Or, might there be a larger problem with the way our database is designed? I am open to suggestions. Thank you all very much in advance!
EDIT: sorry for not posting code; here is some. Thanks everybody for all of your help!
1. Query and array population in cfc:
    <cfquery name="queryByOperator" datasource="vertipedia">
        SELECT view_aircraftbyoperators.aircraftID
          , view_aircraftbyoperators.Aircraft
          , view_aircraftbyoperators.operatorID
          , view_aircraftbyoperators.Operator
          , tbl_companies.country
          , tbl_companies.companyShortName
        FROM view_aircraftbyoperators JOIN tbl_companies
            ON tbl_companies.ID = view_aircraftbyoperators.operatorID
        ORDER BY Aircraft
    </cfquery>

    <cfset count = 1>
    <cfset aircraftByOperator = arrayNew(2)>

    <cfloop query="queryByOperator">
        <cfset aircraftByOperator[count][1] = aircraftID>
        <cfset aircraftByOperator[count][2] = Aircraft>
        <cfset aircraftByOperator[count][3] = operatorID>
        <cfset aircraftByOperator[count][4] = Operator>
        <cfset aircraftByOperator[count][5] = country>
        <cfset count = count+1>
    </cfloop>

2. Outputting on page:

<cfloop from="1" to="#ArrayLen(aircraftByOperator)#" index="i">
    <cfoutput>

        #aircraftByOperator[i][2]#

    </cfoutput>
</cfloop>

[i][1], [i][3] and [i][5] are all IDs. "operatorID" is the one that will change depending on who operates the aircraft. I hope this helps explain what I am trying, and again, many thanks!

A: Dan Bracuk's comment "Does this mean you are pre-loading all your data into javascript? It might be more efficient to throw some ajax in there and just get what you need when you need it" ended up being the way to go for us. I would like to mark his comment as the answer, but am unable to see how to do that.
For others who may read this post, we

*

*Loaded all of the aircraft initially

*When a visitor filters by country and/or organization, a new query is sent via ajax

*I was having a hard time formatting the returned data, so I used jQuery's load() to format it and drop it in the proper place in the output panel.

As Dan said, it is very fast and much easier to work with, especially as our database continues to grow.
Thanks Dan!


text:
Q: Having trouble with a roll-up summary field that is trying to use a formula(date) child field What I want to happen:

*

*Each opportunity has a custom formula field, with a return type Date, called "CASL Implied Consent Expiry date".

If the OPP is Stage=Closed LOST, the Expiry date will be the OPP Created date +182 days.
If the Stage=Closed WON, the expiry date will equal Close Date +730 days.
If the Opp is still open the Expiry date will be empty/null.

*The parent account, will/should use a rollup summary field to find the MAX date of all OPP expiry dates.  (The date that is the most recent)

I've created a formula(date) field on the OPPORTUNITY object - here's the formula (it's producing the correct/expected results):
IF( ISPICKVAL(StageName, "Closed Won"),
    CloseDate + 730,
    IF( ISPICKVAL(StageName, "Closed Lost"),
        DATEVALUE(CreatedDate)+ 182,
        null)
 )

My trouble is that I can't select the CASL Expiry date field in the rollup summary field setup.
It's my understanding that I should be able to use the MAX/Min on date fields - so long as the formula field "does not contain cross-object field references or functions that automatically derive values on the fly, such as NOW or TODAY."
(reference https://help.salesforce.com/HTViewHelpDoc?id=fields_about_roll_up_summary_fields.htm)
I might be misunderstanding the meaning of "automatically derive values on the fly, such as NOW or TODAY" but I don't think my date formula is doing that...
If it is, and the rollup summary is out of the question, what would be the next recommendation?
Thanks in advance.

A: From the reference you cited:

Make sure that the filter for your roll-up summary does not encounter a formula field that results in "#Error!". If your filter criteria uses a formula field that results in an error, no matches are returned for that filter criterion. For example, if your roll-up summary filter is "Formula Field equals 10" and two records contain errors while one contains the value "10" in that field, your summary only includes the record with the value "10."

Your formula will produce an error any time IF(ISPICKVAL(StageName, "Closed Won") or IF( ISPICKVAL(StageName, "Closed Lost") evaluates to false. That's why SF won't allow you to use your formula field.