问:
Firebase Database Keys
This should be a simple answer for anyone with some basic database/firebase experience. I have looked throughout their documentation and cannot find an easy explanation of what I am looking for.

I am new to databases in general so if there is already a good post on here about my question, or somewhere else on the internet feel free to tell me.

My Issue

Lets just say I have an input field in my React app, and every time a user enters a value into it and presses enter, I would like for the data to get pushed to a certain part of my database, lets call that area, "tasks". I am actually able to do that, and can see the information created inside my tasks directory in real time every time I press enter. I can see that firebase enters it into the tasks directory with its own uniquely generated "key".

However, my problem is that I have another component where I would like to output all of the children from "tasks" to the screen. I think my issue is that I am not understanding the basic principles of how the data is stored and how to manipulate it(The official documentation from firebase was not much of a help).

My attempt at the aforementioned
In my component, I was attempting to use the javascript map function, that just iterates through the items in tasks, and outputs each one into its own div. The problem here is that the unique key identifier does not work with the array.map function. However, say I manually enter a list of tasks into the database, and give them my own key starting from 0, then ascending sequentially(0, 1, 2, 3, 4, 5)

The small picture below shows you what I mean. I manually entered those tasks, and can map through them, but if they have the randomly generated key from firebase, it does not work. Any help is greatly appreciated.

答:
You want to use .set() in order to specify your ID's. That said, the randomly generated ID's used by Firebase are used for an important purpose (timestamping), so overwrite those at your own discretion.

Try this if you're set on assigning the ID's manually:

```<code>var tasksRef = ref.child("tasks")
tasksRef.child('0').set({'hello world')}
</code>```

Title: Firebase Database Keys

Body:
You want to use .set() in order to specify your ID's. That said, the randomly generated ID's used by Firebase are used for an important purpose (timestamping), so overwrite those at your own discretion.

Try this if you're set on assigning the ID's manually:

var tasksRef = ref.child("tasks")
tasksRef.child('0').set({'hello world')}


来源: stackexchange

问:
Configure HA for WILDLFY 10 artemis
We have two wildlfy 10.1.0 server with the activeMq (Artemis) running. We want the two artemis to be in sync with messages. And if one is down, other one should start receiving and sending messages. There is lack of documentation in google as well as artemis is new.

Also, keeping both as active for loadbalancing., is it possible?

答:
I am assuming that you are using the internal instance of Artemis in wildfly. In the Wildfly Quickstarts, there is a good demo on Messaging Clustering. This will also work for 10.1.  It shows how to configure using Standalone-HA or Domain

https://github.com/wildfly/quickstart/tree/11.x/messaging-clustering.

ContentLicense: CC BY-SA 3.0

Title: Configure HA for WILDLFY 10 artemis


问:
ASP.net MVC returning JSONP
I am looking to return some JSON across domains and I understand that the way to do this is through JSONP rather than pure JSON.

I am using ASP.net MVC so I was thinking about just extending the JsonResult type and then extending the Controller so that it also implemented a Jsonp method.

Is this the best way to go about it or is there a built-in ActionResult that might be better?

Solution:  I went ahead and did that.  Just for reference sake I added a new result:

```<code>public class JsonpResult : System.Web.Mvc.JsonResult
{
    public override void ExecuteResult(ControllerContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException("context");
        }

        HttpResponseBase response = context.HttpContext.Response;

        if (!String.IsNullOrEmpty(ContentType))
        {
            response.ContentType = ContentType;
        }
        else
        {
            response.ContentType = "application/javascript";
        }
        if (ContentEncoding != null)
        {
            response.ContentEncoding = ContentEncoding;
        }
        if (Data != null)
        {
            // The JavaScriptSerializer type was marked as obsolete prior to .NET Framework 3.5 SP1
        #pragma warning disable 0618
            HttpRequestBase request = context.HttpContext.Request;

            JavaScriptSerializer serializer = new JavaScriptSerializer();
            response.Write(request.Params["jsoncallback"] + "(" + serializer.Serialize(Data) + ")");
        #pragma warning restore 0618
        }
    }
}
</code>```

and also a couple of methods to a superclass of all my controllers:

```<code>protected internal JsonpResult Jsonp(object data)
{
    return Jsonp(data, null /* contentType */);
}

protected internal JsonpResult Jsonp(object data, string contentType)
{
    return Jsonp(data, contentType, null);
}

protected internal virtual JsonpResult Jsonp(object data, string contentType, Encoding contentEncoding)
{
    return new JsonpResult
    {
        Data = data,
        ContentType = contentType,
        ContentEncoding = contentEncoding
    };
}

</code>```

Works like a charm.

答:
Rather than subclassing my controllers with Jsonp() methods, I went the extension method route as it feels a touch cleaner to me. The nice thing about the JsonpResult is that you can test it exactly the same way you would a JsonResult.

I did:

```<code>public static class JsonResultExtensions
{
    public static JsonpResult ToJsonp(this JsonResult json)
    {
        return new JsonpResult { ContentEncoding = json.ContentEncoding, ContentType = json.ContentType, Data = json.Data, JsonRequestBehavior = json.JsonRequestBehavior};
    }
}
</code>```

This way you don't have to worry about creating all the different Jsonp() overloads, just convert your JsonResult to a Jsonp one.

ContentLicense: CC BY-SA 4.0

Title: ASP.net MVC returning JSONP

Body:
I am looking to return some JSON across domains and I understand that the way to do this is through JSONP rather than pure JSON.

I am using ASP.net MVC so I was thinking about just extending the JsonResult type and then extending the Controller so that it also implemented a Jsonp method.

Is this the best way to go about it or is there a built-in ActionResult that might be better?

Solution:  I went ahead and did that.  Just for reference sake I added a new result:

public class JsonpResult : System.Web.Mvc.JsonResult
{
    public override void ExecuteResult(ControllerContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException("context");
        }

        HttpResponseBase response = context.HttpContext.Response;

        if (!String.IsNullOrEmpty(ContentType))
        {
            response.ContentType = ContentType;
        }
        else
        {
            response.ContentType = "application/javascript";
        }
        if (ContentEncoding != null)
        {
            response.ContentEncoding = ContentEncoding;
        }
        if (Data != null)
        {
            // The JavaScriptSerializer type was marked as obsolete prior to .NET Framework 3.5 SP1
        #pragma warning disable 0618
            HttpRequestBase request = context.HttpContext.Request;

            JavaScriptSerializer serializer = new JavaScriptSerializer();
            response.Write(request.Params["jsoncallback"] + "(" + serializer.Serialize(Data) + ")");
        #pragma warning restore 0618
        }
    }
}

and also a couple of methods to a superclass of all my controllers:

protected internal JsonpResult Jsonp(object data)
{
    return Jsonp(data, null /* contentType */);
}

protected internal JsonpResult Jsonp(object data, string contentType)
{
    return Jsonp(data, contentType, null);
}

protected internal virtual JsonpResult Jsonp(object data, string contentType, Encoding contentEncoding)
{
    return new JsonpResult
    {
        Data = data,
        ContentType = contentType,
        ContentEncoding = contentEncoding
    };
}

Works like a charm.

Body:
Rather than subclassing my controllers with Jsonp() methods, I went the extension method route as it feels a touch cleaner to me. The nice thing about the JsonpResult is that you can test it exactly the same way you would a JsonResult.

I did:

public static class JsonResultExtensions
{
    public static JsonpResult ToJsonp(this JsonResult json)
    {
        return new JsonpResult { ContentEncoding = json.ContentEncoding, ContentType = json.ContentType, Data = json.Data, JsonRequestBehavior = json.JsonRequestBehavior};
    }
}

This way you don't have to worry about creating all the different Jsonp() overloads, just convert your JsonResult to a Jsonp one.

ContentLicense: CC BY-SA 2.5


问:
Posting Collection to OData Controller not returning nested collection property to client
I have the following Model class defined:

```<code>public class LinePostModel
    {
        [Key]
        public int OrderId { get; set; }
        public IList<OrderLine> OrderLines { get; set; }
    }
</code>```

and this method on my OData Controller:

```<code>public async Task<IHttpActionResult> Post(LinePostModel model)
{
  //validae model and its OrderLines collection and save to repo.

  return Created(model);
}
</code>```

The server receives the model object correctly, and processes every find.  My problem is that the RESPONSE that is returned to the client only contains the primitive OrderId property, and does NOT contain the collection property OrderLines.

How can I fix this so that the entire complex object is returned to the client?

EDIT: added sample json:

Here is what the client posts:

```<code>{
      orderId:4,
      orderLines: [
        {
            lineType: "S",
            orderQty: 10,
            priceCode: "D",
            stockCode: "62.C6W026A.050",
            warehouse: "GS",
            orderId:4
        },
        {
            lineType: "S",
            orderQty: 20,
            priceCode: "D",
            stockCode: "62.C6W026A.060",
            warehouse: "GS",
            orderId:4
        }
      ]
}
</code>```

and here is what the client receives back from the server:

```<code>{
  "@odata.context": "http://localhost:4095/$metadata#OrderLines/$entity",
  "orderId": 4
}
</code>```

I have tried changing the server to return Ok(model) instead of Created(model), but it makes no difference.

A breakpoint on the return Created(model) line in the controller method shows that at that point the model object definitely contains the collection of OrderLines.

答:
I think you should try this answer response and see if this helps.
https://stackoverflow.com/a/16472870/1233465

You can try adding the accept header in your request and see if that helps. Please share your results and findings.

Body:
I have the following Model class defined:

public class LinePostModel
    {
        [Key]
        public int OrderId { get; set; }
        public IList<OrderLine> OrderLines { get; set; }
    }

and this method on my OData Controller:

public async Task<IHttpActionResult> Post(LinePostModel model)
{
  //validae model and its OrderLines collection and save to repo.

  return Created(model);
}

The server receives the model object correctly, and processes every find.  My problem is that the RESPONSE that is returned to the client only contains the primitive OrderId property, and does NOT contain the collection property OrderLines.

How can I fix this so that the entire complex object is returned to the client?

EDIT: added sample json:

Here is what the client posts:

{
      orderId:4,
      orderLines: [
        {
            lineType: "S",
            orderQty: 10,
            priceCode: "D",
            stockCode: "62.C6W026A.050",
            warehouse: "GS",
            orderId:4
        },
        {
            lineType: "S",
            orderQty: 20,
            priceCode: "D",
            stockCode: "62.C6W026A.060",
            warehouse: "GS",
            orderId:4
        }
      ]
}

and here is what the client receives back from the server:

{
  "@odata.context": "http://localhost:4095/$metadata#OrderLines/$entity",
  "orderId": 4
}

I have tried changing the server to return Ok(model) instead of Created(model), but it makes no difference.

