问:
How to create a replicaset through a custom resource?
I want to create a custom resource that is able to create a replicaset under a certain event. What is the best way to accomplish this?

Note that I am aware of deployment, but deployment does not meet my intended use cases.

答:
Seems like you might be looking into building something that would suit more or less the operator pattern.

https://coreos.com/operators/

https://coreos.com/blog/introducing-operators.html

https://github.com/coreos/prometheus-operator

Generaly you need to watch on some resources including your custom ones with kube client and act based on events propagated from kube API.


来源: stackexchange

问:
relational prolog and bit mask manipulations
I am trying my hand at relational prolog. Part of my program needs to deal with bitmasks. It however seems that prolog code handles bit makes, such as to set a bit or clear a bit doesn't work relationally -- i.e. it only works in setting a bit, but not in the other direction, identifying what bit is set.

For example:

```<code>setbit(X, N, V) :-
    N1 #= 1<< N,
    V #= X \/ N1.
</code>```

this code only work in one direction, where X and N are given and V is calculated. If one provides V and N, then X is not derived, but rather its left as an uninstantiated expression.

Does this mean that calculating with bit maps and masks is out of scope of relational prolog.

```<code>?- setbit(0,1,X).
X = 2.

?- setbit(X, 1, 2).
2#=X\/2.
</code>```

the latter doesn't bind X to 0.

thank you,

Daniel

Edit: based on the comments below, the following code works very well:

```<code>setbit(X, N, V) :-
    X in 0..1,
    label([X]),
    N1 #= 1<< N,
    V #= X \/ N1.

clearbit(X, N, V) :-
    X in 0..1,
    label([X]),
    current_prolog_flag(max_tagged_integer, MTI),
    N1 #= MTI /\ \(1<<N),
%   N1 #= 0xffffffffffffff /\ \(1<<N),
    V #= X /\ N1
</code>```

Note, the current_prolog_flag -- it retrieves the maximum integer fitting into one word on the current machine architecture -- on 64 bit its 54 bits, the rest of the bits are used for housekeeping.

答:
From a given solution, you cannot conclude that it is the only solution. That is, from

```<code>?- setbit(0,1,X).
   X = 2.
</code>```

you cannot conclude that

```<code>?- setbit(X, 1, 2).
</code>```

has X = 0 as the only solution. In fact, there is another solution, namely

```<code>?- setbit(2, 1, 2).
   true.
</code>```

Ideally, all constraints would maintain domain-consistency.  In this ideal world we would have:

```<code>?- setbit(X, 1, 2).
   X in 0\/2,           % idealiter
   2#=X\/2.
</code>```

instead of

```<code>?- setbit(X, 1, 2).
   2#=X\/2.             % realiter
</code>```

But first of all, let us realize that both answers are correct! The second answer says precisely the same as the ideal one.  However, finding a concrete solution may be more costly in the second case. In particular, since the following query has an answer:

```<code>?- setbit(X, 1, 2), X #> 2.
   X in 3..sup,
   2#=X\/2.             % inconsistency
</code>```

This answer reads like the notice of winning a lottery ticket you never heard of:

Yes, congratulation! There is a solution, provided all this fine print, this X in 3..sup, 2#=/2 has a solution, otherwise it does not have any solution. So don't complain, we told you so.