A breakpoint on the return Created(model) line in the controller method shows that at that point the model object definitely contains the collection of OrderLines.


问:
App which displays List does not work
I try to make an App with button which after the push will display all elements from list in editText.
But I have a problem, currently after I push the button I see only "second" in editText

In my opinion I need a tips from you about how to do it.  Maybe I shouldn't use a loop ?

```<code>public class MainActivity extends AppCompatActivity {

    private Button button;
    private EditText editText;
    private ArrayList<String> list = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button = (Button) findViewById(R.id.button);
        editText = (EditText) findViewById(R.id.editText);

        list.add(0, "first");
        list.add(1, "second");

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                for (String abc: list){

                    editText.setText(abc);

                }

            }
        });
    }

}
</code>```

____ edit

```<code>public class MainActivity extends AppCompatActivity {

    private Button button;
    private EditText editText;
    private ArrayList<String> list = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button = (Button) findViewById(R.id.button);
        editText = (EditText) findViewById(R.id.editText);

        list.add(0, "first");
        list.add(1, "second");
        list.add(2, "3");
        list.add(3, "4");
        list.add(4, "5");

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String final_text = "";

                for (String abc: list){

                    final_text = final_text + "\n" + abc;

                }

                editText.setText(final_text);

            }
        });
    }

}
</code>```

enter image description here

答:
You are overwriting the text in editText. Accumulate the strings from the list and do a setText outside the loop:-

```<code>@Override
public void onClick(View v) {
  String final_text ="";
  for (String abc: list){
   final_text = final_text +"\n" + abc;
  }
  editText.setText(final_text);
}
</code>```

Title: App which displays List does not work

Body:
I try to make an App with button which after the push will display all elements from list in editText.
But I have a problem, currently after I push the button I see only "second" in editText

In my opinion I need a tips from you about how to do it.  Maybe I shouldn't use a loop ?

public class MainActivity extends AppCompatActivity {

    private Button button;
    private EditText editText;
    private ArrayList<String> list = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button = (Button) findViewById(R.id.button);
        editText = (EditText) findViewById(R.id.editText);

        list.add(0, "first");
        list.add(1, "second");

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                for (String abc: list){

                    editText.setText(abc);

                }

            }
        });
    }

}

____ edit

public class MainActivity extends AppCompatActivity {

    private Button button;
    private EditText editText;
    private ArrayList<String> list = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button = (Button) findViewById(R.id.button);
        editText = (EditText) findViewById(R.id.editText);

        list.add(0, "first");
        list.add(1, "second");
        list.add(2, "3");
        list.add(3, "4");
        list.add(4, "5");

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String final_text = "";

                for (String abc: list){

                    final_text = final_text + "\n" + abc;

                }

                editText.setText(final_text);

            }
        });
    }

}

enter image description here

Body:
You are overwriting the text in editText. Accumulate the strings from the list and do a setText outside the loop:-

@Override
public void onClick(View v) {
  String final_text ="";
  for (String abc: list){
   final_text = final_text +"\n" + abc;
  }
  editText.setText(final_text);
}


问:
localhost refused to connect Error in visual studio
I have copied my solution file from another system and tried to run it on my machine:
For this, I have gone to the project folder and deleted the previous solution file and copied the new one.

Now, it started giving me error. connection refused etc. So, I got one solution from here: How to solve ERR_CONNECTION_REFUSED when trying to connect to localhost running IISExpress - Error 502 (Cannot debug from Visual Studio)?

According to it, I changed the port number from 1049 to 1052. It loaded and one of the pages gets loaded.
But when I entered the desired login credentials then it redirected to the older port again, like this:

```<code>http://localhost:1049/Home/SearchFlight
</code>```

and the error is:

```<code> This site can’t be reached

 localhost refused to connect.
 Search Google for localhost 1049 Home Search Flight
 ERR_CONNECTION_REFUSED
</code>```

Now, I don't know what to do from here. I have changed the port number to 1052 but still its pointing to 1049. What should i do now?

答:
I solved a similar problem by listing bound IP addresses in a cmd window running as admin:

```<code>netsh http show iplisten
</code>```

Then, one by one, blowing them all away:

```<code>netsh http delete iplisten ipaddress=127.0.0.200
netsh http delete iplisten ipaddress=127.0.0.2
...
</code>```

Body:
I have copied my solution file from another system and tried to run it on my machine:
For this, I have gone to the project folder and deleted the previous solution file and copied the new one.

Now, it started giving me error. connection refused etc. So, I got one solution from here: How to solve ERR_CONNECTION_REFUSED when trying to connect to localhost running IISExpress - Error 502 (Cannot debug from Visual Studio)?

According to it, I changed the port number from 1049 to 1052. It loaded and one of the pages gets loaded.
But when I entered the desired login credentials then it redirected to the older port again, like this:

http://localhost:1049/Home/SearchFlight

and the error is:

 This site can’t be reached

 localhost refused to connect.
 Search Google for localhost 1049 Home Search Flight
 ERR_CONNECTION_REFUSED

Now, I don't know what to do from here. I have changed the port number to 1052 but still its pointing to 1049. What should i do now?

Body:
I solved a similar problem by listing bound IP addresses in a cmd window running as admin:

netsh http show iplisten

Then, one by one, blowing them all away:

netsh http delete iplisten ipaddress=127.0.0.200
netsh http delete iplisten ipaddress=127.0.0.2
...


问:
MatrixTransform inside MatrixTransform behavior is not what I was expecting
I currently have a Border that is bound to a MatrixTransform.  When scrolling the mouse wheel, it will basically scale the MatrixTransform.  Inside of the border, I have a Rectangle that is centered horizontally and vertically.  At the time when the Border transform is scaled, I set the transform of the Rectangle to be equal to the Inverse of the Border.  The ides is to keep the rectangle the same size and in the center.  My current solution will keep the rectangle the same size, but it gradually moves away from center as you keep zooming. It seems as if the Rectangle transform isn't aware of the Border transform, does that make sense?

Here's a couple images, the first is initial, the second is after zooming a couple times (notice the rectangle stayed the same size, but it's no longer centered).

The basic idea that I'm trying to solve is like a Google maps application, when you zoom in, the city name size stays the same.

Here's all of my code, you should be able to pull this in and run it if you'd like:

MainPage.xaml

```<code><UserControl x:Class="InvertedZoomTest.MainPage"
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"
xmlns:local="clr-namespace:InvertedZoomTest"
mc:Ignorable="d">

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

<Border BorderBrush="Pink" Background="Gray" VerticalAlignment="Center" HorizontalAlignment="Center"  BorderThickness="2" MouseWheel="Border_MouseWheel" Height="100" Width="100" RenderTransform="{Binding MainTransform}">
    <Rectangle x:Name="rectangle" Canvas.Top="43" Canvas.Left="43" Fill="Red" Height="10" Width="10" HorizontalAlignment="Center" VerticalAlignment="Center" RenderTransform="{Binding TextTransform}"/>
</Border>
</code>```

MainPage.xaml.cs

```<code>public partial class MainPage : UserControl
{
    public MainPage()
    {
        InitializeComponent();
    }

    private MainPage_ViewModel viewModel
    {
        get
        {
            return this.DataContext as MainPage_ViewModel;
        }
    }

    private void Border_MouseWheel(object sender, MouseWheelEventArgs e)
    {
        if (e.Delta > 0)
        {
            this.viewModel.ZoomRatio += .1;
        }
        else
        {
            this.viewModel.ZoomRatio -= .1;
        }

        this.viewModel.UpdateTextScale();
    }
}
</code>```

MainPage_ViewModel.cs

```<code>public class MainPage_ViewModel : INotifyPropertyChanged
{
    public MatrixTransform TextTransform
    {
        get { return _textTransform; }
        set
        {
            if (value != _textTransform)
            {
                _textTransform = value;
                OnPropertyChanged("TextTransform");
            }
        }
    }
    private MatrixTransform _textTransform = new MatrixTransform();

    public MatrixTransform MainTransform
    {
        get
        {
            return _mainTransform;
        }
        set
        {
            if (value != _mainTransform)
            {
                _mainTransform = value;
                OnPropertyChanged("MainTransform");
            }
        }
    }
    private MatrixTransform _mainTransform = new MatrixTransform();

    public void UpdateTextScale()
    {
        var scaleX = (double)(ZoomRatio);
        var scaleY = (double)(ZoomRatio);

        Matrix updatedMainTransformMatrix = new Matrix(scaleX, 0, 0, scaleY, 0, 0);
        this.MainTransform.Matrix = updatedMainTransformMatrix;
        OnPropertyChanged("MainTransform");

        this.TextTransform = MainTransform.Inverse as MatrixTransform;
        OnPropertyChanged("TextTransform");
    }

    public double ZoomRatio
    {
        get
        {
            return zoomRatio;
        }
        set
        {
            zoomRatio = value;
            OnPropertyChanged("ZoomRatio");

            UpdateTextScale();
        }
    }
    private double zoomRatio = 1;

    public event PropertyChangedEventHandler PropertyChanged;

    public void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
</code>```

Am I doing something wrong that would make this rectangle move from the center?  Any help would be greatly appreciated!

UPDATE
Out of curiousity, I wrapped a border around the rectangle and did an element to element binding on the width & height.  You will notice in the image below that the transform on the rectangle seems to have an origin at the top left, does this make sense?

New XAML:

```<code><Border BorderBrush="Pink" Background="Gray" VerticalAlignment="Center" HorizontalAlignment="Center"  BorderThickness="2" MouseWheel="Border_MouseWheel" Height="100" Width="100" RenderTransform="{Binding MainTransform}">
    <Border BorderBrush="Green" BorderThickness="1" Height="{Binding ElementName=rectangle, Path=Height}" Width="{Binding ElementName=rectangle, Path=Width}">
        <Rectangle x:Name="rectangle" Canvas.Top="43" Canvas.Left="43" Fill="Red" Height="10" Width="10" HorizontalAlignment="Center" VerticalAlignment="Center" RenderTransform="{Binding TextTransform}"/>
    </Border>
</Border>
</code>```

Resulting Image:

答:
I figured this out.  I just needed to set the RenderTransformOrigin of my rectangle to the center.

```<code><Border BorderBrush="Pink" Background="Gray" VerticalAlignment="Center" HorizontalAlignment="Center"  BorderThickness="2" MouseWheel="Border_MouseWheel" Height="100" Width="100" RenderTransform="{Binding MainTransform}">
<Border BorderBrush="Green" BorderThickness="1" Height="{Binding ElementName=rectangle, Path=Height}" Width="{Binding ElementName=rectangle, Path=Width}">
    <Rectangle x:Name="rectangle" Canvas.Top="43" Canvas.Left="43" Fill="Red" Height="10" Width="10" HorizontalAlignment="Center" VerticalAlignment="Center" RenderTransform="{Binding TextTransform}" RenderTransformOrigin=".5,.5"/>
</Border>
</code>```

Body:
I currently have a Border that is bound to a MatrixTransform.  When scrolling the mouse wheel, it will basically scale the MatrixTransform.  Inside of the border, I have a Rectangle that is centered horizontally and vertically.  At the time when the Border transform is scaled, I set the transform of the Rectangle to be equal to the Inverse of the Border.  The ides is to keep the rectangle the same size and in the center.  My current solution will keep the rectangle the same size, but it gradually moves away from center as you keep zooming. It seems as if the Rectangle transform isn't aware of the Border transform, does that make sense?

Here's a couple images, the first is initial, the second is after zooming a couple times (notice the rectangle stayed the same size, but it's no longer centered).

The basic idea that I'm trying to solve is like a Google maps application, when you zoom in, the city name size stays the same.

Here's all of my code, you should be able to pull this in and run it if you'd like:

MainPage.xaml

<UserControl x:Class="InvertedZoomTest.MainPage"
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"
xmlns:local="clr-namespace:InvertedZoomTest"
mc:Ignorable="d">

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

<Border BorderBrush="Pink" Background="Gray" VerticalAlignment="Center" HorizontalAlignment="Center"  BorderThickness="2" MouseWheel="Border_MouseWheel" Height="100" Width="100" RenderTransform="{Binding MainTransform}">
    <Rectangle x:Name="rectangle" Canvas.Top="43" Canvas.Left="43" Fill="Red" Height="10" Width="10" HorizontalAlignment="Center" VerticalAlignment="Center" RenderTransform="{Binding TextTransform}"/>
</Border>

MainPage.xaml.cs

public partial class MainPage : UserControl
{
    public MainPage()
    {
        InitializeComponent();
    }

    private MainPage_ViewModel viewModel
    {
        get
        {
            return this.DataContext as MainPage_ViewModel;
        }
    }

    private void Border_MouseWheel(object sender, MouseWheelEventArgs e)
    {
        if (e.Delta > 0)
        {
            this.viewModel.ZoomRatio += .1;
        }
        else
        {
            this.viewModel.ZoomRatio -= .1;
        }

        this.viewModel.UpdateTextScale();
    }
}

MainPage_ViewModel.cs

public class MainPage_ViewModel : INotifyPropertyChanged
{
    public MatrixTransform TextTransform
    {
        get { return _textTransform; }
        set
        {
            if (value != _textTransform)
            {
                _textTransform = value;
                OnPropertyChanged("TextTransform");
            }
        }
    }
    private MatrixTransform _textTransform = new MatrixTransform();

    public MatrixTransform MainTransform
    {
        get
        {
            return _mainTransform;
        }
        set
        {
            if (value != _mainTransform)
            {
                _mainTransform = value;
                OnPropertyChanged("MainTransform");
            }
        }
    }
    private MatrixTransform _mainTransform = new MatrixTransform();

    public void UpdateTextScale()
    {
        var scaleX = (double)(ZoomRatio);
        var scaleY = (double)(ZoomRatio);

        Matrix updatedMainTransformMatrix = new Matrix(scaleX, 0, 0, scaleY, 0, 0);
        this.MainTransform.Matrix = updatedMainTransformMatrix;
        OnPropertyChanged("MainTransform");

        this.TextTransform = MainTransform.Inverse as MatrixTransform;
        OnPropertyChanged("TextTransform");
    }

    public double ZoomRatio
    {
        get
        {
            return zoomRatio;
        }
        set
        {
            zoomRatio = value;
            OnPropertyChanged("ZoomRatio");

            UpdateTextScale();
        }
    }
    private double zoomRatio = 1;