That is, an answer may very well contain exactly zero solutions. To be absolutely sure about a solution, you have to eliminate all constraints. The easiest way to do so, is using labeling/2. However, labeling/2 is defined only for finite domains (that's where the FD in CLPFD stems from). But in this case X is not constrained to a finite domain - would that be the case, we would have an extra constraint like X in 0..2.

The degree of consistency in clpfd-systems heavily depends on the actual use cases. After all, full consistency is undecidable. So there will always be cases where we would expect a more precise outcome. It is rather a question of tradeoffs for both run- and development time. Should you have convincing use cases contact the system developer.

In this particular case, you are probably better off using modulo arithmetics and addition.

ContentLicense: CC BY-SA 3.0

Body:
I am trying my hand at relational prolog. Part of my program needs to deal with bitmasks. It however seems that prolog code handles bit makes, such as to set a bit or clear a bit doesn't work relationally -- i.e. it only works in setting a bit, but not in the other direction, identifying what bit is set.

For example:

setbit(X, N, V) :-
    N1 #= 1<< N,
    V #= X \/ N1.

this code only work in one direction, where X and N are given and V is calculated. If one provides V and N, then X is not derived, but rather its left as an uninstantiated expression.

Does this mean that calculating with bit maps and masks is out of scope of relational prolog.

?- setbit(0,1,X).
X = 2.

?- setbit(X, 1, 2).
2#=X\/2.

the latter doesn't bind X to 0.

thank you,

Daniel

Edit: based on the comments below, the following code works very well:

setbit(X, N, V) :-
    X in 0..1,
    label([X]),
    N1 #= 1<< N,
    V #= X \/ N1.

clearbit(X, N, V) :-
    X in 0..1,
    label([X]),
    current_prolog_flag(max_tagged_integer, MTI),
    N1 #= MTI /\ \(1<<N),
%   N1 #= 0xffffffffffffff /\ \(1<<N),
    V #= X /\ N1

Note, the current_prolog_flag -- it retrieves the maximum integer fitting into one word on the current machine architecture -- on 64 bit its 54 bits, the rest of the bits are used for housekeeping.

Body:
From a given solution, you cannot conclude that it is the only solution. That is, from

?- setbit(0,1,X).
   X = 2.

you cannot conclude that

?- setbit(X, 1, 2).

has X = 0 as the only solution. In fact, there is another solution, namely

?- setbit(2, 1, 2).
   true.

Ideally, all constraints would maintain domain-consistency.  In this ideal world we would have:

?- setbit(X, 1, 2).
   X in 0\/2,           % idealiter
   2#=X\/2.

instead of

?- setbit(X, 1, 2).
   2#=X\/2.             % realiter

But first of all, let us realize that both answers are correct! The second answer says precisely the same as the ideal one.  However, finding a concrete solution may be more costly in the second case. In particular, since the following query has an answer:

?- setbit(X, 1, 2), X #> 2.
   X in 3..sup,
   2#=X\/2.             % inconsistency

This answer reads like the notice of winning a lottery ticket you never heard of:

Yes, congratulation! There is a solution, provided all this fine print, this X in 3..sup, 2#=/2 has a solution, otherwise it does not have any solution. So don't complain, we told you so.

That is, an answer may very well contain exactly zero solutions. To be absolutely sure about a solution, you have to eliminate all constraints. The easiest way to do so, is using labeling/2. However, labeling/2 is defined only for finite domains (that's where the FD in CLPFD stems from). But in this case X is not constrained to a finite domain - would that be the case, we would have an extra constraint like X in 0..2.

The degree of consistency in clpfd-systems heavily depends on the actual use cases. After all, full consistency is undecidable. So there will always be cases where we would expect a more precise outcome. It is rather a question of tradeoffs for both run- and development time. Should you have convincing use cases contact the system developer.

In this particular case, you are probably better off using modulo arithmetics and addition.


问:
Azure Key Vault Nuget Package Error
I am trying to intigrate azure key vault in my console application that is running on framework 4.5.2.
But i am getting error  when i try to install nuget package "Microsoft.Extensions.Configuration.AzureKeyVault".

can you please suggest,why this error comes. i am attaching error snapshot along with application settings.

答:
I am trying to intigrate azure key vault in my console application that is running on framework 4.5.2

According to Microsoft.Extensions.Configuration.AzureKeyVault version 2.0 nuget, we could know that dependencies is NETStandard 2.0.

Microsoft.Extensions.Configuration.AzureKeyVault version 2. 0  is not compatible with with .net framework 4.5.2,please have a try to install on .net framework 4.6.1 or later or .net core 2.0.

Another way is that we could use the version  Microsoft.Extensions.Configuration.AzureKeyVault 1.0.2 which dependency is .net framework 4.5.1

Title: Azure Key Vault Nuget Package Error


问:
Selenium en OWin Selfhost - how to debug?
I want to create a Selenium Webdriver test and for this to work, I want to start the existing OWin application using OWin SelfHost.

For some reason, the OWin server does not respond once a breakpoint is it... Can somebody tell me what I'm doing wrong?

Below is the code with some more info...

```<code>    [OneTimeSetUp]
    public void InitDriverAndBackend()
    {
        string baseAddress = "http://127.0.0.1:9001/";
        httpServer = WebApp.Start<Startup>(url: baseAddress);
        Thread.Sleep(30000);
        //I have a breakpoint on the line below. Before the breakpoint is hit,
        //I receive a response when going one of my webapi's on port 9001
        //However, once the breakpoint is hit, the server does not response at all and the request stays pending
        Driver = new ChromeDriver();
    }
</code>```

So, I expect to receive a response but once a breakpoint is hit, the requests just stay pending.

答:
Your tests and your OWIN app are separate things. Don't mix them. You shouldn't run UI tests as you would do to unit tests - creating a mocked instance and testing it.

Compile your OWIN app. Deploy it. Run it. Then start your tests from a separate process against the deployed app. Optionally, stop the server after tests finished.
This is a part of what is called proper CI/CD process.

OK, now to your question: what happens is that this Driver = new ChromeDriver(); is non-blocking. So the method finishes, the garbage collector cleans up, and this effectively means the death of your OWIN app.

OK, that was simplified version. In the case of a breakpoint you described, the entire application is stopped, so it simply cannot process your response.

This is wrong, but should you really really need to do it within the same application:

inherit all test classes from some base

in that base in [OneTimeSetup] (nUnit) or equivalent method, create on a separate thread the owin server which won't stop until explicitly told so (while(!ready2Exit){Thread.Sleep(100);})

in [OneTimeTearDown] set that ready2Exit to true;

But mind you, this is marginally wrong.

Body:
I want to create a Selenium Webdriver test and for this to work, I want to start the existing OWin application using OWin SelfHost.

For some reason, the OWin server does not respond once a breakpoint is it... Can somebody tell me what I'm doing wrong?

Below is the code with some more info...

    [OneTimeSetUp]
    public void InitDriverAndBackend()
    {
        string baseAddress = "http://127.0.0.1:9001/";
        httpServer = WebApp.Start<Startup>(url: baseAddress);
        Thread.Sleep(30000);
        //I have a breakpoint on the line below. Before the breakpoint is hit,
        //I receive a response when going one of my webapi's on port 9001
        //However, once the breakpoint is hit, the server does not response at all and the request stays pending
        Driver = new ChromeDriver();
    }

So, I expect to receive a response but once a breakpoint is hit, the requests just stay pending.


问:
Open persistent connection
I want to implement a system that will open a persistent connection between a server and a client (iPhone, in this case), and when it's needed send information using this connection.

How can I implement something like this?
Maybe somebody already wrote something that reach this case?

答:
The most obvious solution would be to use an NSStream. (The Cocoa libraries are incredibly rich, so there's nearly always a solution for common functionality like this.)

However, are you sure you really require a persistent connection? (Especially on a mobile device that may occasionally drop signal/switch from WiFi to 3G networks, etc.)

ContentLicense: CC BY-SA 2.5

Title: Open persistent connection


问:
Correctly calculate the area beneath curve using trapz and simpson in python
I used np.trapz and scipy simps to calculate an area below a curve and noticed that I might not be doing it correctly. As an example below

```<code>import numpy as np
from scipy.integrate import simps

y = np.array([1,2,3,4,5])
y1= np.array([5,5,5,5,5])

print np.trapz(y,dx=1)
print simps(y,dx=1)
print np.trapz(y1,dx=1)
print simps(y1,dx=1)
</code>```

These yield

```<code>12.0
12.0
20.0
20.0
</code>```

But shouldn't they yeild 15 and 25 respectively? It seems like it between to small limits?

答:
You have implicitly that x = [0, 1, 2, 3, 4], remember that in programming almost everywhere and everything starts with 0. Also, usually, upper limits are not inclusive.

For y that means a rectangle with vertices (0,0), (0,1), (4,0), and (4,1) plus a triangle with vertices (0,1), (4,5), and (4,1). The rectangle has an area of 4*1=4 and the triangle 4*4/2=8 totaling an area of 12.

For y1 you have a rectangle with vertices (0,0), (0,5), (4,0), and (4,5), thus giving you and area of 20.

Body:
I used np.trapz and scipy simps to calculate an area below a curve and noticed that I might not be doing it correctly. As an example below

import numpy as np
from scipy.integrate import simps

y = np.array([1,2,3,4,5])
y1= np.array([5,5,5,5,5])

print np.trapz(y,dx=1)
print simps(y,dx=1)
print np.trapz(y1,dx=1)
print simps(y1,dx=1)

These yield

12.0
12.0
20.0
20.0

But shouldn't they yeild 15 and 25 respectively? It seems like it between to small limits?


问:
java.math.BigInteger cannot be cast to fr.pc30.bean.Intervention
I have an error with java.math.BigInteger cannot be cast to a class name.

This is my request

```<code>public List<Intervention> findTicketTaskAnnuler(long partnaireId,InterventionType type)
return   getSession().createSQLQuery(new StringBuilder("")
                .append("SELECT i.id FROM intervention i ")
                .append("INNER JOIN logged_event lo on lo.NEW_ID = i.id and lo.OPERATION ='ANNULATION' and lo.DATE_CREATION =CURDATE() and lo.USER != :name ")
                .append("WHERE i.ID_PARTENAIRE = :partnaireId ")
                .append("and i.annulee=1 ")
                .append("order by i.id desc ").toString())
                .setParameter("partnaireId", partnaireId)
                .setParameter("name", type.getName())
                .list();
</code>```

答: Your query is getting list of ids (which I guess has bigInteger datatype) and you are trying to store your query output to list of Intervention object either change your list to List<Long> or change query to select all the columns with SELECT * query.

Body:
I have an error with java.math.BigInteger cannot be cast to a class name.

This is my request

public List<Intervention> findTicketTaskAnnuler(long partnaireId,InterventionType type)
return   getSession().createSQLQuery(new StringBuilder("")
                .append("SELECT i.id FROM intervention i ")
                .append("INNER JOIN logged_event lo on lo.NEW_ID = i.id and lo.OPERATION ='ANNULATION' and lo.DATE_CREATION =CURDATE() and lo.USER != :name ")
                .append("WHERE i.ID_PARTENAIRE = :partnaireId ")
                .append("and i.annulee=1 ")
                .append("order by i.id desc ").toString())
                .setParameter("partnaireId", partnaireId)
                .setParameter("name", type.getName())
                .list();


问:
Laravel Homestead: requested URL could not be retrieved (working behind proxy)
I'm working on a Windows 10 notebook behind a corporate proxy. Finally I've managed to set up VirtualBox, Vagrant and Homestead.

Unfortunately I'm not able to access my sites in the browser. It says: the requested URL could not be retrieved, unable to determine IP address from host name "test.app".

I've installed the vagrant plugin vagrant-proxyconf and set it up in my Vagrantfile within my Homestead-folder. I've added the following lines to my Vagrantfile:

```<code># -*- mode: ruby -*-
# vi: set ft=ruby :

require 'json'
require 'yaml'

VAGRANTFILE_API_VERSION ||= "2"
confDir = $confDir ||= File.expand_path(File.dirname(__FILE__))

homesteadYamlPath = confDir + "/Homestead.yaml"
homesteadJsonPath = confDir + "/Homestead.json"
afterScriptPath = confDir + "/after.sh"
aliasesPath = confDir + "/aliases"

require File.expand_path(File.dirname(__FILE__) + '/scripts/homestead.rb')

Vagrant.require_version '>= 1.9.0'

Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|

    if Vagrant.has_plugin?("vagrant-proxyconf")
        config.proxy.http     = "http://proxy.my.proxy.com:3128"
        config.proxy.https    = "http://proxy.my.proxy.com:3128"
        config.proxy.no_proxy = "localhost,127.0.0.1,192.168.10.10"
    end
    # ... default configuration
end
</code>```

This is my Homestead.yaml:

```<code>---
ip: "192.168.10.10"
memory: 2048
cpus: 2
provider: virtualbox

authorize: ~/.ssh/id_rsa.pub

keys:
    - ~/.ssh/id_rsa

folders:
    - map: C:/Users/wn00111510/Projekte/ContentAnalyzer
      to: /home/vagrant/contentanalyzer
    - map: C:/Users/wn00111510/Projekte/Test
      to: /home/vagrant/test

sites:
    - map: test.app
      to: /home/vagrant/test

databases:
    - homestead
</code>```

My hosts-file has only one entry:

```<code>192.168.10.10    test.app
</code>```

The machine is running and I'm able to login into my virtual machine via vagrant ssh. vagrant reload --provision does not change something.

During booting there is a warning about a connection reset:

```<code>...
Booting VM...
Waiting for machine to boot. THis may take a few minutes...
SSH address: 127.0.0.1:2222
SSH username: vagrant
SSH auth method: private key
Warning: Connection reset. Retrying...
Warning: Remote Connection disconnect. Retrying...
Warning: Connection reset. Retrying...
Warning: Remote Connection disconnect. Retrying...
Warning: Connection reset. Retrying...
Machine booted and ready!
...
</code>```

Any ideas?

答:
I'm no expert on proxies, but since this is local to your machine you should be able to just bypass any proxy. Have you tried without the proxy plugin?.

The errors here:

```<code>Warning: Connection reset. Retrying...
Warning: Remote Connection disconnect. Retrying...
</code>```

Are usually no big deal as long as the machine connects in a reasonable time.

Since you're only mapping 1 site to the machine, you should also be able to bypass DNS completely by using http://localhost:8000 (or different port that Vagrant mapped to 80 during the vagrant up process).

Body:
I'm working on a Windows 10 notebook behind a corporate proxy. Finally I've managed to set up VirtualBox, Vagrant and Homestead.

Unfortunately I'm not able to access my sites in the browser. It says: the requested URL could not be retrieved, unable to determine IP address from host name "test.app".

I've installed the vagrant plugin vagrant-proxyconf and set it up in my Vagrantfile within my Homestead-folder. I've added the following lines to my Vagrantfile:

# -*- mode: ruby -*-
# vi: set ft=ruby :

require 'json'
require 'yaml'

VAGRANTFILE_API_VERSION ||= "2"
confDir = $confDir ||= File.expand_path(File.dirname(__FILE__))

homesteadYamlPath = confDir + "/Homestead.yaml"
homesteadJsonPath = confDir + "/Homestead.json"
afterScriptPath = confDir + "/after.sh"
aliasesPath = confDir + "/aliases"

require File.expand_path(File.dirname(__FILE__) + '/scripts/homestead.rb')

Vagrant.require_version '>= 1.9.0'

Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|

    if Vagrant.has_plugin?("vagrant-proxyconf")
        config.proxy.http     = "http://proxy.my.proxy.com:3128"
        config.proxy.https    = "http://proxy.my.proxy.com:3128"
        config.proxy.no_proxy = "localhost,127.0.0.1,192.168.10.10"
    end
    # ... default configuration
end

This is my Homestead.yaml:

---
ip: "192.168.10.10"
memory: 2048
cpus: 2
provider: virtualbox

authorize: ~/.ssh/id_rsa.pub

keys:
    - ~/.ssh/id_rsa

folders:
    - map: C:/Users/wn00111510/Projekte/ContentAnalyzer
      to: /home/vagrant/contentanalyzer
    - map: C:/Users/wn00111510/Projekte/Test
      to: /home/vagrant/test

sites:
    - map: test.app
      to: /home/vagrant/test

databases:
    - homestead

My hosts-file has only one entry:

192.168.10.10    test.app

The machine is running and I'm able to login into my virtual machine via vagrant ssh. vagrant reload --provision does not change something.

During booting there is a warning about a connection reset:

...
Booting VM...
Waiting for machine to boot. THis may take a few minutes...
SSH address: 127.0.0.1:2222
SSH username: vagrant
SSH auth method: private key
Warning: Connection reset. Retrying...
Warning: Remote Connection disconnect. Retrying...
Warning: Connection reset. Retrying...
Warning: Remote Connection disconnect. Retrying...
Warning: Connection reset. Retrying...
Machine booted and ready!
...

Any ideas?

Body:
I'm no expert on proxies, but since this is local to your machine you should be able to just bypass any proxy. Have you tried without the proxy plugin?.

The errors here:

Warning: Connection reset. Retrying...
Warning: Remote Connection disconnect. Retrying...

Are usually no big deal as long as the machine connects in a reasonable time.

Since you're only mapping 1 site to the machine, you should also be able to bypass DNS completely by using http://localhost:8000 (or different port that Vagrant mapped to 80 during the vagrant up process).


问:
Using foreach with ArrayList - automatic casting?
```<code>ArrayList x=new ArrayList();
x.Add(10);
x.Add("SS");

foreach(string s in x)
{
}
</code>```

Does it mean that when foreach is run it tries to cast element of array list to type in foreach expression?

答:
Yes, if an element is not convertible to the type, you'll get an InvalidCastException. In your case, you cannot cast boxed int to string causing an exception to be thrown.

Essentially, it's equivalent to:

```<code>foreach (object __o in list) {
    string s = (string)__o;
    // loop body
}
</code>```

Body:
ArrayList x=new ArrayList();
x.Add(10);
x.Add("SS");

foreach(string s in x)
{
}

Does it mean that when foreach is run it tries to cast element of array list to type in foreach expression?

Body:
Yes, if an element is not convertible to the type, you'll get an InvalidCastException. In your case, you cannot cast boxed int to string causing an exception to be thrown.

Essentially, it's equivalent to:

foreach (object __o in list) {
    string s = (string)__o;
    // loop body
}


问:
WPF: How can I make the view dynamic?
I have the following xaml: What is needed that the following xaml must be filled dynamic at runtime, but how? The MainWorkspaceViewModel has a property named "View". This property is of type object, so I can set every view in it.</p>

```<code><UserControl x:Class="DesignerWorkspace.Views.MainWorkspaceView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:DesignerWorkspace.Views"
             xmlns:vm="clr-namespace:DesignerWorkspace.ViewModels"
             mc:Ignorable="d"
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
        <ContentControl Content="{Binding View}"/>
    </Grid>
</UserControl>
</code>```

答:
There are countless ways to do this.
First you have to identify if you are using any toolkit that does this for you.
After identifying just check how this toolkit was set up and how it is used.

There is a very simple way to do this without any toolkit and the one I am going to show you so that you understand how it works.

note that my example is how to create from a new one, it may not be your case, but it's just to understand (feel free to create a new one and see how it works)

first create a ViewModelBase that implements INotifyPropertyChanged, preferably make this abstract class
ViewModelBase class

```<code>public abstract class ViewModelBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    public virtual ICommand NavigateCommand => new RelayCommand(Navigate);

    protected virtual void Navigate(object param)
    {

    }

}
</code>```

then create your MainViewModel, have it inherit the ViewModelBase, and create a property for it to be assigned its ViewModels

```<code>public class MainViewModel: ViewModelBase
{
    private ViewModelBase _currentViewModel;

    public ViewModelBase CurrentViewModel
    {
        get => _currentViewModel;
        set
        {
            if (_currentViewModel == value)
                return;
            _currentViewModel = value;

            OnPropertyChanged(nameof(CurrentViewModel));
        }
    }

    public MainViewModel()
    {

    }

    protected override void Navigate(object args)
    {
        var namespaceName = "YourNameSpace.";
        var className = args.ToString();
        var fullClassName = string.Concat(namespaceName, (string)className);
        if (string.IsNullOrEmpty(fullClassName))
            return;
        var tipo = Type.GetType(fullClassName);
        if (tipo == null)
            return;

        var myObj = Activator.CreateInstance(tipo) as ViewModelBase;
        if (myObj != null)
            CurrentViewModel = (ViewModelBase)myObj;

    }

}
</code>```

you should note that the MainViewModel has an overridden method of the ViewModelBase (Navigate), it is this method that will be used to open other ViewModels from a simple parameter, a string with the name of the ViewModel that wants to open

now you add to your MainWindow your content, in my example, a menu and the content that will be populated with the ViewModels

```<code><Window x:Class="YourNameSpace.MainWindow"
        .......
        Title="MainWindow"
        DataContext="{StaticResource MainViewModel}" >
<Grid>
    .....
    <!--In the Menu, how to open a View -->
    <MenuItem Header="Open ViewA" Command="{Binding NavigateCommand}" CommandParameter="ViewModelA"  />
    .......
    <!-- Your Content Control  -->
    <ContentControl
            HorizontalAlignment="Center"
            VerticalAlignment="Top"
            HorizontalContentAlignment="Center"
            VerticalContentAlignment="Top"
            ClipToBounds="True"
            Content="{Binding CurrentViewModel}" >
    </ContentControl>
.....
</Window>
</code>```

Create your views.
Example:

```<code><UserControl x:Class="YourNameSpace.ucViewA"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             >
    <Grid Background="White">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <Grid  Grid.Row="1">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition Width="*"/>
                <ColumnDefinition Width="Auto"/>
            </Grid.ColumnDefinitions>
            <Label Grid.Column="0" Content="this is the ViewA" Margin="5" />
            <Button Grid.Column="2" Content="Open View B"
                    Command="{Binding DataContext.NavigateCommand, RelativeSource={RelativeSource AncestorType={x:Type Window}}, Mode=OneWay}"
                    CommandParameter="ViewModelB" Margin="5" />
        </Grid>

        <DataGrid Grid.Row="2" ColumnWidth="*"  Margin="5"
                                   IsReadOnly="True"
                                   AutoGenerateColumns="False"
                                   SelectionMode="Single"
                                   HorizontalContentAlignment="Center"

                                   ScrollViewer.CanContentScroll="True"
                                   ScrollViewer.VerticalScrollBarVisibility="Auto"
                                   ScrollViewer.HorizontalScrollBarVisibility="Auto">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Column 1"   MinWidth="50" Width="Auto"/>
                <DataGridTextColumn Header="Column 2"   MinWidth="140" Width="Auto"/>
                <DataGridTextColumn Header="Column 3"   MinWidth="240" Width="*"/>
                <DataGridTextColumn Header="Column 4"   MinWidth="70" Width="Auto"/>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</UserControl>
</code>```

Now in the app.xaml file let's say which ViewModel belongs to which UserControl

```<code><Application x:Class="YourNameSpace.App"
             ...
             xmlns:local="clr-namespace:YourNameSpace"
             StartupUri="MainWindow.xaml">
    <Application.Resources>

        <local:MainViewModel x:Key="MainViewModel"  />

        <DataTemplate DataType="{x:Type local:ViewModelA}">
            <local:ucViewA />
        </DataTemplate>
        <DataTemplate DataType="{x:Type local:ViewModelB}">
            <local:ucViewB />
        </DataTemplate>

    </Application.Resources>
</Application>
</code>```

to open a View from another view use the following:

```<code><Button Content="Open View A"
        Command="{Binding DataContext.NavigateCommand, RelativeSource={RelativeSource AncestorType={x:Type Window}}, Mode=OneWay}"
        CommandParameter="ViewModelA" Margin="5" />
</code>```

Edit: I forgot to say, your ViewModel must have at least one constructor (empty) so no problem occurs

Title: WPF: How can I make the view dynamic?

Body:
I have the following xaml: What is needed that the following xaml must be filled dynamic at runtime, but how? The MainWorkspaceViewModel has a property named "View". This property is of type object, so I can set every view in it.

<UserControl x:Class="DesignerWorkspace.Views.MainWorkspaceView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:DesignerWorkspace.Views"
             xmlns:vm="clr-namespace:DesignerWorkspace.ViewModels"
             mc:Ignorable="d"
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
        <ContentControl Content="{Binding View}"/>
    </Grid>
</UserControl>

Body:
There are countless ways to do this.
First you have to identify if you are using any toolkit that does this for you.
After identifying just check how this toolkit was set up and how it is used.

There is a very simple way to do this without any toolkit and the one I am going to show you so that you understand how it works.

note that my example is how to create from a new one, it may not be your case, but it's just to understand (feel free to create a new one and see how it works)

first create a ViewModelBase that implements INotifyPropertyChanged, preferably make this abstract class
ViewModelBase class

public abstract class ViewModelBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    public virtual ICommand NavigateCommand => new RelayCommand(Navigate);

    protected virtual void Navigate(object param)
    {

    }

}

then create your MainViewModel, have it inherit the ViewModelBase, and create a property for it to be assigned its ViewModels

public class MainViewModel: ViewModelBase
{
    private ViewModelBase _currentViewModel;

    public ViewModelBase CurrentViewModel
    {
        get => _currentViewModel;
        set
        {
            if (_currentViewModel == value)
                return;
            _currentViewModel = value;

            OnPropertyChanged(nameof(CurrentViewModel));
        }
    }

    public MainViewModel()
    {

    }

    protected override void Navigate(object args)
    {
        var namespaceName = "YourNameSpace.";
        var className = args.ToString();
        var fullClassName = string.Concat(namespaceName, (string)className);
        if (string.IsNullOrEmpty(fullClassName))
            return;
        var tipo = Type.GetType(fullClassName);
        if (tipo == null)
            return;

        var myObj = Activator.CreateInstance(tipo) as ViewModelBase;
        if (myObj != null)
            CurrentViewModel = (ViewModelBase)myObj;

    }

}

you should note that the MainViewModel has an overridden method of the ViewModelBase (Navigate), it is this method that will be used to open other ViewModels from a simple parameter, a string with the name of the ViewModel that wants to open

now you add to your MainWindow your content, in my example, a menu and the content that will be populated with the ViewModels

<Window x:Class="YourNameSpace.MainWindow"
        .......
        Title="MainWindow"
        DataContext="{StaticResource MainViewModel}" >
<Grid>
    .....
    <!--In the Menu, how to open a View -->
    <MenuItem Header="Open ViewA" Command="{Binding NavigateCommand}" CommandParameter="ViewModelA"  />
    .......
    <!-- Your Content Control  -->
    <ContentControl
            HorizontalAlignment="Center"
            VerticalAlignment="Top"
            HorizontalContentAlignment="Center"
            VerticalContentAlignment="Top"
            ClipToBounds="True"
            Content="{Binding CurrentViewModel}" >
    </ContentControl>
.....
</Window>

Create your views.
Example:

<UserControl x:Class="YourNameSpace.ucViewA"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             >
    <Grid Background="White">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <Grid  Grid.Row="1">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition Width="*"/>
                <ColumnDefinition Width="Auto"/>
            </Grid.ColumnDefinitions>
            <Label Grid.Column="0" Content="this is the ViewA" Margin="5" />
            <Button Grid.Column="2" Content="Open View B"
                    Command="{Binding DataContext.NavigateCommand, RelativeSource={RelativeSource AncestorType={x:Type Window}}, Mode=OneWay}"
                    CommandParameter="ViewModelB" Margin="5" />
        </Grid>

        <DataGrid Grid.Row="2" ColumnWidth="*"  Margin="5"
                                   IsReadOnly="True"
                                   AutoGenerateColumns="False"
                                   SelectionMode="Single"
                                   HorizontalContentAlignment="Center"

                                   ScrollViewer.CanContentScroll="True"
                                   ScrollViewer.VerticalScrollBarVisibility="Auto"
                                   ScrollViewer.HorizontalScrollBarVisibility="Auto">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Column 1"   MinWidth="50" Width="Auto"/>
                <DataGridTextColumn Header="Column 2"   MinWidth="140" Width="Auto"/>
                <DataGridTextColumn Header="Column 3"   MinWidth="240" Width="*"/>
                <DataGridTextColumn Header="Column 4"   MinWidth="70" Width="Auto"/>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</UserControl>

Now in the app.xaml file let's say which ViewModel belongs to which UserControl

<Application x:Class="YourNameSpace.App"
             ...
             xmlns:local="clr-namespace:YourNameSpace"
             StartupUri="MainWindow.xaml">
    <Application.Resources>

        <local:MainViewModel x:Key="MainViewModel"  />

        <DataTemplate DataType="{x:Type local:ViewModelA}">
            <local:ucViewA />
        </DataTemplate>
        <DataTemplate DataType="{x:Type local:ViewModelB}">
            <local:ucViewB />
        </DataTemplate>

    </Application.Resources>
</Application>

to open a View from another view use the following:

<Button Content="Open View A"
        Command="{Binding DataContext.NavigateCommand, RelativeSource={RelativeSource AncestorType={x:Type Window}}, Mode=OneWay}"
        CommandParameter="ViewModelA" Margin="5" />

Edit: I forgot to say, your ViewModel must have at least one constructor (empty) so no problem occurs


问:
JavaScript does not work when I put it on the server
I have a code that when I run it from any part of the PC without putting it on the server it works perfectly, but when I put it on the server and I call it, it gives me the following error:

Uncaught ReferenceError: crearLienzo is not defined
    at onload ((index):81)

I do not understand why this happens. Thank you all!

```<code><html>
<head>
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<script type="text/javascript" >
    var movimientos = new Array();
    var pulsado;
    function crearLienzo() {
    var canvasDiv = document.getElementById('lienzo');
canvas = document.createElement('canvas');
canvas.setAttribute('width', 200);
canvas.setAttribute('height', 200);
canvas.setAttribute('id', 'canvas');
canvasDiv.appendChild(canvas);
if(typeof G_vmlCanvasManager != 'undefined') {
    canvas = G_vmlCanvasManager.initElement(canvas);
}
context = canvas.getContext("2d");

    $('#canvas').mousedown(function(e){
      pulsado = true;
      movimientos.push([e.pageX - this.offsetLeft,
          e.pageY - this.offsetTop,
          false]);
      repinta();
    });

    $('#canvas').mousemove(function(e){
      if(pulsado){
          movimientos.push([e.pageX - this.offsetLeft,
              e.pageY - this.offsetTop,
              true]);
        repinta();
      }
    });

    $('#canvas').mouseup(function(e){
      pulsado = false;
    });

    $('#canvas').mouseleave(function(e){
      pulsado = false;
    });
    repinta();

}

    function repinta() {
        // función para dibujar en el lienzo los movimientos del ratón que hemos
        // recogido en la variable "movimientos"
         canvas.width = canvas.width; // Limpia el lienzo

  context.strokeStyle = "#0000a0";
  context.lineJoin = "round";
  context.lineWidth = 6;

  for(var i=0; i < movimientos.length; i++)
  {
    context.beginPath();
    if(movimientos[i][2] && i){
      context.moveTo(movimientos[i-1][0], movimientos[i-1][1]);
     }else{
      context.moveTo(movimientos[i][0], movimientos[i][1]);
     }
     context.lineTo(movimientos[i][0], movimientos[i][1]);
     context.closePath();
     context.stroke();
  }
}
function convertCanvasToImage(canvas) {
       var image = new Image();
       image.src = canvas[0].toDataURL("image/png");
        alert(image);
       return image;
}
</script>
</head>
<body style="background: #eee;" onload="crearLienzo()">
<div id="lienzo" style="width: 200px; height: 200px; background: #fff;"></div>
<button type="button" onclick="convertCanvasToImage($('#canvas'));">aa</button>

</body>
</html>
</code>```

答:
Put your script tag inside body to load it first</p>

```<code>    <html>
    <head>
    <script type="text/javascript" src="jquery-3.2.1.min.js"></script>

    </head>
    <body style="background: #eee;" onload="crearLienzo()">
<script type="text/javascript" >
        var movimientos = new Array();
        var pulsado;
        function crearLienzo() {
        var canvasDiv = document.getElementById('lienzo');
    canvas = document.createElement('canvas');
    canvas.setAttribute('width', 200);
    canvas.setAttribute('height', 200);
    canvas.setAttribute('id', 'canvas');
    canvasDiv.appendChild(canvas);
    if(typeof G_vmlCanvasManager != 'undefined') {
        canvas = G_vmlCanvasManager.initElement(canvas);
    }
    context = canvas.getContext("2d");

        $('#canvas').mousedown(function(e){
          pulsado = true;
          movimientos.push([e.pageX - this.offsetLeft,
              e.pageY - this.offsetTop,
              false]);
          repinta();
        });

        $('#canvas').mousemove(function(e){
          if(pulsado){
              movimientos.push([e.pageX - this.offsetLeft,
                  e.pageY - this.offsetTop,
                  true]);
            repinta();
          }
        });

        $('#canvas').mouseup(function(e){
          pulsado = false;
        });

        $('#canvas').mouseleave(function(e){
          pulsado = false;
        });
        repinta();

    }

        function repinta() {
            // función para dibujar en el lienzo los movimientos del ratón que hemos
            // recogido en la variable "movimientos"
             canvas.width = canvas.width; // Limpia el lienzo

      context.strokeStyle = "#0000a0";
      context.lineJoin = "round";
      context.lineWidth = 6;

      for(var i=0; i < movimientos.length; i++)
      {
        context.beginPath();
        if(movimientos[i][2] && i){
          context.moveTo(movimientos[i-1][0], movimientos[i-1][1]);
         }else{
          context.moveTo(movimientos[i][0], movimientos[i][1]);
         }
         context.lineTo(movimientos[i][0], movimientos[i][1]);
         context.closePath();
         context.stroke();
      }
    }
    function convertCanvasToImage(canvas) {
           var image = new Image();
           image.src = canvas[0].toDataURL("image/png");
            alert(image);
           return image;
    }
    </script>
    <div id="lienzo" style="width: 200px; height: 200px; background: #fff;"></div>
    <button type="button" onclick="convertCanvasToImage($('#canvas'));">aa</button>

    </body>
    </html>
</code>```

Body:
I have a code that when I run it from any part of the PC without putting it on the server it works perfectly, but when I put it on the server and I call it, it gives me the following error:

Uncaught ReferenceError: crearLienzo is not defined
    at onload ((index):81)

I do not understand why this happens. Thank you all!

<button type="button" onclick="convertCanvasToImage($('#canvas'));">aa</button>

Body:
Put your script tag inside body to load it first

    <html>
    <head>
    <script type="text/javascript" src="jquery-3.2.1.min.js"></script>

    </head>
    <body style="background: #eee;" onload="crearLienzo()">
<script type="text/javascript" >
        var movimientos = new Array();
        var pulsado;
        function crearLienzo() {
        var canvasDiv = document.getElementById('lienzo');
    canvas = document.createElement('canvas');
    canvas.setAttribute('width', 200);
    canvas.setAttribute('height', 200);
    canvas.setAttribute('id', 'canvas');
    canvasDiv.appendChild(canvas);
    if(typeof G_vmlCanvasManager != 'undefined') {
        canvas = G_vmlCanvasManager.initElement(canvas);
    }
    context = canvas.getContext("2d");

        $('#canvas').mousedown(function(e){
          pulsado = true;
          movimientos.push([e.pageX - this.offsetLeft,
              e.pageY - this.offsetTop,
              false]);
          repinta();
        });

        $('#canvas').mousemove(function(e){
          if(pulsado){
              movimientos.push([e.pageX - this.offsetLeft,
                  e.pageY - this.offsetTop,
                  true]);
            repinta();
          }
        });

        $('#canvas').mouseup(function(e){
          pulsado = false;
        });

        $('#canvas').mouseleave(function(e){
          pulsado = false;
        });
        repinta();

    }

        function repinta() {
            // función para dibujar en el lienzo los movimientos del ratón que hemos
            // recogido en la variable "movimientos"
             canvas.width = canvas.width; // Limpia el lienzo

      context.strokeStyle = "#0000a0";
      context.lineJoin = "round";
      context.lineWidth = 6;

      for(var i=0; i < movimientos.length; i++)
      {
        context.beginPath();
        if(movimientos[i][2] && i){
          context.moveTo(movimientos[i-1][0], movimientos[i-1][1]);
         }else{
          context.moveTo(movimientos[i][0], movimientos[i][1]);
         }
         context.lineTo(movimientos[i][0], movimientos[i][1]);
         context.closePath();
         context.stroke();
      }
    }
    function convertCanvasToImage(canvas) {
           var image = new Image();
           image.src = canvas[0].toDataURL("image/png");
            alert(image);
           return image;
    }
    </script>
    <div id="lienzo" style="width: 200px; height: 200px; background: #fff;"></div>
    <button type="button" onclick="convertCanvasToImage($('#canvas'));">aa</button>

    </body>
    </html>


Title: Group by continuous indexes in Pandas DataFrame

Body:
I'm working on code for sensors data analysis using python.

I'm taking rows from DataFrame (of gyro data in the example) according to some condition.

import pandas as pd

gyro = pd.read_csv("gyroOutput.csv")
above = gyro[gyro['gyro_z'] > 0.30]

above
Out[162]:
        gyro_x    gyro_y    gyro_z  elapsed
27    0.026632  0.021305  0.305731    4.927
28    0.017044  0.011718  0.344080    5.115
29    0.008522  0.013848  0.380299    5.289
30    0.006392  0.026632  0.412257    5.470
31    0.007457  0.005326  0.448476    5.643
32   -0.004261  0.012783  0.465521    5.822
33   -0.001065  0.000000  0.452737    6.002
34    0.009587  0.006392  0.445281    6.181
35    0.010653  0.001065  0.412257    6.361
36    0.006392  0.003196  0.373908    6.543
37   -0.006392  0.007457  0.320645    6.722
108  -0.036219  0.052198  0.323840   19.470
109  -0.061785 -0.001065  0.389887   19.654
110  -0.049002  0.018109  0.453803   19.835
111  -0.038350  0.078830  0.513458   20.015
112  -0.034088  0.011718  0.555003   20.192
113  -0.005326 -0.001065  0.607201   20.374
114   0.009587  0.058590  0.629571   20.553
115   0.038350 -0.029827  0.598679   20.727
116   0.006392  0.013848  0.546481   20.907
117   0.007457  0.030893  0.478304   21.086
118   0.012783 -0.035154  0.446346   21.266
119   0.005326 -0.026632  0.367516   21.444
352   0.007457  0.028762  0.313188   63.284
353   0.006392 -0.011718  0.332363   63.463
354   0.008522  0.030893  0.378169   63.643
355  -0.015979  0.039415  0.409062   63.822
356  -0.009587 -0.022371  0.423975   64.002
357  -0.008522  0.023436  0.450607   64.181
358  -0.011718  0.047937  0.453803   64.361

That result data frame (above) holds groups of continuous indexes rows. For example, lines 27-37.

I want to get all those group's, couldn't find any way to do it using DataFrame.groupby or any other function.

I could iterate over the rows and separate them myself, but maybe there's some simpler way using pandas functions.

Body:
IIUC:

In [294]: df.groupby(df.index.to_series().diff().ne(1).cumsum()).groups
Out[294]:
{1: Int64Index([27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37], dtype='int64'),
 2: Int64Index([108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119], dtype='int64'),
 3: Int64Index([352, 353, 354, 355, 356, 357, 358], dtype='int64')}


问:
Input type="time" on Safari
I've been using:

```<code><input type="time">
</code>```

for most of my pages and testing it on Chrome.
To my dismay, it turns out that on Safari, this input type refers back to a text field. Any idea why it does this?

答:
This appears to be supported from iOS 5.0.

See here:

https://developer.apple.com/library/content/documentation/AppleApplications/Reference/SafariHTMLRef/Articles/InputTypes.html

Title: Input type="time" on Safari

Body:
I've been using:

<input type="time">

for most of my pages and testing it on Chrome.
To my dismay, it turns out that on Safari, this input type refers back to a text field. Any idea why it does this?


问:
Composing object in javascript by passing a list of functionality to a factory function
Using an example from this source

```<code>const barker = (state) => ({
  bark: () => console.log('Woof, I am ' + state.name)
})

const driver = (state) => ({
  drive: () => state.position = state.position + state.speed
})

const murderRobotDog = (name)  => {
  let state = {
    name,
    speed: 100,
    position: 0
  }
  return Object.assign(
        {},
        barker(state),
        driver(state)
    )
}
</code>```

How should I modify this code, to be able to assign functionality based on a parameter passed to the factory function.

For example I could have an array of names like so:

```<code>let properties = ["barker", "driver", "killer" etc... ];
murderRobotDog(name, properties);
</code>```

And it does Object.assign to each of those function names?

I am still learning new syntax, I tried using spread operator like so:

```<code>return Object.assign({}, ...properties(state));
</code>```

Only to come to realization that this is not how any of this works. Can't really figure out how to make a loop out of this either. How should this be done?

答:
You could create a dictionary where the keys form the function names. Then you can just loop over the properties and do the Object.assign:

```<code>const barker = (state) => ({
    bark: () => console.log('Woof, I am ' + state.name)
});

const driver = (state) => ({
    drive: () => state.position = state.position + state.speed
});

let types = {
    barker,
    driver
};

const murderRobotDog = (name, properties) => {
    let state = {
        name,
        speed: 100,
        position: 0
    };

    let obj = {};
    for(let prop of properties) {
        Object.assign(obj, types[prop](state));
    }

    return obj;
}

let properties = ["barker", "driver"];
let result = murderRobotDog('Name', properties);
console.log(result);
result.bark()
</code>```

Output:

```<code>node .\index.js
{ bark: [Function: bark], drive: [Function: drive] }
Woof, I am Name
</code>```

Body:
Using an example from this source

const barker = (state) => ({
  bark: () => console.log('Woof, I am ' + state.name)
})

const driver = (state) => ({
  drive: () => state.position = state.position + state.speed
})

const murderRobotDog = (name)  => {
  let state = {
    name,
    speed: 100,
    position: 0
  }
  return Object.assign(
        {},
        barker(state),
        driver(state)
    )
}

How should I modify this code, to be able to assign functionality based on a parameter passed to the factory function.

For example I could have an array of names like so:

let properties = ["barker", "driver", "killer" etc... ];
murderRobotDog(name, properties);

And it does Object.assign to each of those function names?

I am still learning new syntax, I tried using spread operator like so:

return Object.assign({}, ...properties(state));

Only to come to realization that this is not how any of this works. Can't really figure out how to make a loop out of this either. How should this be done?

Body:
You could create a dictionary where the keys form the function names. Then you can just loop over the properties and do the Object.assign:

const barker = (state) => ({
    bark: () => console.log('Woof, I am ' + state.name)
});

const driver = (state) => ({
    drive: () => state.position = state.position + state.speed
});

let types = {
    barker,
    driver
};

const murderRobotDog = (name, properties) => {
    let state = {
        name,
        speed: 100,
        position: 0
    };

    let obj = {};
    for(let prop of properties) {
        Object.assign(obj, types[prop](state));
    }

    return obj;
}

let properties = ["barker", "driver"];
let result = murderRobotDog('Name', properties);
console.log(result);
result.bark()

Output:

node .\index.js
{ bark: [Function: bark], drive: [Function: drive] }
Woof, I am Name


问:
AVPlayer not stop playing when going back to the previous view
I have two View Controllers a TableViewController where I have a list of musics and a UIViewController where it plays the music. The music automatically plays when the view is loaded and pauses when the pause button is pressed.

However whenever I go back to the previous TableViewController to select another music, the music continues to play. And if i select another music, both of them are playing together.

My Codes:

```<code>var audioplayer = AVPlayer()

override func viewDidLoad() {
        super.viewDidLoad()

    play()
}

func play(){

    var songUrl = songList[selectedItem].url

    audioplayer = AVPlayer(url: songUrl!)

    audioplayer.play()

}
</code>```

答:
Have you tried to use .pause() ? example:

```<code>var audioplayer: AVPlayer? = AVPlayer()

override func viewDidLoad() {
    super.viewDidLoad()

    play()
}

func play(){

    var songUrl = songList[selectedItem].url

    audioplayer = AVPlayer(url: songUrl!)

    audioplayer.play()

}

override func viewDidDisappear(_ animated: Bool) {
    super.viewDidDisappear(animated)
    audioplayer.pause()
    audioplayer = nil
}
</code>```

Body:
I have two View Controllers a TableViewController where I have a list of musics and a UIViewController where it plays the music. The music automatically plays when the view is loaded and pauses when the pause button is pressed.

However whenever I go back to the previous TableViewController to select another music, the music continues to play. And if i select another music, both of them are playing together.

My Codes:

var audioplayer = AVPlayer()

override func viewDidLoad() {
        super.viewDidLoad()

    play()
}

func play(){

    var songUrl = songList[selectedItem].url

    audioplayer = AVPlayer(url: songUrl!)

    audioplayer.play()

}

Body:
Have you tried to use .pause() ? example:

var audioplayer: AVPlayer? = AVPlayer()

override func viewDidLoad() {
    super.viewDidLoad()

    play()
}

func play(){

    var songUrl = songList[selectedItem].url

    audioplayer = AVPlayer(url: songUrl!)

    audioplayer.play()

}

override func viewDidDisappear(_ animated: Bool) {
    super.viewDidDisappear(animated)
    audioplayer.pause()
    audioplayer = nil
}


问:
How to find an object which contains a specific string and a number which is the highest number?
I'm a beginner in Python and I'm trying to use boto (CloudFormation) to list the latest stacks created which contains a string.

```<code>import boto3
client = boto3.client('cloudformation')
stacks = client.list_stacks(
    StackStatusFilter=[
        'CREATE_COMPLETE'
    ]
)

for st in stacks["StackSummaries"]:
    print(st)
</code>```

This is part of the output I get from running the command:

```<code>{u'StackId': 'arn:aws:cloudformation:us-west-2:AWSACCOUNTID:stack/Company-Dev-31/4d501360-d521-11e7-9aff-50a68a0bca9a', u'StackName': 'Company-Dev-31', u'CreationTime': datetime.datetime(2017, 11, 29, 16, 21, 6, 636000, tzinfo=tzutc()), u'StackStatus': 'CREATE_COMPLETE', u'TemplateDescription': 'Company - Formation of Server Machines @ Oregon (us-west-2)'}
{u'StackId': 'arn:aws:cloudformation:us-west-2:AWSACCOUNTID:stack/Company-Dev-30/4d501360-c231-11e7-8aca-50a68a0bca9a', u'StackName': 'Company-Dev-30', u'CreationTime': datetime.datetime(2017, 11, 29, 16, 21, 6, 644000, tzinfo=tzutc()), u'StackStatus': 'CREATE_COMPLETE', u'TemplateDescription': 'Company - Formation of Server Machines @ Oregon (us-west-2)'}
{u'StackId': 'arn:aws:cloudformation:us-west-2:AWSACCOUNTID:stack/Company-Stg-22/bc2b6c10-d41a-11e7-b1ab-50d5ca789eae', u'StackName': 'Company-Stg-22', u'CreationTime': datetime.datetime(2017, 11, 28, 9, 1, 34, 985000, tzinfo=tzutc()), u'StackStatus': 'CREATE_COMPLETE', u'TemplateDescription': 'Company - Formation of Server Machines @ Oregon (us-west-2)'}
{u'StackId': 'arn:aws:cloudformation:us-west-2:AWSACCOUNTID:stack/Company-Prod-US-API-64/0e85cc00-9602-11e7-8c08-50d5ca0184d2', u'StackName': 'Company-Prod-US-API-64', u'CreationTime': datetime.datetime(2017, 9, 10, 8, 28, 43, 598000, tzinfo=tzutc()), u'StackStatus': 'CREATE_COMPLETE', u'TemplateDescription': 'Company - Formation of Server Machines'}
{u'StackId': 'arn:aws:cloudformation:us-west-2:AWSACCOUNTID:stack/Company-Prod-US-API-63/1ba257c0-9600-11e7-821f-503f20f2ad4a', u'StackName': 'Company-Prod-US-API-63', u'CreationTime': datetime.datetime(2017, 9, 10, 8, 14, 46, 602000, tzinfo=tzutc()), u'StackStatus': 'CREATE_COMPLETE', u'TemplateDescription': 'Company - Formation of Server Machines'}
{u'StackId': 'arn:aws:cloudformation:us-west-2:AWSACCOUNTID:stack/Company-Prod-US-API-61/9252a9d0-2ace-11e7-8eea-503ac9ec2461', u'StackName': 'Company-Prod-US-API-61', u'CreationTime': datetime.datetime(2017, 4, 26, 22, 20, 36, 473000, tzinfo=tzutc()), u'StackStatus': 'CREATE_COMPLETE', u'TemplateDescription': 'Company - Formation of Server Machines'}
{u'StackId': 'arn:aws:cloudformation:us-west-2:AWSACCOUNTID:stack/Company-Prod-US-API-60/1ba83440-2acd-11e7-a0c3-503a90a9c435', u'StackName': 'Company-Prod-US-API-60', u'CreationTime': datetime.datetime(2017, 4, 26, 22, 10, 7, 890000, tzinfo=tzutc()), u'StackStatus': 'CREATE_COMPLETE', u'TemplateDescription': 'Company - Formation of Server Machines'}
</code>```

It seems like the output is already sorted with the newest objects first.

I would like to parse the name of the stack which contains the word "Dev" and where the number is the highest among the rest of the stacks of the same environment (Dev), in this case "Company-Dev-31".

How can it be achieved?

答:
To add to Martin's answer, you can take the number from each entry containing 'Dev' then use a list comprehension to retrieve the entry with the highest number:

```<code>numlist = []

for item in st:
    if 'Dev' in item['StackName']:
        num = int(item['StackName'].split('Dev-')[1])
        numlist.append(num)

result = [i for i in st if ('Dev-%s' % max(numlist)) in i['StackName']]

print(result)
</code>```

Giving:

```<code>[{u'StackId': 'arn:aws:cloudformation:us-west-2:AWSACCOUNTID:stack/Company-Dev-31/4d501360-d521-11e7-9aff-50a68a0bca9a', u'StackName': 'Company-Dev-31', u'CreationTime': datetime.datetime(2017, 11, 29, 16, 21, 6, 636000, tzinfo=tzutc()), u'StackStatus': 'CREATE_COMPLETE', u'TemplateDescription': 'Company - Formation of Server Machines @ Oregon (us-west-2)'}]
</code>```

Body:
I'm a beginner in Python and I'm trying to use boto (CloudFormation) to list the latest stacks created which contains a string.

import boto3
client = boto3.client('cloudformation')
stacks = client.list_stacks(
    StackStatusFilter=[
        'CREATE_COMPLETE'
    ]
)

for st in stacks["StackSummaries"]:
    print(st)

This is part of the output I get from running the command:

{u'StackId': 'arn:aws:cloudformation:us-west-2:AWSACCOUNTID:stack/Company-Dev-31/4d501360-d521-11e7-9aff-50a68a0bca9a', u'StackName': 'Company-Dev-31', u'CreationTime': datetime.datetime(2017, 11, 29, 16, 21, 6, 636000, tzinfo=tzutc()), u'StackStatus': 'CREATE_COMPLETE', u'TemplateDescription': 'Company - Formation of Server Machines @ Oregon (us-west-2)'}
{u'StackId': 'arn:aws:cloudformation:us-west-2:AWSACCOUNTID:stack/Company-Dev-30/4d501360-c231-11e7-8aca-50a68a0bca9a', u'StackName': 'Company-Dev-30', u'CreationTime': datetime.datetime(2017, 11, 29, 16, 21, 6, 644000, tzinfo=tzutc()), u'StackStatus': 'CREATE_COMPLETE', u'TemplateDescription': 'Company - Formation of Server Machines @ Oregon (us-west-2)'}
{u'StackId': 'arn:aws:cloudformation:us-west-2:AWSACCOUNTID:stack/Company-Stg-22/bc2b6c10-d41a-11e7-b1ab-50d5ca789eae', u'StackName': 'Company-Stg-22', u'CreationTime': datetime.datetime(2017, 11, 28, 9, 1, 34, 985000, tzinfo=tzutc()), u'StackStatus': 'CREATE_COMPLETE', u'TemplateDescription': 'Company - Formation of Server Machines @ Oregon (us-west-2)'}
{u'StackId': 'arn:aws:cloudformation:us-west-2:AWSACCOUNTID:stack/Company-Prod-US-API-64/0e85cc00-9602-11e7-8c08-50d5ca0184d2', u'StackName': 'Company-Prod-US-API-64', u'CreationTime': datetime.datetime(2017, 9, 10, 8, 28, 43, 598000, tzinfo=tzutc()), u'StackStatus': 'CREATE_COMPLETE', u'TemplateDescription': 'Company - Formation of Server Machines'}
{u'StackId': 'arn:aws:cloudformation:us-west-2:AWSACCOUNTID:stack/Company-Prod-US-API-63/1ba257c0-9600-11e7-821f-503f20f2ad4a', u'StackName': 'Company-Prod-US-API-63', u'CreationTime': datetime.datetime(2017, 9, 10, 8, 14, 46, 602000, tzinfo=tzutc()), u'StackStatus': 'CREATE_COMPLETE', u'TemplateDescription': 'Company - Formation of Server Machines'}
{u'StackId': 'arn:aws:cloudformation:us-west-2:AWSACCOUNTID:stack/Company-Prod-US-API-61/9252a9d0-2ace-11e7-8eea-503ac9ec2461', u'StackName': 'Company-Prod-US-API-61', u'CreationTime': datetime.datetime(2017, 4, 26, 22, 20, 36, 473000, tzinfo=tzutc()), u'StackStatus': 'CREATE_COMPLETE', u'TemplateDescription': 'Company - Formation of Server Machines'}
{u'StackId': 'arn:aws:cloudformation:us-west-2:AWSACCOUNTID:stack/Company-Prod-US-API-60/1ba83440-2acd-11e7-a0c3-503a90a9c435', u'StackName': 'Company-Prod-US-API-60', u'CreationTime': datetime.datetime(2017, 4, 26, 22, 10, 7, 890000, tzinfo=tzutc()), u'StackStatus': 'CREATE_COMPLETE', u'TemplateDescription': 'Company - Formation of Server Machines'}

It seems like the output is already sorted with the newest objects first.

I would like to parse the name of the stack which contains the word "Dev" and where the number is the highest among the rest of the stacks of the same environment (Dev), in this case "Company-Dev-31".

How can it be achieved?

Body:
To add to Martin's answer, you can take the number from each entry containing 'Dev' then use a list comprehension to retrieve the entry with the highest number:

numlist = []

for item in st:
    if 'Dev' in item['StackName']:
        num = int(item['StackName'].split('Dev-')[1])
        numlist.append(num)

result = [i for i in st if ('Dev-%s' % max(numlist)) in i['StackName']]

print(result)

Giving:

[{u'StackId': 'arn:aws:cloudformation:us-west-2:AWSACCOUNTID:stack/Company-Dev-31/4d501360-d521-11e7-9aff-50a68a0bca9a', u'StackName': 'Company-Dev-31', u'CreationTime': datetime.datetime(2017, 11, 29, 16, 21, 6, 636000, tzinfo=tzutc()), u'StackStatus': 'CREATE_COMPLETE', u'TemplateDescription': 'Company - Formation of Server Machines @ Oregon (us-west-2)'}]


问:
AsyncStorage doesnt return anything
I want to store data via asyncstorage in my react-native app, But I have a problem. I using it like that:

```<code> async componentDidMount() {
 console.log("Flag1");
 await AsyncStorage.setItem('name', 'I like to save it.');
 console.log("Flag2");
 }
</code>```

But for some reason I cant reach "Flag2", And I am not getting an error or a data from the await call.
I also tried use try/catch, facing the same problem.

edit I noticed that AsyncStorage works for me only when I just open the emulator, after a couple of uses it stops working.

答:
Your code should work.
I tried

```<code>async componentDidMount(){
  await AsyncStorage.setItem('name', 'I like to save it.');
  console.log(await AsyncStorage.getItem('name')); // I like to save it.
}
</code>```

Try to check that that data is saved by using await AsyncStorage.getItem.

Title: AsyncStorage doesnt return anything

Body:
I want to store data via asyncstorage in my react-native app, But I have a problem. I using it like that:

 async componentDidMount() {
 console.log("Flag1");
 await AsyncStorage.setItem('name', 'I like to save it.');
 console.log("Flag2");
 }

But for some reason I cant reach "Flag2", And I am not getting an error or a data from the await call.
I also tried use try/catch, facing the same problem.

edit I noticed that AsyncStorage works for me only when I just open the emulator, after a couple of uses it stops working.

Body:
Your code should work.
I tried

async componentDidMount(){
  await AsyncStorage.setItem('name', 'I like to save it.');
  console.log(await AsyncStorage.getItem('name')); // I like to save it.
}

Try to check that that data is saved by using await AsyncStorage.getItem.


问:
Customize gradle task properties when dependsOn
I created custom task which should process output of gradle dependencies task ( exactly ./gradlew dependencies --configuration myFlavorDebugRuntimeClasspath). I want to create my custom task for every buildVariant (PassportGenerateTask passportGen = project.tasks.create("pasportGenerate${variantName}", PassportGenerateTask)).

But i cant customize dependenciesReportTask properties for every passportGen. When i call passportGen for speciefic buildVariant it use dependenciesReportTask.setProperty("configurations", ...) of last build variant among all (project.android.applicationVariants.all).

For examlpe if I have following build variants (googleDebug googleRelease samsungDebug samsungRelease) and call passportGen task (./gradlew pasportGenerateGoogleDebug) it will use wrong properties for dependenciesReportTask (configuration will be samsungReleaseRuntimeClasspath configuration )

```<code>class AppPlugin implements Plugin<Project> {

    void apply(Project project) {

        project.afterEvaluate {
            // Create tasks for each Build Variant
            project.android.applicationVariants.all { ApplicationVariant variant ->
                def variantName = variant.name.capitalize()
                def variantOutput = variant.outputs.first()

                //Generating configuration name for dependency report
                def configurationName = ""
                if (variant.productFlavors.size() > 0) {
                    configurationName += variant.productFlavors.get(0).name
                    configurationName += variant.getBuildType().name.capitalize()
                } else {
                    configurationName += variant.getBuildType().name
                }
                configurationName += "RuntimeClasspath"

                def configurations = project.configurations.collect()

                configurations.removeAll {
                    !it.name.equals(configurationName)
                }

                //prepare file for output of "dependencies" tasks
                def depReportFileName = "dependeciesReport${variantName}.txt"
                def dependenciesReportOutputFile = new File(depReportFileName)

                //Get "dependencies" task from all project tasks
                def dependenciesReportTask = project.tasks["dependencies"]
                dependenciesReportTask.setProperty("configurations", configurations)
                dependenciesReportTask.setProperty("outputFile", dependenciesReportOutputFile)

                //create cutom task for every buildVariant which depends on "dependencies" task
                PassportGenerateTask passportGen = project.tasks.create("pasportGenerate${variantName}", PassportGenerateTask)
                passportGen.variant = variant
                passportGen.configuration = configurations.collect().get(0)

                //add dependency on "dependencies"
                passportGen.dependsOn dependenciesReportTask

            }
        }
    }
}
</code>```

The only way i can achieve what i want is call:

```<code>def dependenciesReportTask = project.tasks["dependencies"]
dependenciesReportTask.setProperty("configurations", configurations)
dependenciesReportTask.setProperty("outputFile", dependenciesReport)
dependenciesReportTask.execute()
</code>```

inside my custom PassportGenerateTask task main action method (@TaskAction) but calling execute inside other task is deprecated feature and will be removed in gradle 5.0

答:
It is not only deprecated, it is purely internal implementation detail that most probably does not do what you expect it does and almost always produces many more problems than it tries to solve and actually fails.

You most probably also shouldn't rape the dependencies task. If you need multiple such tasks with different configuration, simply create new tasks of type DependencyReportTask and configure them however you like.

Body:
I created custom task which should process output of gradle dependencies task ( exactly ./gradlew dependencies --configuration myFlavorDebugRuntimeClasspath). I want to create my custom task for every buildVariant (PassportGenerateTask passportGen = project.tasks.create("pasportGenerate${variantName}", PassportGenerateTask)).

But i cant customize dependenciesReportTask properties for every passportGen. When i call passportGen for speciefic buildVariant it use dependenciesReportTask.setProperty("configurations", ...) of last build variant among all (project.android.applicationVariants.all).

For examlpe if I have following build variants (googleDebug googleRelease samsungDebug samsungRelease) and call passportGen task (./gradlew pasportGenerateGoogleDebug) it will use wrong properties for dependenciesReportTask (configuration will be samsungReleaseRuntimeClasspath configuration )

class AppPlugin implements Plugin<Project> {

    void apply(Project project) {

        project.afterEvaluate {
            // Create tasks for each Build Variant
            project.android.applicationVariants.all { ApplicationVariant variant ->
                def variantName = variant.name.capitalize()
                def variantOutput = variant.outputs.first()

                //Generating configuration name for dependency report
                def configurationName = ""
                if (variant.productFlavors.size() > 0) {
                    configurationName += variant.productFlavors.get(0).name
                    configurationName += variant.getBuildType().name.capitalize()
                } else {
                    configurationName += variant.getBuildType().name
                }
                configurationName += "RuntimeClasspath"

                def configurations = project.configurations.collect()

                configurations.removeAll {
                    !it.name.equals(configurationName)
                }

                //prepare file for output of "dependencies" tasks
                def depReportFileName = "dependeciesReport${variantName}.txt"
                def dependenciesReportOutputFile = new File(depReportFileName)

                //Get "dependencies" task from all project tasks
                def dependenciesReportTask = project.tasks["dependencies"]
                dependenciesReportTask.setProperty("configurations", configurations)
                dependenciesReportTask.setProperty("outputFile", dependenciesReportOutputFile)

                //create cutom task for every buildVariant which depends on "dependencies" task
                PassportGenerateTask passportGen = project.tasks.create("pasportGenerate${variantName}", PassportGenerateTask)
                passportGen.variant = variant
                passportGen.configuration = configurations.collect().get(0)

                //add dependency on "dependencies"
                passportGen.dependsOn dependenciesReportTask

            }
        }
    }
}

The only way i can achieve what i want is call:

def dependenciesReportTask = project.tasks["dependencies"]
dependenciesReportTask.setProperty("configurations", configurations)
dependenciesReportTask.setProperty("outputFile", dependenciesReport)
dependenciesReportTask.execute()

inside my custom PassportGenerateTask task main action method (@TaskAction) but calling execute inside other task is deprecated feature and will be removed in gradle 5.0


问:
How to tell gradle to install npm within the project on build?
My angular 4 UI for a java web application depends only on the below few bundles. I ran the below commands from webapps root. App works fine. I want to know the best practices as I'm new to angular.

```<code>npm install rxjs
npm install @angular/core@4.4.6 @angular/common@4.4.6 @angular/compiler@4.4.6 @angular/platform-browser@4.4.6 @angular/platform-browser-dynamic@4.4.6 @angular/router@4.4.6 @angular/forms@4.4.6 --save
npm install typescript@2.4.2 --save
npm install plugin-typescript@5.2.7 --save
</code>```

I'm referring the installed bundles from systemjs.config.js like below:

```<code>paths: {
       'npm:' : 'node_modules/'
},
map: {
       '@angular/core' : 'npm:@angular/core/bundles/core.umd.js'
       .
       .
}
</code>```

Queries:

The app should not be heavy, could not include the entire node_modules in war

If I keep node_modules in project root instead of webapps, how do I refer it from systemjs.config.js

I just want those bundles and not the huge file stack that gets downloaded while running npm install @angular/cli

If we can use global node_modules, how to refer to that from systemjs.config.js (I prefer keeping it within project not to disturb other applications in the server using different versions)

Finally, what should I include in build.gradle to download the required bundles while gradle builds

答:
As @Oliver Charlesworth said, Gradle has his limitations, but you can create a custom gradle task.

Example:

```<code>task npmInstall(type: Exec) {
    workingDir 'src/main/webapp'
    commandLine 'npm', 'install'
}
</code>```

Add the build dependency to your war build step

```<code>war {
    dependsOn npmBuild
}
</code>```

Body:
My angular 4 UI for a java web application depends only on the below few bundles. I ran the below commands from webapps root. App works fine. I want to know the best practices as I'm new to angular.

npm install rxjs
npm install @angular/core@4.4.6 @angular/common@4.4.6 @angular/compiler@4.4.6 @angular/platform-browser@4.4.6 @angular/platform-browser-dynamic@4.4.6 @angular/router@4.4.6 @angular/forms@4.4.6 --save
npm install typescript@2.4.2 --save
npm install plugin-typescript@5.2.7 --save

I'm referring the installed bundles from systemjs.config.js like below:

paths: {
       'npm:' : 'node_modules/'
},
map: {
       '@angular/core' : 'npm:@angular/core/bundles/core.umd.js'
       .
       .
}

Queries:

The app should not be heavy, could not include the entire node_modules in war

If I keep node_modules in project root instead of webapps, how do I refer it from systemjs.config.js

I just want those bundles and not the huge file stack that gets downloaded while running npm install @angular/cli

If we can use global node_modules, how to refer to that from systemjs.config.js (I prefer keeping it within project not to disturb other applications in the server using different versions)

Finally, what should I include in build.gradle to download the required bundles while gradle builds

Body:
As @Oliver Charlesworth said, Gradle has his limitations, but you can create a custom gradle task.

Example:

task npmInstall(type: Exec) {
    workingDir 'src/main/webapp'
    commandLine 'npm', 'install'
}

Add the build dependency to your war build step

war {
    dependsOn npmBuild
}


问:
stepping into application.run(...) doesn't show code to step through
I want to share an experience here so you don't spend too much time...
I use Excel within Microsoft Office Professional Plus 2016.

I have an Excel file fileA.xlsb which does

open fileB.xlsb from a source folder

modify something in fileB

save fileB.xlsb to another folder (target folder)

call function funcB in fileB.xlsb with Application.Run "'" & fileBname & "'" & "!funcB", [parameter...]

save & close fileB.xlsb

```<code>            Set appO = Application()
            udfTmp = appO.Run("'" & strFullTgtFilename & "'" & "!reCalc_npFB", _
                                dummyColl, _
                                colVarsAv_dtMtrx_TotEff, _
                                colVarsAv_dtMtrx_iFlag, _
                                PPlistsSheetName, _
                                LRC_logFilename, _
                                algID, _
                                varErrMsg)
</code>```

When I step through the code in fileA everything's fine until Application.Run...
Pressing F8 doesn't show the code in fileB/funcB but keeps the Application.Run statement highlighted. I can keep on pressing F8 or press F5 until funcB ended and stepping through fileA continues as usual. And: funcB is executed correctly.

答:
After spending a good number of hours I found a solution (or rather a workaround):
I changed the code in fileA:

open fileB.xlsb from the source folder

modify something in fileB

save fileB.xlsb to another folder (target folder)

close fileB.xlsb

re-open fileB.xlsb from it's target (!) folder

call Application.Run "'" & fileBname & "'" & "!funcB",

=> stepping in with F8 works nicely as expected

save & close fileB.xlsb

Body:
I want to share an experience here so you don't spend too much time...
I use Excel within Microsoft Office Professional Plus 2016.

I have an Excel file fileA.xlsb which does

open fileB.xlsb from a source folder

modify something in fileB

save fileB.xlsb to another folder (target folder)

call function funcB in fileB.xlsb with Application.Run "'" & fileBname & "'" & "!funcB", [parameter...]

save & close fileB.xlsb

            Set appO = Application()
            udfTmp = appO.Run("'" & strFullTgtFilename & "'" & "!reCalc_npFB", _
                                dummyColl, _
                                colVarsAv_dtMtrx_TotEff, _
                                colVarsAv_dtMtrx_iFlag, _
                                PPlistsSheetName, _
                                LRC_logFilename, _
                                algID, _
                                varErrMsg)

When I step through the code in fileA everything's fine until Application.Run...
Pressing F8 doesn't show the code in fileB/funcB but keeps the Application.Run statement highlighted. I can keep on pressing F8 or press F5 until funcB ended and stepping through fileA continues as usual. And: funcB is executed correctly.


问:
Any plans for "do"/Action LINQ operator?
Here's a simple method with a foreach loop:

```<code>IEnumerable<XElement> FieldsToXElements(object instance)
{
    var fieldElements = new List<XElement>();

    foreach (var field in instance.GetType().GetFields(instance))
    {
        fieldElements.Add(new XElement(field.Name, field.GetValue(instance)));
    }

    return fieldElements;
}
</code>```

Kind of ugly. If there were some operator in LINQ that mean "do something" (e.g. perform an Action for each selected in the LINQ statement), it would look nicer, more terse:

```<code>IEnumerable<XElement> FieldsToXElements(object instance)
{
    var fieldElements = new List<XElement>();

    from field in instance.GetType().GetFields(instance))
    let name = field.Name
    let value = field.GetValue(instance)
    do fieldElements.Add(new XElement(name, value));

    return fieldElements;
}
</code>```

I realize that's subjective, and just my opinion. For a foreach loop that has one line that simply invokes a method, a "do" operator makes sense, in my opinion. But I'm wondering if anyone at MS has thought the same thing. Is such LINQ operator planned in any upcoming releases (e.g. alongside the C# 4.0 debut)?

Here's another example, with a predicate, where the fictitious do operator would really make the code look cleaner. This:

```<code>IEnumerable<XElement> FieldsToXElements
    (object instance, Func<FieldInfo, bool> predicate)
{
    var fieldElements = new List<XElement>();

    foreach (var field in instance.GetType().GetFields(instance).Where(predicate))
    {
        fieldElements.Add(new XElement(field.Name, field.GetValue(instance)));
    }

    return fieldElements;
}
</code>```

vs. this:

```<code>IEnumerable<XElement> FieldsToXElements
    (object instance, Func<FieldInfo, bool> predicate)
{
    var fieldElements = new List<XElement>();

    from field in instance.GetType().GetFields(instance))
    let name = field.Name
    let value = field.GetValue(instance)
    where predicate(field)
    do fieldElements.Add(new XElement(name, value));

    return fieldElements;
}
</code>```

答:
I don't think this is too hard or maybe I'm missing something...</p>

```<code>IEnumerable<XElement> FieldsToXElements(object instance)
{
    return instance.GetType()
                   .GetFields(instance)
                   .Select( f => new XElement( f.Name,
                                               f.GetValue(instance) ) );
}
</code>```

OwnerDisplayName: Chris

Body:
Here's a simple method with a foreach loop:

IEnumerable<XElement> FieldsToXElements(object instance)
{
    var fieldElements = new List<XElement>();

    foreach (var field in instance.GetType().GetFields(instance))
    {
        fieldElements.Add(new XElement(field.Name, field.GetValue(instance)));
    }

    return fieldElements;
}

Kind of ugly. If there were some operator in LINQ that mean "do something" (e.g. perform an Action for each selected in the LINQ statement), it would look nicer, more terse:

IEnumerable<XElement> FieldsToXElements(object instance)
{
    var fieldElements = new List<XElement>();

    from field in instance.GetType().GetFields(instance))
    let name = field.Name
    let value = field.GetValue(instance)
    do fieldElements.Add(new XElement(name, value));

    return fieldElements;
}

I realize that's subjective, and just my opinion. For a foreach loop that has one line that simply invokes a method, a "do" operator makes sense, in my opinion. But I'm wondering if anyone at MS has thought the same thing. Is such LINQ operator planned in any upcoming releases (e.g. alongside the C# 4.0 debut)?

Here's another example, with a predicate, where the fictitious do operator would really make the code look cleaner. This:

IEnumerable<XElement> FieldsToXElements
    (object instance, Func<FieldInfo, bool> predicate)
{
    var fieldElements = new List<XElement>();

    foreach (var field in instance.GetType().GetFields(instance).Where(predicate))
    {
        fieldElements.Add(new XElement(field.Name, field.GetValue(instance)));
    }

    return fieldElements;
}

vs. this:

IEnumerable<XElement> FieldsToXElements
    (object instance, Func<FieldInfo, bool> predicate)
{
    var fieldElements = new List<XElement>();

    from field in instance.GetType().GetFields(instance))
    let name = field.Name
    let value = field.GetValue(instance)
    where predicate(field)
    do fieldElements.Add(new XElement(name, value));

    return fieldElements;
}

Body:
I don't think this is too hard or maybe I'm missing something...

IEnumerable<XElement> FieldsToXElements(object instance)
{
    return instance.GetType()
                   .GetFields(instance)
                   .Select( f => new XElement( f.Name,
                                               f.GetValue(instance) ) );
}

OwnerDisplayName: tvanfosson


问:
How to pass value from javascript to php file
I am getting value via JQuery as something like this

```<code>var query= popURL.split('?');
var dim= query[1].split('&');
var popWidth = dim[0].split('=')[1]; //Gets the first query string value
var id = dim[1].split('=')[1];
</code>```

Now i want to send or get this "id" value into same php file. I think we can only get value on other php page using get method. I want to get value on same php file.

I think we can do with this using AJAX right?

If yes please give me some links or code how to get? I am newbie to ajax.

答:
Take a look at the jQuery api documentation, in particular to the jQuery.ajax() function. You'll find documentation and many useful examples. This is a piece of code from that page that does exactly what you've requested:

```<code>$.ajax({
   type: "POST",
   url: "some.php",
   data: "name=John&location=Boston",
   success: function(msg){
     alert( "Data Saved: " + msg );
   }
 });
</code>```

(Of course you can also pass the data by simply using GET params and appending them to the url)

Body:
I am getting value via JQuery as something like this

var query= popURL.split('?');
var dim= query[1].split('&');
var popWidth = dim[0].split('=')[1]; //Gets the first query string value
var id = dim[1].split('=')[1];

Now i want to send or get this "id" value into same php file. I think we can only get value on other php page using get method. I want to get value on same php file.

I think we can do with this using AJAX right?

If yes please give me some links or code how to get? I am newbie to ajax.

Body:
Take a look at the jQuery api documentation, in particular to the jQuery.ajax() function. You'll find documentation and many useful examples. This is a piece of code from that page that does exactly what you've requested:

$.ajax({
   type: "POST",
   url: "some.php",
   data: "name=John&location=Boston",
   success: function(msg){
     alert( "Data Saved: " + msg );
   }
 });

(Of course you can also pass the data by simply using GET params and appending them to the url)


问:
Implementing an in-app purchase auto renewing subscription on an Apple Watch app?
My watch app will put a portion of its features behind a subscription paywall, I'm following a few tutorials I found re: implementing an auto-renewing subscription: savvyapps and RW

Is there any reason I cannot/should not build this code on watch and have the user make the purchase there?  Or should I write the IAP code on the iPhone app and pass a subscribed Bool message to the watch upon load?

答: StoreKit is not available in WatchOS.  The user has to make the purchase on the iPhone, then use WCSession to pass a message to the watch to keep whether the user's subscription is current in sync.


问:
Detect circles of the following picture MATLAB

I am trying to detect the cirles on the notes. with the code following:

```<code>A = imread('note.png');
A = rgb2gray(A);
 imshow(A)
    [centers, radii, metric] = imfindcircles(A,[1 15]);

    centersStrong5 = centers(1:5,:);
    radiiStrong5 = radii(1:5);
    metricStrong5 = metric(1:5);

    viscircles(centersStrong5, radiiStrong5,'EdgeColor','b');
</code>```

However matlab's imfindcircles seems to fail which i cant understand why.... i also changed the radius of circle which is the command [1 15] with getting more circles as adusting the parameter of to centers(1:x,:) so that it will get all the circles but still;

The result i get:

答:
I don't see any circles in this image. This is why the algorithm cannot find them. The closest thing to a circle is the letter G.

I hope this answers your question.

Please read https://en.wikipedia.org/wiki/Circle

I guess you're looking for the lower part of the notes.
Use a template based approach or maybe blob analysis after some preprocessing that  removes all lines.

Body:
I am trying to detect the cirles on the notes. with the code following:

A = imread('note.png');
A = rgb2gray(A);
 imshow(A)
    [centers, radii, metric] = imfindcircles(A,[1 15]);

    centersStrong5 = centers(1:5,:);
    radiiStrong5 = radii(1:5);
    metricStrong5 = metric(1:5);

    viscircles(centersStrong5, radiiStrong5,'EdgeColor','b');

However matlab's imfindcircles seems to fail which i cant understand why.... i also changed the radius of circle which is the command [1 15] with getting more circles as adusting the parameter of to centers(1:x,:) so that it will get all the circles but still;

The result i get:


问:
Combining two dataframes and increasing count for common entries
I have two dataframes which I have computed after wrangling the data, and I am stuck on how to combine them. I have tried to recreate the scenario below:

The first dataframe d1:

```<code>player <- c("Ace", "Ace", "Ace", "Ace")
champ <- c("Azir", "Kassadin", "Xerath", "Zed")
games.played <- c(1, 2, 1, 1)
d1 <- data.frame(player, champ, games.played)
</code>```

Which looks something like this:

```<code>player  champ   games.played
-------------------------
Ace     Azir         1
Ace     Kassadin     2
Ace     Xerath       1
Ace     Zed          1
</code>```

The second dataframe d2:

```<code>player <- c("Ace", "Ace", "Ace", "Ace")
champ <- c("Chogath", "Karthus", "Victor", "Xerath")
games.played <- c(1, 1, 1, 2)
d2 <- data.frame(player, champ, games.played)
</code>```

Which looks something like this:

```<code>player  champ   games.played
-------------------------
Ace     Chogath     1
Ace     Karthus     2
Ace     Viktor      1
Ace     Xerath      1
</code>```

My desired output is (ordering is not really relevant):

```<code>player  champ   games.played
-------------------------
Ace     Azir         1
Ace     Kassadin     2
Ace     Xerath       3
Ace     Zed          1
Ace     Chogath      1
Ace     Karthus      1
Ace     Victor       1
</code>```

Here's the catch, if there exists a pair of player and champ which exists in both the dataframes, I want to just add the number of games played. Otherwise, just add the pair which does not exist.

The closest I have gotten so far is by using rbind(d1, d2) which gives me the below output:

```<code>player    champ     games.played
-------------------------
Ace       Azir      1
Ace       Kassadin  2
Ace       Xerath    1
Ace       Zed       1
Ace       Chogath   1
Ace       Karthus   1
Ace       Victor    1
Ace       Xerath    2
</code>```

My actual data frames are much bigger, so I cannot go about manually checking for duplicate rows and the individually combining them and adding the games.played. My actual dataframes are arranged by (player, champ) and that's why the scenario I have created is sorted so. Any help would really be appreciated!

答:
We could rbind both the datasets, then do a group by and get the sum using aggregate from base R

```<code>aggregate(games.played~., rbind(d1, d2), sum)
</code>```

A similar option with dplyr would be bind_rows with group_by and summarise

```<code>library(dplyr)
bind_rows(d1, d2) %>%
    group_by(player, champ) %>%
    summarise(games.played = sum(games.played))
</code>```

Body:
I have two dataframes which I have computed after wrangling the data, and I am stuck on how to combine them. I have tried to recreate the scenario below:

The first dataframe d1:

player <- c("Ace", "Ace", "Ace", "Ace")
champ <- c("Azir", "Kassadin", "Xerath", "Zed")
games.played <- c(1, 2, 1, 1)
d1 <- data.frame(player, champ, games.played)

Which looks something like this:

player  champ   games.played
-------------------------
Ace     Azir         1
Ace     Kassadin     2
Ace     Xerath       1
Ace     Zed          1

The second dataframe d2:

player <- c("Ace", "Ace", "Ace", "Ace")
champ <- c("Chogath", "Karthus", "Victor", "Xerath")
games.played <- c(1, 1, 1, 2)
d2 <- data.frame(player, champ, games.played)

Which looks something like this:

player  champ   games.played
-------------------------
Ace     Chogath     1
Ace     Karthus     2
Ace     Viktor      1
Ace     Xerath      1

My desired output is (ordering is not really relevant):

player  champ   games.played
-------------------------
Ace     Azir         1
Ace     Kassadin     2
Ace     Xerath       3
Ace     Zed          1
Ace     Chogath      1
Ace     Karthus      1
Ace     Victor       1

Here's the catch, if there exists a pair of player and champ which exists in both the dataframes, I want to just add the number of games played. Otherwise, just add the pair which does not exist.

The closest I have gotten so far is by using rbind(d1, d2) which gives me the below output:

player    champ     games.played
-------------------------
Ace       Azir      1
Ace       Kassadin  2
Ace       Xerath    1
Ace       Zed       1
Ace       Chogath   1
Ace       Karthus   1
Ace       Victor    1
Ace       Xerath    2

My actual data frames are much bigger, so I cannot go about manually checking for duplicate rows and the individually combining them and adding the games.played. My actual dataframes are arranged by (player, champ) and that's why the scenario I have created is sorted so. Any help would really be appreciated!

Body:
We could rbind both the datasets, then do a group by and get the sum using aggregate from base R

aggregate(games.played~., rbind(d1, d2), sum)

A similar option with dplyr would be bind_rows with group_by and summarise

library(dplyr)
bind_rows(d1, d2) %>%
    group_by(player, champ) %>%
    summarise(games.played = sum(games.played))