    public event PropertyChangedEventHandler PropertyChanged;

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

Am I doing something wrong that would make this rectangle move from the center?  Any help would be greatly appreciated!

UPDATE
Out of curiousity, I wrapped a border around the rectangle and did an element to element binding on the width & height.  You will notice in the image below that the transform on the rectangle seems to have an origin at the top left, does this make sense?

New XAML:

<Border BorderBrush="Pink" Background="Gray" VerticalAlignment="Center" HorizontalAlignment="Center"  BorderThickness="2" MouseWheel="Border_MouseWheel" Height="100" Width="100" RenderTransform="{Binding MainTransform}">
    <Border BorderBrush="Green" BorderThickness="1" Height="{Binding ElementName=rectangle, Path=Height}" Width="{Binding ElementName=rectangle, Path=Width}">
        <Rectangle x:Name="rectangle" Canvas.Top="43" Canvas.Left="43" Fill="Red" Height="10" Width="10" HorizontalAlignment="Center" VerticalAlignment="Center" RenderTransform="{Binding TextTransform}"/>
    </Border>
</Border>

Resulting Image:

Body:
I figured this out.  I just needed to set the RenderTransformOrigin of my rectangle to the center.

<Border BorderBrush="Pink" Background="Gray" VerticalAlignment="Center" HorizontalAlignment="Center"  BorderThickness="2" MouseWheel="Border_MouseWheel" Height="100" Width="100" RenderTransform="{Binding MainTransform}">
<Border BorderBrush="Green" BorderThickness="1" Height="{Binding ElementName=rectangle, Path=Height}" Width="{Binding ElementName=rectangle, Path=Width}">
    <Rectangle x:Name="rectangle" Canvas.Top="43" Canvas.Left="43" Fill="Red" Height="10" Width="10" HorizontalAlignment="Center" VerticalAlignment="Center" RenderTransform="{Binding TextTransform}" RenderTransformOrigin=".5,.5"/>
</Border>


问:
Recursively checking for odd or even
In this code:

```<code>def is_even(x):
  if x == 0:
    return True
  else:
    return is_odd(x-1)

def is_odd(x):
  return not is_even(x)

print(is_even(2))
print(is_odd(2))
</code>```

I keep going through this in my head and wondering how it's working.  It seems to me that eventually x in is_even(x) will return True every time.  However, when I run the code, it works perfectly fine and returns True and False appropriately.  Can someone explain how that's happening?

I understand the basic concept of recursion and fully understand how the famous factorial example works.  However, this one is hard for me to wrap my head around.

Feeling inept right now...

答:
Like in most cases it might be helpful to include simply prints to follow the execution:

```<code>def is_even(x):
    print('check if {} is even'.format(x))
    if x == 0:
        return True
    else:
        return is_odd(x-1)

def is_odd(x):
    print('check if {} is odd'.format(x))
    return not is_even(x)
</code>```

Then in your cases:

```<code>>>> print(is_even(2))
check if 2 is even
check if 1 is odd
check if 1 is even
check if 0 is odd
check if 0 is even
True

>>> print(is_odd(2))
check if 2 is odd
check if 2 is even
check if 1 is odd
check if 1 is even
check if 0 is odd
check if 0 is even
False
</code>```

So basically it decrements the number until it's 0. The point is just how many nots have been accumulated in the is_odd calls. If it's an even number of nots then the result will be True, otherwise False.

Title: Recursively checking for odd or even

Body:
In this code:

def is_even(x):
  if x == 0:
    return True
  else:
    return is_odd(x-1)

def is_odd(x):
  return not is_even(x)

print(is_even(2))
print(is_odd(2))

I keep going through this in my head and wondering how it's working.  It seems to me that eventually x in is_even(x) will return True every time.  However, when I run the code, it works perfectly fine and returns True and False appropriately.  Can someone explain how that's happening?

I understand the basic concept of recursion and fully understand how the famous factorial example works.  However, this one is hard for me to wrap my head around.

Feeling inept right now...

Body:
Like in most cases it might be helpful to include simply prints to follow the execution:

def is_even(x):
    print('check if {} is even'.format(x))
    if x == 0:
        return True
    else:
        return is_odd(x-1)

def is_odd(x):
    print('check if {} is odd'.format(x))
    return not is_even(x)

Then in your cases:

>>> print(is_even(2))
check if 2 is even
check if 1 is odd
check if 1 is even
check if 0 is odd
check if 0 is even
True

>>> print(is_odd(2))
check if 2 is odd
check if 2 is even
check if 1 is odd
check if 1 is even
check if 0 is odd
check if 0 is even
False

So basically it decrements the number until it's 0. The point is just how many nots have been accumulated in the is_odd calls. If it's an even number of nots then the result will be True, otherwise False.


问:
In R only keep values that appear for at least 3 years, at least 10 times per year
Please see a general sample of my dataset below. I only want to keep count data from IDs that appear for at least 3 years, with at least 10 appearances during each of those years. So, here, I only want the data from ID 'a', and I want to remove the data with the ID of 'b' and 'c.'

I have some basic/general knowledge of r, python, and excel. Any way to do this using any of those three languages would be great. I guess r would be preferred. Thank you.

```<code>ID  year    count
a   2001    2
b   2001    3
a   2001    2
a   2001    1
a   2001    4
a   2001    0
a   2001    1
a   2001    3
a   2001    2
b   2001    3
b   2001    4
a   2001    5
b   2001    2
c   2001    3
a   2001    5
a   2001    1
c   2001    1
c   2002    2
a   2002    1
b   2002    2
c   2002    3
a   2002    2
a   2002    1
a   2002    3
a   2002    4
a   2002    3
a   2002    2
b   2002    4
b   2002    2
a   2002    1
b   2002    1
c   2002    2
a   2002    3
a   2002    4
a   2002    5
c   2002    2
a   2003    2
a   2003    1
a   2003    2
a   2003    4
c   2003    3
a   2003    2
a   2003    1
b   2003    3
a   2003    5
a   2003    3
a   2003    2
a   2003    1
a   2003    3
a   2003    2
c   2003    2
b   2003    2
b   2003    1
b   2003    4
c   2003    3
</code>```

答:
In R you could use

```<code>GoodIDs = names(which(rowSums(table(df$ID, df$year) >= 10) >=3))
df[df$ID %in% GoodIDs,]
</code>```

The gory Details

Just making a table of how many times each year-id combination occurred helps a lot.

```<code>table(df$ID, df$year)
    2001 2002 2003
  a   11   11   12
  b    4    4    4
  c    2    4    3
</code>```

Now we see the answer (only id=a is wanted),  but we want to push that through to get the full answer.  Next step, test which entries in the table are at least 10.

```<code>table(df$ID, df$year) >= 10
     2001  2002  2003
  a  TRUE  TRUE  TRUE
  b FALSE FALSE FALSE
  c FALSE FALSE FALSE
</code>```

Now we want to count how many years had true for each id. Using the fact that TRUE will be treated as 1 and FALSE will be treated as 0, we can just add across the rows.

```<code>rowSums(table(df$ID, df$year) >= 10)
a b c
3 0 0
</code>```

Now we want to test which of these was at least 3

```<code>which(rowSums(table(df$ID, df$year) >= 10) >=3)
a
1
</code>```

Now get which ID's were selected

```<code>names(which(rowSums(table(df$ID, df$year) >= 10) >=3))
[1] "a"
</code>```

We store that in GoodIDs and then extract all of the rows with the selected IDs.

```<code>df[df$ID %in% GoodIDs,]
<output omitted>
</code>```

Body:
Please see a general sample of my dataset below. I only want to keep count data from IDs that appear for at least 3 years, with at least 10 appearances during each of those years. So, here, I only want the data from ID 'a', and I want to remove the data with the ID of 'b' and 'c.'

I have some basic/general knowledge of r, python, and excel. Any way to do this using any of those three languages would be great. I guess r would be preferred. Thank you.

ID  year    count
a   2001    2
b   2001    3
a   2001    2
a   2001    1
a   2001    4
a   2001    0
a   2001    1
a   2001    3
a   2001    2
b   2001    3
b   2001    4
a   2001    5
b   2001    2
c   2001    3
a   2001    5
a   2001    1
c   2001    1
c   2002    2
a   2002    1
b   2002    2
c   2002    3
a   2002    2
a   2002    1
a   2002    3
a   2002    4
a   2002    3
a   2002    2
b   2002    4
b   2002    2
a   2002    1
b   2002    1
c   2002    2
a   2002    3
a   2002    4
a   2002    5
c   2002    2
a   2003    2
a   2003    1
a   2003    2
a   2003    4
c   2003    3
a   2003    2
a   2003    1
b   2003    3
a   2003    5
a   2003    3
a   2003    2
a   2003    1
a   2003    3
a   2003    2
c   2003    2
b   2003    2
b   2003    1
b   2003    4
c   2003    3

Body:
In R you could use

GoodIDs = names(which(rowSums(table(df$ID, df$year) >= 10) >=3))
df[df$ID %in% GoodIDs,]

The gory Details

Just making a table of how many times each year-id combination occurred helps a lot.

table(df$ID, df$year)
    2001 2002 2003
  a   11   11   12
  b    4    4    4
  c    2    4    3

Now we see the answer (only id=a is wanted),  but we want to push that through to get the full answer.  Next step, test which entries in the table are at least 10.

table(df$ID, df$year) >= 10
     2001  2002  2003
  a  TRUE  TRUE  TRUE
  b FALSE FALSE FALSE
  c FALSE FALSE FALSE

Now we want to count how many years had true for each id. Using the fact that TRUE will be treated as 1 and FALSE will be treated as 0, we can just add across the rows.

rowSums(table(df$ID, df$year) >= 10)
a b c
3 0 0

Now we want to test which of these was at least 3

which(rowSums(table(df$ID, df$year) >= 10) >=3)
a
1

Now get which ID's were selected

names(which(rowSums(table(df$ID, df$year) >= 10) >=3))
[1] "a"

We store that in GoodIDs and then extract all of the rows with the selected IDs.

df[df$ID %in% GoodIDs,]
<output omitted>


答:
That's true; the recursion is supposed to end inside is_even.

And when that will happen, you'll know that the number you have is 0.

Now lets go backwards. This final state will be achieved by two cases - direct call to is_even(0) or a call from is_odd(0). In the first case - the result is all good. In the second - the result will be returned to the is_odd function, negated, and therefore will be falsy - giving a correct result.

Now, here the missing piece comes - the recursion: in order to reach this state, we need to decrease the argument each time, passing it through the opposite function - and that's exactly what we get with return is_odd(x-1).

Note: eventually this recursion leads to a chain of negations of the value True returned by the is_even. This chain is of length x where x is your number, and therefore odd or even in correspondence.

Therefore, the following code will do the same (lacking the is_odd nice side effect):

```<code>def is_even (x):
    res = True
    while x:
        res = not res
        x -= 1
    return res
</code>```

Title: Recursively checking for odd or even

Body:
That's true; the recursion is supposed to end inside is_even.

And when that will happen, you'll know that the number you have is 0.

Now lets go backwards. This final state will be achieved by two cases - direct call to is_even(0) or a call from is_odd(0). In the first case - the result is all good. In the second - the result will be returned to the is_odd function, negated, and therefore will be falsy - giving a correct result.

Now, here the missing piece comes - the recursion: in order to reach this state, we need to decrease the argument each time, passing it through the opposite function - and that's exactly what we get with return is_odd(x-1).

Note: eventually this recursion leads to a chain of negations of the value True returned by the is_even. This chain is of length x where x is your number, and therefore odd or even in correspondence.

Therefore, the following code will do the same (lacking the is_odd nice side effect):

def is_even (x):
    res = True
    while x:
        res = not res
        x -= 1
    return res


问:
Dropdown trigger change function to fetch dates to disable in datetimepicker
I have a dropdown of staff names and  StaffId. This is wired to an appointment business logic. I am trying to trigger a select change so that setting dates stored in database will be made unavailable in the connected jquery datetimepicker.  I have assembled the code below which seems not working. Could anyone point me to the right direction. Thanks</p>

```<code><script type="text/javascript">
        $(document).ready(function () {
            getdates();
        });

        var unavailableDates;
        $(document).ready( function getdates() {

            $("#StaffId").change(function (e) {
                $this = $(e.target);
                    $.ajax({
                        type: "POST",
                        url: "/Appointment/GetOffdays",
                        data: { StaffId: $this.val()  },
                        //contentType: "application/json"
                        success: function (data) {
                            debugger;
                            unavailableDates = data;

                            $(".jqueryui-marker-datepicker").datepicker({
                                dateFormat: "dd/M/yy",
                                changeMonth: true,
                                changeYear: false,
                                yearRange: "-1:+0",
                                //beforeShowDay: $.datepicker.noWeekends,
                                minDate: new Date(@(ViewBag.year+","+ViewBag.month+","+ViewBag.day)),
                                maxDate: new Date(@(ViewBag.eyear+","+ViewBag.emonth+","+ViewBag.eday)),

                                beforeShowDay: function (date) {
                                    var dmy = date.getDate() + "-" + (date.getMonth() + 1) + "-" + date.getFullYear();
                                    debugger;
                                    if ($.inArray(dmy, unavailableDates) == -1) {
                                        return [true, ""];
                                    } else {
                                        return [false, "myclass", "Unavailable"];
                                    }
                                }
                                });
                            },
                             dataType: "json",
                            traditional: true,
                            })

                }

           )
            $('#StaffId').trigger('change');
        });
        </script>
</code>```

答:
To reduce the complexity of your code I stripped out the content of getdates and replaced it with a simple log(), which I will put below. If I execute this page as is, the anonymous function sent to $(document.ready() is invoked first, before the function getdates is even mentioned, causing the console to throw

jQuery.Deferred exception: getdates is not defined ReferenceError: getdates is not defined

According to this question

jQuery - multiple $(document).ready ...?

When multiple consecutive calls to $(document).ready are made, upon DOM ready each function will be called in the order they were set. Even if you reverse the order of the calls to ready, since the named function getDates is only named during the function call, it isn't callable by that name anywhere else. Edit: Also note that if the first function queued for documentready throws an exception, jquery will not invoke the next one. So if the anonymous function fails, the named one will be skipped entirely.

Bear with me as I have really not answered many questions on this site, and its possible I've gravely misunderstood your code. But I think what you're trying to do is define a function getDates and invoke it when the value of an HTML element called '#StaffId' is changed. To accomplish this, you only need one call to $(document).ready(), which either calls the function getdates, which has to be defined in its scope, or you could get rid of getdates entirely and call its contents anonymously.

```<code><script type="text/javascript">
    $(document).ready(function () {
        getdates();
    });

    var unavailableDates;
    //this function might as well be anonymous since getdates is not available anywhere else by that name.
    //The function it refers to is passed and executed on document ready, but the alias getdates goes away.
    $(document).ready( function getdates() {

        console.log("getting dates");
    });
</script>
</code>```

should be

```<code><script type="text/javascript">
    //if unavailableDates is not used outside this function, it probably shouldn't be in the global scope.
    var unavailableDates;
    function getDates(){
        //now getDates is available everywhere, by its name
        console.log("getting dates");
    };

    //or $(document).ready(getDates);
    $(getDates);
</script>
</code>```

or just

```<code><script type="text/javascript">
        $(function (){
            //no need for named getdates polluting global namespace if you only intend to call it once.

            //do whatever you want here
    });
</script>
</code>```

Body:
To reduce the complexity of your code I stripped out the content of getdates and replaced it with a simple log(), which I will put below. If I execute this page as is, the anonymous function sent to $(document.ready() is invoked first, before the function getdates is even mentioned, causing the console to throw

jQuery.Deferred exception: getdates is not defined ReferenceError: getdates is not defined

According to this question

jQuery - multiple $(document).ready ...?

When multiple consecutive calls to $(document).ready are made, upon DOM ready each function will be called in the order they were set. Even if you reverse the order of the calls to ready, since the named function getDates is only named during the function call, it isn't callable by that name anywhere else. Edit: Also note that if the first function queued for documentready throws an exception, jquery will not invoke the next one. So if the anonymous function fails, the named one will be skipped entirely.

Bear with me as I have really not answered many questions on this site, and its possible I've gravely misunderstood your code. But I think what you're trying to do is define a function getDates and invoke it when the value of an HTML element called '#StaffId' is changed. To accomplish this, you only need one call to $(document).ready(), which either calls the function getdates, which has to be defined in its scope, or you could get rid of getdates entirely and call its contents anonymously.

<script type="text/javascript">
    $(document).ready(function () {
        getdates();
    });

    var unavailableDates;
    //this function might as well be anonymous since getdates is not available anywhere else by that name.
    //The function it refers to is passed and executed on document ready, but the alias getdates goes away.
    $(document).ready( function getdates() {

        console.log("getting dates");
    });
</script>

should be

<script type="text/javascript">
    //if unavailableDates is not used outside this function, it probably shouldn't be in the global scope.
    var unavailableDates;
    function getDates(){
        //now getDates is available everywhere, by its name
        console.log("getting dates");
    };

    //or $(document).ready(getDates);
    $(getDates);
</script>

or just

<script type="text/javascript">
        $(function (){
            //no need for named getdates polluting global namespace if you only intend to call it once.

            //do whatever you want here
    });
</script>


问:
Testing Vue.js Component
I'd like to test a Vue.js component, and I'm failing at that. Simply put, I'm setting a component property, and I want to assert that it is set correctly. If that matters, the module is loaded with exports, and the JS is output using Webpack.</p>

```<code>// component
exports = module.exports = {};

module.exports = {
  data: function () {
    return {
      active: false
    };
  },
  methods: {
    'close': function () {
       console.log(this.active); // -> true
       this.active = false;
       console.log(this.active); // -> false
    }
  }
};

// component-test
var modal = require('../../resources/src/js/components/_component.js');
var assert = require('assert');

describe('close()', function () {
  beforeEach(function () {
    modal.data.active = true;
  });
  it('should set modal to inactive', function () {
    console.log(modal.data.active); // -> true
    modal.methods.close();
    console.log(modal.data.active); // -> true
    assert.equal(modal.data.active, false);
  });
});
</code>```

答: https://github.com/eddyerburgh/avoriaz is now the official testing library for Vue.js checkout the documentation on getting setup to make assertions on your components https://eddyerburgh.gitbooks.io/avoriaz/content/</p>

Title: Testing Vue.js Component

Body:
I'd like to test a Vue.js component, and I'm failing at that. Simply put, I'm setting a component property, and I want to assert that it is set correctly. If that matters, the module is loaded with exports, and the JS is output using Webpack.

// component
exports = module.exports = {};

module.exports = {
  data: function () {
    return {
      active: false
    };
  },
  methods: {
    'close': function () {
       console.log(this.active); // -> true
       this.active = false;
       console.log(this.active); // -> false
    }
  }
};

// component-test
var modal = require('../../resources/src/js/components/_component.js');
var assert = require('assert');

describe('close()', function () {
  beforeEach(function () {
    modal.data.active = true;
  });
  it('should set modal to inactive', function () {
    console.log(modal.data.active); // -> true
    modal.methods.close();
    console.log(modal.data.active); // -> true
    assert.equal(modal.data.active, false);
  });
});


问:
Login-AzureRmAccount Could not establish trust relationship for the SSL/TLS secure channel
I am trying to connect to Azure using Powershell. When I try the command Login-AzureRmAccount, I get a pop-up to enter my credentials. But, immediately after that I get an error:

```<code>Login-AzureRmAccount : Service returned error. Check InnerException for more details: The underlying connection was
closed: Could not establish trust relationship for the SSL/TLS secure channel.
At line:1 char:1
+ Login-AzureRmAccount
+ ~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : CloseError: (:) [Add-AzureRmAccount], AadAuthenticationFailedException
    + FullyQualifiedErrorId : Microsoft.Azure.Commands.Profile.AddAzureRMAccountCommand
</code>```

Can someone shed some light on this?

Update
The below inner exception is what I see:

'Microsoft.IdentityModel.Clients.ActiveDirectory.AdalServiceException:
  Service returned error. Check InnerException for more details --->
  System.Net.WebException: The underlying connection was closed: Could
  not establish trust relationship for the SSL/TLS secure channel. --->
  System.Security.Authentication.AuthenticationException: The remote
  certificate is invalid according to the validation procedure.    at
  System.Net.Security.SslState.StartSendAuthResetSignal(ProtocolToken
  message, AsyncProtocolRequest asyncRequest, Exception exception)    at
  System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32
  count, AsyncProtocolRequest asyncRequest)    at
  System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer,
  AsyncProtocolRequest asyncRequest)    at
  System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32
  count, AsyncProtocolRequest asyncRequest)    at
  System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer,
  AsyncProtocolRequest asyncRequest)    at
  System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32
  count, AsyncProtocolRequest asyncRequest)    at
  System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer,
  AsyncProtocolRequest asyncRequest)    at
  System.Net.Security.SslState.ForceAuthentication(Boolean receiveFirst,
  Byte[] buffer, AsyncProtocolRequest asyncRequest)    at
  System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult
  lazyResult)    at
  System.Threading.ExecutionContext.RunInternal(ExecutionContext
  executionContext, ContextCallback callback, Object state, Boolean
  preserveSyncCtx)    at
  System.Threading.ExecutionContext.Run(ExecutionContext
  executionContext, ContextCallback callback, Object state, Boolean
  preserveSyncCtx)    at
  System.Threading.ExecutionContext.Run(ExecutionContext
  executionContext, ContextCallback callback, Object state)    at
  System.Net.TlsStream.ProcessAuthentication(LazyAsyncResult result)

  at System.Net.TlsStream.Write(Byte[] buffer, Int32 offset, Int32 size)
  at System.Net.ConnectStream.WriteHeaders(Boolean async)    --- End of
  inner exception stack trace ---    at
  System.Net.HttpWebRequest.GetResponse()    at
  Microsoft.IdentityModel.Clients.ActiveDirectory.HttpWebRequestWrapper.d__2.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)    at
  Microsoft.IdentityModel.Clients.ActiveDirectory.HttpHelper.d__0
  .MoveNext()    --- End of inner exception stack trace ---    at
  Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext.RunAsyncTask[T](Task1
  task)    at
  Microsoft.Azure.Commands.Common.Authentication.UserTokenProvider.DoAcquireToken(AdalConfiguration
  config, PromptBehavior promptBehavior, String userId, SecureString
  password)    at
  Microsoft.Azure.Commands.Common.Authentication.UserTokenProvider.SafeAquireToken(AdalConfiguration
  config, ShowDialog showDialog, String userId, SecureString password,
  Exception& ex)
      ErrorCode: service_returned_error
      StatusCode: 501'. At line:1 char:1
  + Login-AzureRmAccount $Error[0].Exception.InnerException

答:
I'm fairly certain this will bypass your problem but not actually solve it.

DISCLAIMER: This is not secure, and should only be done if you are certain that the certificate error you are getting is a false positive, or you truly don't care! This method leaves you open to establishing connections to malicious and/or compromised sites. This is the PowerShell equivalent to going to a web page in Internet Explorer, getting a certificate error, and clicking the Continue Anyway link.

If you try to manually login, and get a certificate error, but are ok with continuing past it then you can disable certificate checking in PowerShell so that it behaves similarly. Running this line before you try to login to Azure will disable certificate checking for the current session. You will have to run this each time you want to login to Azure, so long as there is a certificate error.

```<code> [System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
</code>```

A better solution would probably be to resolve the SSL/TLS issue that you are seeing, but that is most likely something better suited for ServerFault or something.

Body:
I am trying to connect to Azure using Powershell. When I try the command Login-AzureRmAccount, I get a pop-up to enter my credentials. But, immediately after that I get an error:

Login-AzureRmAccount : Service returned error. Check InnerException for more details: The underlying connection was
closed: Could not establish trust relationship for the SSL/TLS secure channel.
At line:1 char:1
+ Login-AzureRmAccount
+ ~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : CloseError: (:) [Add-AzureRmAccount], AadAuthenticationFailedException
    + FullyQualifiedErrorId : Microsoft.Azure.Commands.Profile.AddAzureRMAccountCommand

Can someone shed some light on this?

Update
The below inner exception is what I see:

'Microsoft.IdentityModel.Clients.ActiveDirectory.AdalServiceException:
  Service returned error. Check InnerException for more details --->
  System.Net.WebException: The underlying connection was closed: Could
  not establish trust relationship for the SSL/TLS secure channel. --->
  System.Security.Authentication.AuthenticationException: The remote
  certificate is invalid according to the validation procedure.    at
  System.Net.Security.SslState.StartSendAuthResetSignal(ProtocolToken
  message, AsyncProtocolRequest asyncRequest, Exception exception)    at
  System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32
  count, AsyncProtocolRequest asyncRequest)    at
  System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer,
  AsyncProtocolRequest asyncRequest)    at
  System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32
  count, AsyncProtocolRequest asyncRequest)    at
  System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer,
  AsyncProtocolRequest asyncRequest)    at
  System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32
  count, AsyncProtocolRequest asyncRequest)    at
  System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer,
  AsyncProtocolRequest asyncRequest)    at
  System.Net.Security.SslState.ForceAuthentication(Boolean receiveFirst,
  Byte[] buffer, AsyncProtocolRequest asyncRequest)    at
  System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult
  lazyResult)    at
  System.Threading.ExecutionContext.RunInternal(ExecutionContext
  executionContext, ContextCallback callback, Object state, Boolean
  preserveSyncCtx)    at
  System.Threading.ExecutionContext.Run(ExecutionContext
  executionContext, ContextCallback callback, Object state, Boolean
  preserveSyncCtx)    at
  System.Threading.ExecutionContext.Run(ExecutionContext
  executionContext, ContextCallback callback, Object state)    at
  System.Net.TlsStream.ProcessAuthentication(LazyAsyncResult result)

  at System.Net.TlsStream.Write(Byte[] buffer, Int32 offset, Int32 size)
  at System.Net.ConnectStream.WriteHeaders(Boolean async)    --- End of
  inner exception stack trace ---    at
  System.Net.HttpWebRequest.GetResponse()    at
  Microsoft.IdentityModel.Clients.ActiveDirectory.HttpWebRequestWrapper.d__2.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)    at
  Microsoft.IdentityModel.Clients.ActiveDirectory.HttpHelper.d__0
  .MoveNext()    --- End of inner exception stack trace ---    at
  Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext.RunAsyncTask[T](Task1
  task)    at
  Microsoft.Azure.Commands.Common.Authentication.UserTokenProvider.DoAcquireToken(AdalConfiguration
  config, PromptBehavior promptBehavior, String userId, SecureString
  password)    at
  Microsoft.Azure.Commands.Common.Authentication.UserTokenProvider.SafeAquireToken(AdalConfiguration
  config, ShowDialog showDialog, String userId, SecureString password,
  Exception& ex)
      ErrorCode: service_returned_error
      StatusCode: 501'. At line:1 char:1
  + Login-AzureRmAccount $Error[0].Exception.InnerException

Body:
I'm fairly certain this will bypass your problem but not actually solve it.

DISCLAIMER: This is not secure, and should only be done if you are certain that the certificate error you are getting is a false positive, or you truly don't care! This method leaves you open to establishing connections to malicious and/or compromised sites. This is the PowerShell equivalent to going to a web page in Internet Explorer, getting a certificate error, and clicking the Continue Anyway link.

If you try to manually login, and get a certificate error, but are ok with continuing past it then you can disable certificate checking in PowerShell so that it behaves similarly. Running this line before you try to login to Azure will disable certificate checking for the current session. You will have to run this each time you want to login to Azure, so long as there is a certificate error.

 [System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}

A better solution would probably be to resolve the SSL/TLS issue that you are seeing, but that is most likely something better suited for ServerFault or something.


问:
PostgreSQL trigger prevents another one to work
Suppose we have:

```<code>create table T
(
    id bigserial primary key
  , a  int
  , b  int
  , c  int
);
</code>```

I want c to be always equals to a+b and I want to prevent manual changes of c. So I create two triggers:

```<code>-- Prevents manual changes of c:

create or replace function no_changes() returns trigger as $$
begin
    if old.c is distinct from new.c then
        raise exception 'Can''t change c manually.';
    end if;
    return new;
end;
$$ language plpgsql;

create trigger no_changes
before update of c  -- 'before' so prevents changes in 'c'
on T
for each row
execute procedure no_changes();

-- Do c = a + b:

create or replace function change() returns trigger as $$
begin
    update T
    set c = a + b
    where id = new.id;
    return new;
end;
$$ language plpgsql;

create trigger change
after insert or update of a, b  -- 'after' so I'm sure the row is inserted/updated
on T
for each row
execute procedure change();
</code>```

If I do:

```<code>update T set c = 247;
</code>```

I see the error message "Can't change c manually" and the column doesn't changes. Great.

However, If I do:

```<code>insert into T (a, b) values (4, 3);
</code>```

Or:

```<code>update T set a = 3 where id = 2 -- suppose id = 2 exists
</code>```

Then I get the same error message as before. Obviously, The update command from change trigger fires no_changes trigger preventing the update in the c column.

Any ideas? Thanks!

答:
The whole logic could be placed in single function:

```<code>create or replace function change() returns trigger as $$
begin
    if old.c is distinct from new.c then
        raise exception 'Can''t change c manually.';
    end if;
    new.c := new.a + new.b;
    return new;
end;
$$ language plpgsql;

create trigger change
before insert or update on T
for each row
execute procedure change();
</code>```

But if you prefer to split the logic, then

1) Create both triggers on before event

2) "If multiple triggers of the same kind are defined for the same event, they will be fired in alphabetical order by name." So name triggers to get the desired order, for example trg1_check to prevent changes of c and trg2_change to calculate c value.

Body:
Suppose we have:

create table T
(
    id bigserial primary key
  , a  int
  , b  int
  , c  int
);

I want c to be always equals to a+b and I want to prevent manual changes of c. So I create two triggers:

-- Prevents manual changes of c:

create or replace function no_changes() returns trigger as $$
begin
    if old.c is distinct from new.c then
        raise exception 'Can''t change c manually.';
    end if;
    return new;
end;
$$ language plpgsql;

create trigger no_changes
before update of c  -- 'before' so prevents changes in 'c'
on T
for each row
execute procedure no_changes();

-- Do c = a + b:

create or replace function change() returns trigger as $$
begin
    update T
    set c = a + b
    where id = new.id;
    return new;
end;
$$ language plpgsql;

create trigger change
after insert or update of a, b  -- 'after' so I'm sure the row is inserted/updated
on T
for each row
execute procedure change();

If I do:

update T set c = 247;

I see the error message "Can't change c manually" and the column doesn't changes. Great.

However, If I do:

insert into T (a, b) values (4, 3);

Or:

update T set a = 3 where id = 2 -- suppose id = 2 exists

Then I get the same error message as before. Obviously, The update command from change trigger fires no_changes trigger preventing the update in the c column.

Any ideas? Thanks!

Body:
The whole logic could be placed in single function:

create or replace function change() returns trigger as $$
begin
    if old.c is distinct from new.c then
        raise exception 'Can''t change c manually.';
    end if;
    new.c := new.a + new.b;
    return new;
end;
$$ language plpgsql;

create trigger change
before insert or update on T
for each row
execute procedure change();

But if you prefer to split the logic, then

1) Create both triggers on before event

2) "If multiple triggers of the same kind are defined for the same event, they will be fired in alphabetical order by name." So name triggers to get the desired order, for example trg1_check to prevent changes of c and trg2_change to calculate c value.


问:
Phonegap yellow highlight
I have a Samsung Captivate. Whenever I click on a button or image a yellow highlight shows up around it. I was wondering is this the phone itself? Or is it something I can turn off via PhoneGap.

Makes the app ugly ;)

Thanks

答:
Use -webkit-tap-highlight-color in your CSS.

See this answer as well: How to disable the orange circle effect when clicking on a link, in a WebView

Title: Phonegap yellow highlight


问:
XDocument : Difference between .Root.Value and .Root.ToString
Does anybody know what is the difference between those two below statements :

```<code>xdoc.Root.Value;
</code>```

and

```<code>xdoc.Root.ToString();
</code>```

From my own research, I can see that the first line removes the root node and replaces the '\r\n' to '\n' whereas the second one keeps the content as original. Am I correct ? any documentation to back that up ?
As I want to use the first line but keep the original Windows new lines, is there a way to do that ?

答:
Did you read the documentation?

Value:

A String that contains all of the text content of this element. If there are multiple text nodes, they will be concatenated.

ToString():

Returns the indented XML for this node.

Body:
Does anybody know what is the difference between those two below statements :

xdoc.Root.Value;

and

xdoc.Root.ToString();

From my own research, I can see that the first line removes the root node and replaces the '\r\n' to '\n' whereas the second one keeps the content as original. Am I correct ? any documentation to back that up ?
As I want to use the first line but keep the original Windows new lines, is there a way to do that ?


问:
Transactions/Identity API must be enabled before using
I have been trying to enable the streamline identity flown for google-actions. I have also set up a mocked Authorisation flow. I edited the fields in the actions console but I keep getting this error:

expected_inputs[0].possible_intents[0]: Transactions/Identity API must be enabled before using.

I have tried from the simulator, from my phone, sandbox on and off, I still don't see what I need to activate to make it work.

答:
You don't have to use Transactions API to enable streamlined account linking but you need it only to use the mid-dialog account linking (AskForSignIn)

To test streamlined account linking without transactions API, you'll need to go to API.AI and select account linking required at the welcome intent. Learn more here.


问:
Can I throw exception with java bean
I want to notify to class1 with exception that can or cannot change a variable. I have tried to put in propertyChange to throw a exception but i can't with this method. how can I notify class1??

class1 ->

```<code>public void setProperty(int var) {
    if(var > 0){
    propertySupport.firePropertyChange("var", this.var,var);
    this.var = var;
    }else{
       System.out.println("bla bla");
    }
}

//methods
public void addPropertyChangeListener(PropertyChangeListener listener) {
    propertySupport.addPropertyChangeListener(listener);
}

public void removePropertyChangeListener(PropertyChangeListener listener) {
    propertySupport.removePropertyChangeListener(listener);
}
</code>```

class2 ->

```<code>@Override
public void propertyChange(PropertyChangeEvent evt){
    if(evt.getNewValue().equals("var"))
       //TODO
    }else{
       //throw exception to not change var in class1
    }
</code>```

答:
FirePropertyChange would tell me to change a variable or attribute that I'm interested in using. You should validate whether or not to change the variable in the same "setProperty" method then to notify class 2 that that value has changed

class1

```<code>public void setProperty(int var) {

if(this.var != var && var > 0){
   propertySupport.firePropertyChange("var", this.var,var);
   this.var = var;
}else{
   System.out.println("bla bla");
}
</code>```

}

class2

```<code>@Override
public void propertyChange(PropertyChangeEvent evt){
if(evt.getPropertyName().equals("var")){

   //I do something with this new variable
   System.out.print(evt.getNewValue());
}else{
   //throw exception to not change var in class1
}
</code>```

Title: Can I throw exception with java bean

Body:
I want to notify to class1 with exception that can or cannot change a variable. I have tried to put in propertyChange to throw a exception but i can't with this method. how can I notify class1??

class1 ->

public void setProperty(int var) {
    if(var > 0){
    propertySupport.firePropertyChange("var", this.var,var);
    this.var = var;
    }else{
       System.out.println("bla bla");
    }
}

//methods
public void addPropertyChangeListener(PropertyChangeListener listener) {
    propertySupport.addPropertyChangeListener(listener);
}

public void removePropertyChangeListener(PropertyChangeListener listener) {
    propertySupport.removePropertyChangeListener(listener);
}

class2 ->

@Override
public void propertyChange(PropertyChangeEvent evt){
    if(evt.getNewValue().equals("var"))
       //TODO
    }else{
       //throw exception to not change var in class1
    }

Body:
FirePropertyChange would tell me to change a variable or attribute that I'm interested in using. You should validate whether or not to change the variable in the same "setProperty" method then to notify class 2 that that value has changed

class1

public void setProperty(int var) {

if(this.var != var && var > 0){
   propertySupport.firePropertyChange("var", this.var,var);
   this.var = var;
}else{
   System.out.println("bla bla");
}

}

class2

@Override
public void propertyChange(PropertyChangeEvent evt){
if(evt.getPropertyName().equals("var")){

   //I do something with this new variable
   System.out.print(evt.getNewValue());
}else{
   //throw exception to not change var in class1
}


问:
Filtering in tweepy - exact phrase
I can't get tweepy filtering to quite work how I want to.
stream.filter(track=['one two' , 'three four'])

I want to retweet based on a specific two word set
i.e. "one two"

but I'm getting retweets where the tweet has those two words, but not in order and separated
i.e. "three two one" or "one three two" etc.

I want tweets which contain my phrase but in order
i.e. "one two three" or "three one two" or "one two" etc.

答: the twitter api doesn't allow that. you'll have to check for each returned tweet whether or not it actually contains one of your exact phrases.</p>

Title: Filtering in tweepy - exact phrase


答:
It always helps to decompose a recurrence relation till you find its base case.

```<code>is_even(2) => return is_odd(1)
           => return not is_even(1)
           => return not is_odd(0)
           => return not not is_even(0)
           => return not not True
           => return True            ---- (1)
</code>```

```<code>is_odd(2) => return not is_even(2)
          => return not True       [from (1)]
          => return False
</code>```

In general, from your recurrence functions, it is easy to observe that is_even(n) will return [not not not ... n times] True, while is_odd(n) will return [not not not ... n - 1 times] True. So the number of nots and hence the final expression depend on n (aha!). Well, that's certainly a roundabout way of asking whether

```<code>n % 2 == 0
</code>```

Title: Recursively checking for odd or even

Body:
It always helps to decompose a recurrence relation till you find its base case.

is_even(2) => return is_odd(1)
           => return not is_even(1)
           => return not is_odd(0)
           => return not not is_even(0)
           => return not not True
           => return True            ---- (1)

is_odd(2) => return not is_even(2)
          => return not True       [from (1)]
          => return False

In general, from your recurrence functions, it is easy to observe that is_even(n) will return [not not not ... n times] True, while is_odd(n) will return [not not not ... n - 1 times] True. So the number of nots and hence the final expression depend on n (aha!). Well, that's certainly a roundabout way of asking whether

n % 2 == 0


问:
Error running deep learning image classification example with Mxnet library on Python
I am trying to run the this image classification example that uses Mxnet library in python and the pre-trained deep learning model Inception-BN. The execution throws and error on this line: prob = model.predict(batch)[0] with the error message:

```<code>MXNetError: InferShape Error in ch_concat_3c_chconcat: [14:35:56] src/operator/./concat-inl.h:152: Check failed: (dshape[j]) == (tmp[j]) Incorrect shape[2]: (1,320,15,15). (first input shape: (1,576,14,14))
</code>```

I tried downloading the Inception-BN model again to make sure it was up to date but it didn't make a difference. I do suspect the problem could be on line: model = mx.model.FeedForward.load(prefix, num_round, ctx=mx.gpu(), numpy_batch_size=1) where I had to change gpu for cpu since my server is not equiped with a gpu. Nevertheless the error doesn't seem to point on that direction.

Any idea how to fix it? Is using a cpu instead of a gpu a problem other than a lower performance?

Finally here is the complete error information:

```<code>---------------------------------------------------------------------------
MXNetError                                Traceback (most recent call last)
<ipython-input-7-98e51e4226e1> in <module>()
      1 # Get prediction probability of 1000 classes from model
----> 2 prob = model.predict(batch)[0]
      3 # Argsort, get prediction index from largest prob to lowest
      4 pred = np.argsort(prob)[::-1]
      5 # Get top1 label

/users/CREATE/olb/mxnet/python/mxnet/model.pyc in predict(self, X, num_batch, return_data, reset)
    589         data_shapes = X.provide_data
    590         data_names = [x[0] for x in data_shapes]
--> 591         self._init_predictor(data_shapes)
    592         batch_size = X.batch_size
    593         data_arrays = [self._pred_exec.arg_dict[name] for name in data_names]

/users/CREATE/olb/mxnet/python/mxnet/model.pyc in _init_predictor(self, input_shapes)
    520         # for now only use the first device
    521         pred_exec = self.symbol.simple_bind(
--> 522             self.ctx[0], grad_req='null', **dict(input_shapes))
    523         pred_exec.copy_params_from(self.arg_params, self.aux_params)
    524

/users/CREATE/olb/mxnet/python/mxnet/symbol.pyc in simple_bind(self, ctx, grad_req, type_dict, **kwargs)
    623         if type_dict is None:
    624             type_dict = {k: mx_real_t for k in self.list_arguments()}
--> 625         arg_shapes, _, aux_shapes = self.infer_shape(**kwargs)
    626         arg_types, _, aux_types = self.infer_type(**type_dict)
    627         if arg_shapes == None or arg_types == None:

/users/CREATE/olb/mxnet/python/mxnet/symbol.pyc in infer_shape(self, *args, **kwargs)
    410             The order is in the same order as list_auxiliary()
    411         """
--> 412         return self._infer_shape_impl(False, *args, **kwargs)
    413
    414     def infer_shape_partial(self, *args, **kwargs):

/users/CREATE/olb/mxnet/python/mxnet/symbol.pyc in _infer_shape_impl(self, partial, *args, **kwargs)
    470             ctypes.byref(aux_shape_ndim),
    471             ctypes.byref(aux_shape_data),
--> 472             ctypes.byref(complete)))
    473         if complete.value != 0:
    474             arg_shapes = [

/users/CREATE/olb/mxnet/python/mxnet/base.pyc in check_call(ret)
     75     """
     76     if ret != 0:
---> 77         raise MXNetError(py_str(_LIB.MXGetLastError()))
     78
     79 def c_str(string):

MXNetError: InferShape Error in ch_concat_3c_chconcat: [14:35:56] src/operator/./concat-inl.h:152: Check failed: (dshape[j]) == (tmp[j]) Incorrect shape[2]: (1,320,15,15). (first input shape: (1,576,14,14))
</code>```

答:
The mentioned notebook is moved to notebooks repository. I tried to run it today and was able to run the tutorial successfully.
The issue was in old model because the change in interface broke backward compatibility. Seems like they have uploaded the new trained inception-BN model.

Posting this if someone else also got this error, just download the new model here.

Body:
I am trying to run the this image classification example that uses Mxnet library in python and the pre-trained deep learning model Inception-BN. The execution throws and error on this line: prob = model.predict(batch)[0] with the error message:

MXNetError: InferShape Error in ch_concat_3c_chconcat: [14:35:56] src/operator/./concat-inl.h:152: Check failed: (dshape[j]) == (tmp[j]) Incorrect shape[2]: (1,320,15,15). (first input shape: (1,576,14,14))

I tried downloading the Inception-BN model again to make sure it was up to date but it didn't make a difference. I do suspect the problem could be on line: model = mx.model.FeedForward.load(prefix, num_round, ctx=mx.gpu(), numpy_batch_size=1) where I had to change gpu for cpu since my server is not equiped with a gpu. Nevertheless the error doesn't seem to point on that direction.

Any idea how to fix it? Is using a cpu instead of a gpu a problem other than a lower performance?

Finally here is the complete error information:

---------------------------------------------------------------------------
MXNetError                                Traceback (most recent call last)
<ipython-input-7-98e51e4226e1> in <module>()
      1 # Get prediction probability of 1000 classes from model
----> 2 prob = model.predict(batch)[0]
      3 # Argsort, get prediction index from largest prob to lowest
      4 pred = np.argsort(prob)[::-1]
      5 # Get top1 label

/users/CREATE/olb/mxnet/python/mxnet/model.pyc in predict(self, X, num_batch, return_data, reset)
    589         data_shapes = X.provide_data
    590         data_names = [x[0] for x in data_shapes]
--> 591         self._init_predictor(data_shapes)
    592         batch_size = X.batch_size
    593         data_arrays = [self._pred_exec.arg_dict[name] for name in data_names]

/users/CREATE/olb/mxnet/python/mxnet/model.pyc in _init_predictor(self, input_shapes)
    520         # for now only use the first device
    521         pred_exec = self.symbol.simple_bind(
--> 522             self.ctx[0], grad_req='null', **dict(input_shapes))
    523         pred_exec.copy_params_from(self.arg_params, self.aux_params)
    524

/users/CREATE/olb/mxnet/python/mxnet/symbol.pyc in simple_bind(self, ctx, grad_req, type_dict, **kwargs)
    623         if type_dict is None:
    624             type_dict = {k: mx_real_t for k in self.list_arguments()}
--> 625         arg_shapes, _, aux_shapes = self.infer_shape(**kwargs)
    626         arg_types, _, aux_types = self.infer_type(**type_dict)
    627         if arg_shapes == None or arg_types == None:

/users/CREATE/olb/mxnet/python/mxnet/symbol.pyc in infer_shape(self, *args, **kwargs)
    410             The order is in the same order as list_auxiliary()
    411         """
--> 412         return self._infer_shape_impl(False, *args, **kwargs)
    413
    414     def infer_shape_partial(self, *args, **kwargs):

/users/CREATE/olb/mxnet/python/mxnet/symbol.pyc in _infer_shape_impl(self, partial, *args, **kwargs)
    470             ctypes.byref(aux_shape_ndim),
    471             ctypes.byref(aux_shape_data),
--> 472             ctypes.byref(complete)))
    473         if complete.value != 0:
    474             arg_shapes = [

/users/CREATE/olb/mxnet/python/mxnet/base.pyc in check_call(ret)
     75     """
     76     if ret != 0:
---> 77         raise MXNetError(py_str(_LIB.MXGetLastError()))
     78
     79 def c_str(string):

MXNetError: InferShape Error in ch_concat_3c_chconcat: [14:35:56] src/operator/./concat-inl.h:152: Check failed: (dshape[j]) == (tmp[j]) Incorrect shape[2]: (1,320,15,15). (first input shape: (1,576,14,14))


问:
Flexbox different size childs
I learn flexbox and I have a first question how to make such a layout of columns as in the picture?  [MyCodeFiddle](http://jsfiddle.net/1s3bo913/)

layout project

答:
You can nest flexbox containers:

One outer container A, display: flex; flex-direction: column;

Inside of that two containers B1 and B2, both display: flex; flex-direction: row;

Inside the first one of those (B1) two containers B1a and B1b

B1b should again have display: flex; flex-direction: column; and contain two DIVs or images (the berry pictures)

Inside B2 two regular DIVs (no flexbox)

Title: Flexbox different size childs


问:
React-native componentWillUnmount not being called
I'm running on Android and if I used the hardware back button to exit the application the componentWillUnmount function gets called.  However, if I use the square button to show the list of running apps and swipe to close the function does not get called.

Any ideas on how to detect when the app is being closed so that I can clear timers, save data etc.

Thanks.

答:
I ran into the same problem.  To solve it, I didn't attach an event listener to the stateChange.  Instead I just look at AppState.currentState inside of the componentDidMount() function.

The problem was that eventListeners were getting attached when the component mounted, but not becoming detached at componentWillUnmount.


问:
sql group by sum of all sums
I have a query (formatted for Oracle):

```<code>select sum(inv.quantity * inv.price), spn.salesperson_name
from invoice inv
inner join salesperson spn on spn.spn_id = inv.spn_id
where inc.invoice_date between to_date('05/01/2017', 'MM/dd/YYYY') and to_date('05/31/2017', 'MM/dd/YYYY')
group by spn.salesperson_name
</code>```

To add up invoices for the month of May. The result is similar to:

```<code>$446,088.62     Bob
$443,439.29     Sally
$275,097.00     Tom
 $95,170.00     George
 $53,150.00     Jill
</code>```

But, I need to divide each sum to the sum of the sums ($1,312,944.91), so that the result is:

```<code>$446,088.62     34%  Bob
$443,439.29     34%  Sally
$275,097.00     21%  Tom
 $95,170.00      7%  George
 $53,150.00      4%  Jill
</code>```

(The sum of the percentage column should be 100%)

Is there a way to accomplish this in the query?

答:
When functions exist that do exactly what you need, it is best to use those functions. In this case, the SQL Standard analytic function RATIO_TO_REPORT (which is implemented at least in Oracle and SQL Server) does exactly what you need. https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions124.htm

Specifically, the select clause could be:

```<code>select sum(inv.quantity * inv.price) AS TOTAL_REVENUE   --  use column aliases!
     , ratio_to_report(sum(inv.quantity * inv.price)) over () AS RATIO,
     , spn.salesperson_name
from   .......   (rest of your query goes here)
</code>```

Note that this solution, like the Accepted Answer, will show the ratio as a decimal, not as a percentage (and not rounded). If you need to attach a percentage sign, you will need to convert to string... and if so, the following trick (it is a trick!) will give you what you need:

```<code>to_char( ratio_to_report(.....), 'fm99L', 'nls_currency = %' ) AS RATIO, .....
</code>```

The L element in to_char is for currency symbol; you define the currency symbol to be the percent sign.

Title: sql group by sum of all sums

Body:
I have a query (formatted for Oracle):

select sum(inv.quantity * inv.price), spn.salesperson_name
from invoice inv
inner join salesperson spn on spn.spn_id = inv.spn_id
where inc.invoice_date between to_date('05/01/2017', 'MM/dd/YYYY') and to_date('05/31/2017', 'MM/dd/YYYY')
group by spn.salesperson_name

To add up invoices for the month of May. The result is similar to:

$446,088.62     Bob
$443,439.29     Sally
$275,097.00     Tom
 $95,170.00     George
 $53,150.00     Jill

But, I need to divide each sum to the sum of the sums ($1,312,944.91), so that the result is:

$446,088.62     34%  Bob
$443,439.29     34%  Sally
$275,097.00     21%  Tom
 $95,170.00      7%  George
 $53,150.00      4%  Jill

(The sum of the percentage column should be 100%)

Is there a way to accomplish this in the query?

Body:
When functions exist that do exactly what you need, it is best to use those functions. In this case, the SQL Standard analytic function RATIO_TO_REPORT (which is implemented at least in Oracle and SQL Server) does exactly what you need. https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions124.htm

Specifically, the select clause could be:

select sum(inv.quantity * inv.price) AS TOTAL_REVENUE   --  use column aliases!
     , ratio_to_report(sum(inv.quantity * inv.price)) over () AS RATIO,
     , spn.salesperson_name
from   .......   (rest of your query goes here)

Note that this solution, like the Accepted Answer, will show the ratio as a decimal, not as a percentage (and not rounded). If you need to attach a percentage sign, you will need to convert to string... and if so, the following trick (it is a trick!) will give you what you need:

to_char( ratio_to_report(.....), 'fm99L', 'nls_currency = %' ) AS RATIO, .....

The L element in to_char is for currency symbol; you define the currency symbol to be the percent sign.


问:
Error when testing a component which uses templateUrl
I can see in the test output that console.log(dummyComponentInstance); is being called and evaluating to undefined.

Also, console.log('beforeEach done'); is never logged.

dummy.component.spec.ts

```<code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { DummyComponent } from './dummy.component';

describe('DummyComponent', () => {

  let dummyComponentInstance: DummyComponent;
  let fixture: ComponentFixture<DummyComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [DummyComponent]
    })
      .compileComponents()
      .then(() => {
        fixture = TestBed.createComponent(DummyComponent);
        dummyComponentInstance = fixture.componentInstance;
        console.log('beforeEach done');
      });
  }));

  it('should work', () => {
    console.log(dummyComponentInstance);
    expect(dummyComponentInstance instanceof DummyComponent).toBe(true, 'should create DummyComponent');
  });
});
</code>```

dummy.component.ts

```<code>import { Component } from '@angular/core';

@Component({
  selector: 'dummy',
  templateUrl: './dummy.component.html'
})
export class DummyComponent {
  public initialized = false;
}
</code>```

Error after running the test:

```<code>07 06 2017 13:27:09.187:INFO [launcher]: Starting browser PhantomJS
07 06 2017 13:27:09.437:INFO [PhantomJS 2.1.1 (Linux 0.0.0)]: Connected on socket 4Vq49vX24cDAIZfjAAAA with id 34827962
LOG: undefined
PhantomJS 2.1.1 (Linux 0.0.0) DummyComponent should work FAILED
    invokeTask@/tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:605:36
    onInvokeTask@/tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:154:49
    invokeTask@/tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:604:48
    runTask@/tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:372:57
    drainMicroTaskQueue@/tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:765:42
    run@/tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:17951:29
    /tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:17964:31
    flush@/tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:17813:11
    resolvePromise@/tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:951:78
    resolvePromise@/tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:921:31
    /tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:998:31
    Expected false to be true, 'should create DummyComponent'.
    src/app/dummy.component.spec.js:21:98
</code>```

答:
So a couple things, and this might just be my confusion. Does dummy.component.html actually exist?

When you call

```<code>beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [DummyComponent]
    })
      .compileComponents()
      .then(() => {
        fixture = TestBed.createComponent(DummyComponent);
        dummyComponentInstance = fixture.componentInstance;
        console.log('beforeEach done');
      });
  }));
</code>```

You're basically saying "hey, I have some files I need you to fetch, that's an async operation, please compile that template and then create my fixture.

If that html file doesn't exist ... it will fail during your testbed configuration. I ask because you didn't show that file.

I dropped your code into my test project and it worked fine with an empty template. It also worked with an empty templateUrl file.

If you don't have the file yet, or you don't intend to test the file, you can save overhead costs by avoiding fixture =TestBed.createComponent(DummyComponent) all together. It's very very expensive (you're talking 800~ms vs 15ms), because it creates a lot of additional (and powerful) functionality (like compiling your template to a kind of shadow DOM, as I understand it).

If you do have a dummy.component.html file, and it has elements the dynamic module doesn't know how to interpret, then you can either import the NO_SCHEMA_ERRORS from @angular/core and put that in your configuration TestBed:

```<code>...
schemas: [NO_SCHEMA_ERRORS]
...
</code>```

Or you can just teach the testbed how to provide those elements (generally importing those parts. But again, that's not really your problem. Your problem seems to be dummy.component.html doesn't exist.

Hope this helps.

Body:
I can see in the test output that console.log(dummyComponentInstance); is being called and evaluating to undefined.

Also, console.log('beforeEach done'); is never logged.

dummy.component.spec.ts

import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { DummyComponent } from './dummy.component';

describe('DummyComponent', () => {

  let dummyComponentInstance: DummyComponent;
  let fixture: ComponentFixture<DummyComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [DummyComponent]
    })
      .compileComponents()
      .then(() => {
        fixture = TestBed.createComponent(DummyComponent);
        dummyComponentInstance = fixture.componentInstance;
        console.log('beforeEach done');
      });
  }));

  it('should work', () => {
    console.log(dummyComponentInstance);
    expect(dummyComponentInstance instanceof DummyComponent).toBe(true, 'should create DummyComponent');
  });
});

dummy.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'dummy',
  templateUrl: './dummy.component.html'
})
export class DummyComponent {
  public initialized = false;
}

Error after running the test:

07 06 2017 13:27:09.187:INFO [launcher]: Starting browser PhantomJS
07 06 2017 13:27:09.437:INFO [PhantomJS 2.1.1 (Linux 0.0.0)]: Connected on socket 4Vq49vX24cDAIZfjAAAA with id 34827962
LOG: undefined
PhantomJS 2.1.1 (Linux 0.0.0) DummyComponent should work FAILED
    invokeTask@/tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:605:36
    onInvokeTask@/tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:154:49
    invokeTask@/tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:604:48
    runTask@/tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:372:57
    drainMicroTaskQueue@/tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:765:42
    run@/tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:17951:29
    /tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:17964:31
    flush@/tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:17813:11
    resolvePromise@/tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:951:78
    resolvePromise@/tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:921:31
    /tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:998:31
    Expected false to be true, 'should create DummyComponent'.
    src/app/dummy.component.spec.js:21:98

Body:
So a couple things, and this might just be my confusion. Does dummy.component.html actually exist?

When you call

beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [DummyComponent]
    })
      .compileComponents()
      .then(() => {
        fixture = TestBed.createComponent(DummyComponent);
        dummyComponentInstance = fixture.componentInstance;
        console.log('beforeEach done');
      });
  }));

You're basically saying "hey, I have some files I need you to fetch, that's an async operation, please compile that template and then create my fixture.

If that html file doesn't exist ... it will fail during your testbed configuration. I ask because you didn't show that file.

I dropped your code into my test project and it worked fine with an empty template. It also worked with an empty templateUrl file.

If you don't have the file yet, or you don't intend to test the file, you can save overhead costs by avoiding fixture =TestBed.createComponent(DummyComponent) all together. It's very very expensive (you're talking 800~ms vs 15ms), because it creates a lot of additional (and powerful) functionality (like compiling your template to a kind of shadow DOM, as I understand it).

If you do have a dummy.component.html file, and it has elements the dynamic module doesn't know how to interpret, then you can either import the NO_SCHEMA_ERRORS from @angular/core and put that in your configuration TestBed:

...
schemas: [NO_SCHEMA_ERRORS]
...

Or you can just teach the testbed how to provide those elements (generally importing those parts. But again, that's not really your problem. Your problem seems to be dummy.component.html doesn't exist.

Hope this helps.


问:
Using filters in pyGtk
I am writing a script to display a GUI in which certain files can be chosen. I am using pyGtk and as of now, my code can display all the zip files. I want to add another filter to display only the zip files with the latest date.

Below is my function that displays only zip files.

```<code> def open_file( self, w, data=None):
    d = gtk.FileChooserDialog( title="Select a file",
                               parent=self.window,
                               action=gtk.FILE_CHOOSER_ACTION_OPEN,
                               buttons=("OK",True,"Cancel",False)
                               )
    #create filters
    filter1 = gtk.FileFilter()
    filter1.set_name("All files")
    filter1.add_pattern("*")
    d.add_filter(filter1)
    filter2 = gtk.FileFilter()
    filter2.set_name("Zip files")
    filter2.add_pattern("*.zip")
    d.add_filter(filter2)

    ok = d.run()
    if ok:
      import os
      fullname = d.get_filename()
      dirname, fname = os.path.split( fullname)
      size = "%d bytes" % os.path.getsize( fullname)
      text = self.label_template % (fname, dirname, size)
    else:
      text = self.label_template % ("","","")
    self.label.set_label( text)
    d.destroy()
</code>```

Is there a way I can choose a filter to display only the latest zip files in a each folder?

Thanks in advance for your help!

答: Instead of using filter2.add_pattern("*.zip") use filter2.add_pattern("filename")where filename is the name of the file with the latest date. You can write a function that would return a list with file names of the latest zip file.

Title: Using filters in pyGtk

Body:
I am writing a script to display a GUI in which certain files can be chosen. I am using pyGtk and as of now, my code can display all the zip files. I want to add another filter to display only the zip files with the latest date.

Below is my function that displays only zip files.

 def open_file( self, w, data=None):
    d = gtk.FileChooserDialog( title="Select a file",
                               parent=self.window,
                               action=gtk.FILE_CHOOSER_ACTION_OPEN,
                               buttons=("OK",True,"Cancel",False)
                               )
    #create filters
    filter1 = gtk.FileFilter()
    filter1.set_name("All files")
    filter1.add_pattern("*")
    d.add_filter(filter1)
    filter2 = gtk.FileFilter()
    filter2.set_name("Zip files")
    filter2.add_pattern("*.zip")
    d.add_filter(filter2)

    ok = d.run()
    if ok:
      import os
      fullname = d.get_filename()
      dirname, fname = os.path.split( fullname)
      size = "%d bytes" % os.path.getsize( fullname)
      text = self.label_template % (fname, dirname, size)
    else:
      text = self.label_template % ("","","")
    self.label.set_label( text)
    d.destroy()

Is there a way I can choose a filter to display only the latest zip files in a each folder?

Thanks in advance for your help!