问:
What is the quickest way to compile and run any single C file
I'd like to compile and run a single c source file on a keypress such as <F5>, now I've looked at several ways of accomplishing this and most involve using a Makefile. However, every example I've found on a generic Makefile require editing the TARGET or compiling all source files in the working directory. This led me to the question if I could run a regexp and replace the first line of the Makefile from any source file I'm working on.

Press <F5>

Update Makefile in root projectdir with current <file>.c working on.

Run make ONLY on <file>

There may be a simpler way of accomplishing this without editing the Makefile, but I've exhausted myself with trying to make a generic enough makefile to do it.

The regexp I have that would select the correct line:

```<code>^TARGET\s[=]\s.*
</code>```

答:
Here is a simplified version of a function I bind to C-c C-C in my c-mode-map. It just compiles the file, runs it with output to the compilation buffer, and then removes the compiled program. Note that you can string together multiple shell commands in your compile-command to run/cleanup etc. With a prefix it will prompt for compilation command as normal.

```<code>(defun my-compile-and-run (arg)
  "Compile, run (output to compilation buffer), remove program."
  (interactive "P")
  (let* ((out (concat (file-name-sans-extension
                       (file-name-nondirectory buffer-file-name))))
         (command
          (concat "gcc -std=c11 "       ;other flags, etc.
                  buffer-file-name " -o " out
                  "; ./" out            ;run executable
                  "; rm " out)))        ;clean up
    (unless arg
      (setq-local compilation-read-command nil))
    (setq-local compile-command command)
    (call-interactively 'compile)))
</code>```

You can get more creative with your compile-command as well. If you actually wanted to run it through a makefile, for example,

```<code>CURRENT ?=
EXE     = $(CURRENT:.c=)

target: ${CURRENT}
    gcc -ansi -Wall -pedantic -O3 ${CURRENT} -o ${EXE}

run-target: target
    ${EXE}

clean-target:
    $(RM) ${EXE}
</code>```

You could then compile from emacs by just setting the compile-command to set the CURRENT variable to the buffers name and call whichever make targets you want, eg.

```<code>(defun my-compile-and-run (arg)
  "Compile, run (output to compilation buffer), remove program."
  (interactive "P")
  (when (file-exists-p "Makefile")
    (let ((command (concat "make CURRENT=\"" ;set current target
                           (shell-quote-argument buffer-file-name)
                           ;run and clean program
                           "\" run-target clean-target")))
      (unless arg
        (setq-local compilation-read-command nil))
      (setq-local compile-command command)
      (call-interactively 'compile))))
</code>```

Typically you want to set the compile-command in you mode-hooks or as a local variable like @phils shows in the .dirs-locals.el or the other alternative ways to define emacs local variables.

Body:
I'd like to compile and run a single c source file on a keypress such as <F5>, now I've looked at several ways of accomplishing this and most involve using a Makefile. However, every example I've found on a generic Makefile require editing the TARGET or compiling all source files in the working directory. This led me to the question if I could run a regexp and replace the first line of the Makefile from any source file I'm working on.

Press <F5>

Update Makefile in root projectdir with current <file>.c working on.

Run make ONLY on <file>

There may be a simpler way of accomplishing this without editing the Makefile, but I've exhausted myself with trying to make a generic enough makefile to do it.

The regexp I have that would select the correct line:

^TARGET\s[=]\s.*

Body:
Here is a simplified version of a function I bind to C-c C-C in my c-mode-map. It just compiles the file, runs it with output to the compilation buffer, and then removes the compiled program. Note that you can string together multiple shell commands in your compile-command to run/cleanup etc. With a prefix it will prompt for compilation command as normal.

(defun my-compile-and-run (arg)
  "Compile, run (output to compilation buffer), remove program."
  (interactive "P")
  (let* ((out (concat (file-name-sans-extension
                       (file-name-nondirectory buffer-file-name))))
         (command
          (concat "gcc -std=c11 "       ;other flags, etc.
                  buffer-file-name " -o " out
                  "; ./" out            ;run executable
                  "; rm " out)))        ;clean up
    (unless arg
      (setq-local compilation-read-command nil))
    (setq-local compile-command command)
    (call-interactively 'compile)))

You can get more creative with your compile-command as well. If you actually wanted to run it through a makefile, for example,

CURRENT ?=
EXE     = $(CURRENT:.c=)

target: ${CURRENT}
    gcc -ansi -Wall -pedantic -O3 ${CURRENT} -o ${EXE}

run-target: target
    ${EXE}

clean-target:
    $(RM) ${EXE}

You could then compile from emacs by just setting the compile-command to set the CURRENT variable to the buffers name and call whichever make targets you want, eg.

(defun my-compile-and-run (arg)
  "Compile, run (output to compilation buffer), remove program."
  (interactive "P")
  (when (file-exists-p "Makefile")
    (let ((command (concat "make CURRENT=\"" ;set current target
                           (shell-quote-argument buffer-file-name)
                           ;run and clean program
                           "\" run-target clean-target")))
      (unless arg
        (setq-local compilation-read-command nil))
      (setq-local compile-command command)
      (call-interactively 'compile))))

Typically you want to set the compile-command in you mode-hooks or as a local variable like @phils shows in the .dirs-locals.el or the other alternative ways to define emacs local variables.


来源: stackexchange

问:
Left join, where clause
I'm wondering why this returns no values but if I place the "and r2.ref_nm = 'memberPrograStatusType" in the join clause it returns values. The 'memberPrograStatusType is null. </p>

```<code>`select mp.mbr_id
,r1.ref_desc as program_name
,r2.ref_desc as program_status
,mp.nom_dt
,mp.enrl_dt
,mp.end_dt
from icue.mbr_pgm mp
  left join icue.ref r1 on mp.pgm_typ_id = r1.ref_cd
  left join icue.ref r2 on mp.mbr_pgm_sts_typ_id = r2.ref_cd
where '15-JAN-17' between mp.enrl_dt and nvl(mp.end_dt,sysdate)
    and mp.mbr_id = 46714641
    and r1.ref_nm = 'programType'
    and r2.ref_nm = 'memberPrograStatusType'
'
</code>```

答:
The key here is order of operations

WHERE is applied after JOIN

If you put r2.ref_nm = 'x' into the JOIN predicate, it is applied against the right table, which is then joined to the left table.  Because you are using a LEFT JOIN, this means that the rows joined from the right table are filtered on r2.ref_nm = 'x', but all rows from the left table are still preserved in the result set.

If you put r2.ref_nm = 'x' into the WHERE clause, then it is applied to the entire result set, after the joins have occured.  This essentially makes your LEFT JOIN into an INNER JOIN if your filter is looking for anything other than NULL

TLDR: if you want to filter on the right table in a LEFT JOIN, you have to do so in the join predicate, otherwise you will lose all the NULL values that are created from the LEFT JOIN

ContentLicense: CC BY-SA 3.0

Title: Left join, where clause

Body:
I'm wondering why this returns no values but if I place the "and r2.ref_nm = 'memberPrograStatusType" in the join clause it returns values. The 'memberPrograStatusType is null.

`select mp.mbr_id
,r1.ref_desc as program_name
,r2.ref_desc as program_status
,mp.nom_dt
,mp.enrl_dt
,mp.end_dt
from icue.mbr_pgm mp
  left join icue.ref r1 on mp.pgm_typ_id = r1.ref_cd
  left join icue.ref r2 on mp.mbr_pgm_sts_typ_id = r2.ref_cd
where '15-JAN-17' between mp.enrl_dt and nvl(mp.end_dt,sysdate)
    and mp.mbr_id = 46714641
    and r1.ref_nm = 'programType'
    and r2.ref_nm = 'memberPrograStatusType'
'


问:
Resource not loaded with PrismApplication (Prism v7 - 7.0.0.329-ci)
Using the new Prism v7 library, the Bootstrapper class is obsolete and must be replaced by the PrismApplication class.

I configured the new PrismApplication for my app but the app failed to load the XAML resources at the right time.

I declare a few resources in the App.xaml file:

```<code><local:MyPrismApplication x:Class="Xxx.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:Xxx">
    <local:MyPrismApplication.Resources>
...
    </local:MyPrismApplication.Resources>
</local:MyPrismApplication>
</code>```

The new PrismApplication creates the Shell. The Shell need resources that aren't yet loaded.

Using the 'old' bootstrapper class, the problem doesn't exist.

What is recommended with the new PrismApplication class? Can we not set up anymore the resources in the App.xaml ?

答:
Actually, you may have found a bug. I changed the startup process to start in the Ctor, not in the OnStartup override. I should probably change it back to do everything in OnStartup instead, similar to the bootstrapper. This will ensure all resources are available. Can you submit a bug on the GitHub site?

https://github.com/prismlibrary/prism/issues

EDIT: Just updated the PrismApplication class. Try the latest CI build and see if it works.

Body:
Using the new Prism v7 library, the Bootstrapper class is obsolete and must be replaced by the PrismApplication class.

I configured the new PrismApplication for my app but the app failed to load the XAML resources at the right time.

I declare a few resources in the App.xaml file:

<local:MyPrismApplication x:Class="Xxx.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:Xxx">
    <local:MyPrismApplication.Resources>
...
    </local:MyPrismApplication.Resources>
</local:MyPrismApplication>

The new PrismApplication creates the Shell. The Shell need resources that aren't yet loaded.

Using the 'old' bootstrapper class, the problem doesn't exist.

What is recommended with the new PrismApplication class? Can we not set up anymore the resources in the App.xaml ?


问:
Proper way of consuming WCF Services in WPF Application using DI
The problem is that contrary to controllers in MVC, MVVM models in WPF are instantiated and are there for good. Practically what that means for me is that if I have a private property in my viemodel my proxy will be open for a long time eg.:

```<code>//Some example after googling for "consuming wcf services in wpf app~"
private FootballerServices.FootballerServiceClient footballersService = null;

private void Window_Loaded(object sender, RoutedEventArgs e)
{

    footballersService = new FootballerServices.FootballerServiceClient();
    try
    {
        FootballerBox.ItemsSource = footballersService.GetFootballers();
    }
    catch (Exception ex)
    {

        MessageBox.Show(ex.Message);
    }

}
</code>```

How do I solve that issue properly?

First solution:

```<code>private void button_Click(object sender, RoutedEventArgs e)
{
    MyServicesClient proxy = new MyServicesClient();

    try
    {
        MyServicesData data = proxy.GetDataFromMyService();

        proxy.Close();
    }
    catch (FaultException ex)
    {
        MessageBox.Show("Fault Exception: " + ex.Message);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}
</code>```

Then I could make a new class like ServiceWrapper where I would encapsulate all the method calls:
    private void button_Click(object sender, RoutedEventArgs e)
    {
        var t = serviceWrapper.GetDataFromMyService();
        (...)
    }

and in Service Wrapper:

```<code>private void button_Click(object sender, RoutedEventArgs e)
{
    MyServicesClient proxy = new MyServicesClient();

    try
    {
        MyServicesData data = proxy.GetDataFromMyService();

        proxy.Close();
    }
    catch (FaultException ex)
    {
        (...)
    }
    catch (Exception ex)
    {
        (...)
    }

    return data;
}
</code>```

Now the last thing would be to add DI to that solution

Second Solution

Another way that I found is to use Abstract Factory pattern with DI like it was answered here:

Dependency Injection wcf

I do not fully understand this solution, however.
My understanding was that it happens like this:
DI resolves an instance of my ServiceClient and after execution goes out scope of the method that used the resolved instance, the DI container disposes of that instance - that there is no need for Abstract factory pattern.
Apparently, my understanding was wrong.

Question: What is the proper practice in such case?

答:
You most likely wouldn't want to inject a WCF client because you only need it for a very short time. What you can inject is a factory that will return the service when needed.

The factory interface may look like this:

```<code>public interface IMyServiceFactory
{
    IMyService Create();
    void Release(IMyService created);
}
</code>```

Assume that you're injecting this through your constructor and adding a private readonly field to your class, like this:

```<code>private readonly IMyServiceFactory _myServiceFactory;
</code>```

Then when you need the service, you do this:

```<code>var myService = _myServiceFactory.Create();
try
{
   // do something with the service
}
finally
{
   _myService.Release(myService);
}
</code>```

A big benefit is that your class depends entirely on abstractions. It doesn't "know" that the service is implemented by a WCF client or that the factory is calling a DI container. You can test it using a mock of IMyService. That's impossible if your class is directly creating its own WCF client.

You didn't mention which container you're using, but many of them will create WCF clients for you to implement interfaces.

Autofac

Windsor - their documentation is lacking at this point. In the off chance that you're using Windsor I can provide more detail.

Another nice detail about Windsor is that it will also create the abstract factory for you.

Here's a few more pieces to make up a sample implementation using Windsor. This supposes that you have a WCF service that implements IMyService.

Here's the service interface, the factory interface, and the class that consumes it:

```<code>public interface IMyService
{
    IEnumerable<string> GetSomeData();
}

public interface IMyServiceFactory
{
    IMyService Create();
    void Release(IMyService created);
}

public class ClassThatConsumesService
{
    private readonly IMyServiceFactory _serviceFactory;

    public ClassThatConsumesService(IMyServiceFactory myServiceFactory)
    {
        _serviceFactory = myServiceFactory;
    }

    public void MethodThatDoesSomething()
    {
        var service = _serviceFactory.Create();
        try
        {
            var data = service.GetSomeData();
            // do whatever
        }
        finally
        {
            _serviceFactory.Release(service);
        }
    }
}
</code>```

Then here's an example of some implementation details using Windsor. But one important detail is that nothing above depends on Windsor. You could do this using a different DI container. You don't even need a DI container at all. All your class knows is that it's calling a factory to get an instance of a service.

```<code>public class ClassThatConsumesService
{
    private readonly IMyServiceFactory _serviceFactory;

    public ClassThatConsumesService(IMyServiceFactory myServiceFactory)
    {
        _serviceFactory = myServiceFactory;
    }

    public void MethodThatDoesSomething()
    {
        var service = _serviceFactory.Create();
        try
        {
            var data = service.GetSomeData();
            // do whatever
        }
        finally
        {
            _serviceFactory.Release(service);
        }
    }
}
</code>```

To use Windsor you would add the Windsor WCF Facility nuget package, which is Windsor plus some additional classes for handling WCF services.

Your container registration might look like this:

```<code>container.AddFacility<TypedFactoryFacility>();
container.AddFacility<WcfFacility>();
container.Register(Component.For<IMyService>()
    .AsWcfClient(WcfEndpoint.FromConfiguration("MyServiceEndpointName")));
container.Register(Component.For<IMyServiceFactory>().AsFactory());
</code>```

This does the following:

Adds the "facility" or capability for the container to provide an abstract factory (I'll come back to that.)

Adds the WCF facility for managing WCF services

Tells the container that the implementation of IMyService is a WCF client using the endpoint specified in app.config/web.config named "MyServiceEndpointName".

Tells the container that the implementation of IMyServiceFactory is a factory that Windsor creates. Here's that documentation again.. What that means is that you don't actually create a class to implement IMyServiceFactory. The container does it. When you call Create the factory creates the client. When you call Release it disposes the client.

If you wanted to you could write your own factory implementation, like this:

```<code>public class WcfClientMyServiceFactory : IMyServiceFactory
{
    public IMyService Create()
    {
        return new MyServiceClient();
    }

    public void Release(IMyService created)
    {
        var client = (MyServiceClient) created;
        try
        {
            try
            {
                client.Close();
            }
            catch
            {
                client.Abort();
            }
        }
        finally
        {
            client.Dispose();
        }
    }
}
</code>```

(Don't quote me on the details of how to properly close a WCF client. It's been a while and I'm rusty.)

But having gotten used to using Windsor it's just a lot easier.

Having done it this way, what if you want to unit test your class assuming that IMyService will return specific data? Now it's really easy to use Moq or just write test double classes like this:

```<code>public class MyServiceDouble : IMyService
{
    public IEnumerable<string> GetSomeData()
    {
        return new [] {"x", "y", "z"};
    }
}

public class MyServiceFactoryDouble : IMyServiceFactory
{
    public IMyService Create()
    {
        return new MyServiceDouble();
    }

    public void Release(IMyService created)
    {
        // Nothing to clean up.
    }
}
</code>```

Because your class doesn't know anything about IMyService - it doesn't know that the "normal" implementation is a WCF client - it's easy to replace it with something else.

Body:
The problem is that contrary to controllers in MVC, MVVM models in WPF are instantiated and are there for good. Practically what that means for me is that if I have a private property in my viemodel my proxy will be open for a long time eg.:

//Some example after googling for "consuming wcf services in wpf app~"
private FootballerServices.FootballerServiceClient footballersService = null;

private void Window_Loaded(object sender, RoutedEventArgs e)
{

    footballersService = new FootballerServices.FootballerServiceClient();
    try
    {
        FootballerBox.ItemsSource = footballersService.GetFootballers();
    }
    catch (Exception ex)
    {

        MessageBox.Show(ex.Message);
    }

}

How do I solve that issue properly?

First solution:

private void button_Click(object sender, RoutedEventArgs e)
{
    MyServicesClient proxy = new MyServicesClient();

    try
    {
        MyServicesData data = proxy.GetDataFromMyService();

        proxy.Close();
    }
    catch (FaultException ex)
    {
        MessageBox.Show("Fault Exception: " + ex.Message);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

Then I could make a new class like ServiceWrapper where I would encapsulate all the method calls:
    private void button_Click(object sender, RoutedEventArgs e)
    {
        var t = serviceWrapper.GetDataFromMyService();
        (...)
    }

and in Service Wrapper:

private void button_Click(object sender, RoutedEventArgs e)
{
    MyServicesClient proxy = new MyServicesClient();

    try
    {
        MyServicesData data = proxy.GetDataFromMyService();

        proxy.Close();
    }
    catch (FaultException ex)
    {
        (...)
    }
    catch (Exception ex)
    {
        (...)
    }

    return data;
}

Now the last thing would be to add DI to that solution

Second Solution

Another way that I found is to use Abstract Factory pattern with DI like it was answered here:

Dependency Injection wcf

I do not fully understand this solution, however.
My understanding was that it happens like this:
DI resolves an instance of my ServiceClient and after execution goes out scope of the method that used the resolved instance, the DI container disposes of that instance - that there is no need for Abstract factory pattern.
Apparently, my understanding was wrong.

Question: What is the proper practice in such case?

Body:
You most likely wouldn't want to inject a WCF client because you only need it for a very short time. What you can inject is a factory that will return the service when needed.

The factory interface may look like this:

public interface IMyServiceFactory
{
    IMyService Create();
    void Release(IMyService created);
}

Assume that you're injecting this through your constructor and adding a private readonly field to your class, like this:

private readonly IMyServiceFactory _myServiceFactory;

Then when you need the service, you do this:

var myService = _myServiceFactory.Create();
try
{
   // do something with the service
}
finally
{
   _myService.Release(myService);
}

A big benefit is that your class depends entirely on abstractions. It doesn't "know" that the service is implemented by a WCF client or that the factory is calling a DI container. You can test it using a mock of IMyService. That's impossible if your class is directly creating its own WCF client.

You didn't mention which container you're using, but many of them will create WCF clients for you to implement interfaces.

Autofac

Windsor - their documentation is lacking at this point. In the off chance that you're using Windsor I can provide more detail.

Another nice detail about Windsor is that it will also create the abstract factory for you.

Here's a few more pieces to make up a sample implementation using Windsor. This supposes that you have a WCF service that implements IMyService.

Here's the service interface, the factory interface, and the class that consumes it:

public interface IMyService
{
    IEnumerable<string> GetSomeData();
}

public interface IMyServiceFactory
{
    IMyService Create();
    void Release(IMyService created);
}

public class ClassThatConsumesService
{
    private readonly IMyServiceFactory _serviceFactory;

    public ClassThatConsumesService(IMyServiceFactory myServiceFactory)
    {
        _serviceFactory = myServiceFactory;
    }

    public void MethodThatDoesSomething()
    {
        var service = _serviceFactory.Create();
        try
        {
            var data = service.GetSomeData();
            // do whatever
        }
        finally
        {
            _serviceFactory.Release(service);
        }
    }
}

Then here's an example of some implementation details using Windsor. But one important detail is that nothing above depends on Windsor. You could do this using a different DI container. You don't even need a DI container at all. All your class knows is that it's calling a factory to get an instance of a service.

public class ClassThatConsumesService
{
    private readonly IMyServiceFactory _serviceFactory;

    public ClassThatConsumesService(IMyServiceFactory myServiceFactory)
    {
        _serviceFactory = myServiceFactory;
    }

    public void MethodThatDoesSomething()
    {
        var service = _serviceFactory.Create();
        try
        {
            var data = service.GetSomeData();
            // do whatever
        }
        finally
        {
            _serviceFactory.Release(service);
        }
    }
}

To use Windsor you would add the Windsor WCF Facility nuget package, which is Windsor plus some additional classes for handling WCF services.

Your container registration might look like this:

container.AddFacility<TypedFactoryFacility>();
container.AddFacility<WcfFacility>();
container.Register(Component.For<IMyService>()
    .AsWcfClient(WcfEndpoint.FromConfiguration("MyServiceEndpointName")));
container.Register(Component.For<IMyServiceFactory>().AsFactory());

This does the following:

Adds the "facility" or capability for the container to provide an abstract factory (I'll come back to that.)

Adds the WCF facility for managing WCF services

Tells the container that the implementation of IMyService is a WCF client using the endpoint specified in app.config/web.config named "MyServiceEndpointName".

Tells the container that the implementation of IMyServiceFactory is a factory that Windsor creates. Here's that documentation again.. What that means is that you don't actually create a class to implement IMyServiceFactory. The container does it. When you call Create the factory creates the client. When you call Release it disposes the client.

If you wanted to you could write your own factory implementation, like this:

public class WcfClientMyServiceFactory : IMyServiceFactory
{
    public IMyService Create()
    {
        return new MyServiceClient();
    }

    public void Release(IMyService created)
    {
        var client = (MyServiceClient) created;
        try
        {
            try
            {
                client.Close();
            }
            catch
            {
                client.Abort();
            }
        }
        finally
        {
            client.Dispose();
        }
    }
}

(Don't quote me on the details of how to properly close a WCF client. It's been a while and I'm rusty.)

But having gotten used to using Windsor it's just a lot easier.

Having done it this way, what if you want to unit test your class assuming that IMyService will return specific data? Now it's really easy to use Moq or just write test double classes like this:

public class MyServiceDouble : IMyService
{
    public IEnumerable<string> GetSomeData()
    {
        return new [] {"x", "y", "z"};
    }
}

public class MyServiceFactoryDouble : IMyServiceFactory
{
    public IMyService Create()
    {
        return new MyServiceDouble();
    }

    public void Release(IMyService created)
    {
        // Nothing to clean up.
    }
}

Because your class doesn't know anything about IMyService - it doesn't know that the "normal" implementation is a WCF client - it's easy to replace it with something else.


Title: Sort and remove duplicates

Body:
Please can you help me to solve this problem.

I would like to sort column 1, 2 to be able to delete the duplicates in column 1, keeping always the first 2 records.

The objective in the sort is to keep in the second column diff numbers not the same.

example

I got this

3039949085;**19**;1195616938480000;1  ;V2
3039949085;**19**;1195616938480000;2  ;V2
3039949085;**30**;1195616938480000;2  ;V2

after the sorting should be

3039949085;**19**;1195616938480000;1  ;V2
3039949085;**30**;1195616938480000;2  ;V2
3039949085;**19**;1195616938480000;2  ;V2

i use this code

sort -t';' -k1,2n -k4 file | gawk -F';' 'a[$1]++<2

My input file is:

2995347947;6;1195617034732000;1  ;V3
2995347947;9;1195617034732000;1  ;V3
2995347947;6;1195617034732000;2  ;V3
2995347947;9;1195617034732000;2  ;V3
3039948773;14;1195616284532000;1  ;V2
3039948785;14;1195616747632000;1  ;V2
3039948785;25;1195616747632000;1  ;V2
3039948785;14;1195616747632000;2  ;V2
3039948785;25;1195616747632000;2  ;V2
3039949061;19;1195615542032000;1  ;V2
3039949061;19;1195615542032000;2  ;V2
3039949061;30;1195615542032000;2  ;V2
3039949073;19;1195616109632000;1  ;V2
3039949073;19;1195616109632000;2  ;V2
3039949073;30;1195616109632000;2  ;V2
3039949085;19;1195616938480000;1  ;V2
3039949085;19;1195616938480000;2  ;V2
3039949085;30;1195616938480000;2  ;V2
3039949373;10;1195615559208000;1  ;V2
3039949373;11;1195615559208000;1  ;V2
3039949373;10;1195615559208000;2  ;V2

output I got

2995347947;6;1195617034732000;1  ;V3
2995347947;9;1195617034732000;1  ;V3
3039948773;14;1195616284532000;1  ;V2
3039948785;14;1195616747632000;1  ;V2
3039948785;25;1195616747632000;1  ;V2
3039949061;19;1195615542032000;1  ;V2
3039949061;19;1195615542032000;2  ;V2
3039949073;19;1195616109632000;1  ;V2
3039949073;19;1195616109632000;2  ;V2
3039949085;19;1195616938480000;1  ;V2
3039949085;19;1195616938480000;2  ;V2
3039949373;10;1195615559208000;1  ;V2
3039949373;11;1195615559208000;1  ;V2

But i will like to get the following output

2995347947;6;1195617034732000;1  ;V3
2995347947;9;1195617034732000;1  ;V3
3039948773;14;1195616284532000;1  ;V2
3039948785;14;1195616747632000;1  ;V2
3039948785;25;1195616747632000;1  ;V2
3039949061;19;1195615542032000;1  ;V2
3039949061;30;1195615542032000;2  ;V2
3039949073;19;1195616109632000;1  ;V2
3039949073;30;1195616109632000;2  ;V2
3039949085;30;1195616938480000;2  ;V2
3039949085;19;1195616938480000;1  ;V2
3039949373;10;1195615559208000;1  ;V2
3039949373;11;1195615559208000;1  ;V2

My problem is in the sort step

Appreciate your help.

Body:
You can use this awk to print unique sets of $1,$2:

awk -F';' '!a[$1,$2]++'

Full example:

sort -t';' -k1,2n -k4 file | awk -F';' '!a[$1,$2]++'

2995347947;6;1195617034732000;1  ;V3
2995347947;9;1195617034732000;1  ;V3
3039948773;14;1195616284532000;1  ;V2
3039948785;14;1195616747632000;1  ;V2
3039948785;25;1195616747632000;1  ;V2
3039949061;19;1195615542032000;1  ;V2
3039949061;30;1195615542032000;2  ;V2
3039949073;19;1195616109632000;1  ;V2
3039949073;30;1195616109632000;2  ;V2
3039949085;19;1195616938480000;1  ;V2
3039949085;30;1195616938480000;2  ;V2
3039949373;10;1195615559208000;1  ;V2
3039949373;11;1195615559208000;1  ;V2


问:
Regex to remove word from XSLT
I need help writing regex to remove a word using XSLT.

I need to change the output of my XML file's "detailpath" from:

/events/262/26207

...to simply:

262/26207

The XSL is:

```<code><xsl:value-of select="detailpath"/>
</code>```

How can I remove "/events/"?

Thanks in advance.

答:
Do note that for your example (starting string) you could alse use this XPath 1.0 expression:</p>

```<code>substring(detailpath, 9 * starts-with(detailpath,'/events/'))
</code>```

ContentLicense: CC BY-SA 2.5

Title: Regex to remove word from XSLT

Body:
I need help writing regex to remove a word using XSLT.

I need to change the output of my XML file's "detailpath" from:

/events/262/26207

...to simply:

262/26207

The XSL is:

<xsl:value-of select="detailpath"/>

How can I remove "/events/"?

Thanks in advance.

Body:
Do note that for your example (starting string) you could alse use this XPath 1.0 expression:

substring(detailpath, 9 * starts-with(detailpath,'/events/'))


问:
Asp.Net Core 2.0 MVC Issue with jQuery ready function
Let me start off by saying that I an new to Core 2.0 as well as MVC so please forgive my ignorance

I have used webforms for many years and would use AJAX to handle this, but I have had a hard time finding the answer for MVC.

I believe the issue I am having is that when I click the button on the page, that it is doing a full post and not using Ajax to partially post. The only reason this makes a difference is that on this login screen I have the login form fly down on page load.

```<code><script type="text/javascript">
    $().ready(function () {
        setTimeout(function () { $('.card').removeClass('card-hidden'); }, 700)
    });
</script>
</code>```

If the user were to enter incorrect information and I have to display an error, the login form will once again fly in from the top.

So my question is two fold.

For starters is there any easy way to stop it from floating in on a postback?
With webforms I could access the HTML directly in the code behind and remove the class before I return.
Maybe I could do something like adding a state to my ViewModel and then I could switch the class based on that in Razer.

Alternatively it would be nice to be able to use AJAX like I am able to do in webforms as I am sure I will have additional more complex UI issues associated with page loading and current status of elements. Does anyone know of a good resource for this?

RECAP

Using Asp.net Core 2.0 MVC

Issue with the JQuery ready method firing on postback

This causes my login form to fly in again

Am I going to have to hack the UI as in item 1

Should I focus on AJAX and what would be a good resource based on my needs.

Sample page: http://demos.creative-tim.com/material-dashboard-pro/examples/pages/login.html

Solution

First off a big thanks to David Lang for pointing me in the right direction. Between his post and the link I was able to work this out.

A word of caution, much of my issues were caused by a nuget package not installing correctly. The Microsoft unobtrusive Ajax installed, but because I didn't have a folder called scripts, it never put the JS files in my project. Once I got those in my project the rest became easier.

Start by adding the script for the jQuery unobtrusive to your page.

```<code><script src="~/js/jquery.unobtrusive-ajax.min.js"></script>
</code>```

Add the minimum form tags

```<code><form asp-action="CheckPassword" data-ajax="true" data-ajax-method="post" data-ajax-success="onSuccess" >
</code>```

In your controller check your data, and in my case return a viewModel (not a view)

```<code>[HttpPost]
public ActionResult CheckPassword([Bind("userName, password")] LoginVM loginModel)
{
    if (loginModel.userName == "somename" && loginModel.password == "1234")
    {
        loginModel.invalidUser = false;
        return Ok(loginModel);
    }
    else
    {
        loginModel.invalidUser = true;
        return Ok(loginModel);
    }
}
</code>```

Create JS function to do something with the returned data.

```<code>var onSuccess = function (context) {
    var errorMessage = $("#errorMessage");
    errorMessage.html("");

    if (context.invalidUser)
    {
        errorMessage.html("Invalid Credentials");
    }
    else
    {
        errorMessage.html("Valid user!");
    }
};
</code>```

答:
Since you're new to ASP.NET Core 2.0, I am not going to explain things in details but I very want to encourage you to go research them and later on master them by yourself.

Regular Form Post

LoginViewModel.cs

```<code>namespace DL.SO.Project.Reporting.Accounts
{
    public class LoginViewModel
    {
        [Required]
        public string Username { get; set; }

        [Required]
        [DataType(DataType.Password)]
        public string Password { get; set; }

        [Display(Name = "Remember my login?")]
        public bool RememberMe { get; set; }

        public string ReturnUrl { get; set; }
    }
}
</code>```

Login.cshtml

```<code>@model DL.SO.Project.Reporting.Accounts.LoginViewModel
@{
    ViewBag.Title = "Login";
    Layout = "~/Views/Shared/_CenteredLayout.cshtml";
}

<div class="widget">
    <form asp-area="" asp-controller="account" asp-action="login">
        <input type="hidden" asp-for="ReturnUrl" />

        <div asp-validation-summary="ModelOnly" class="text-danger"></div>

        <div class="form-group">
            <label asp-for="Username" class="required"></label>
            <input type="text" class="form-control" asp-for="Username" autofocus="autofocus" />
            <span class="form-text" asp-validation-for="Username"></span>
        </div>
        <div class="form-group">
            <label asp-for="Password" class="required"></label>
            <input type="password" class="form-control" asp-for="Password" autocomplete="off" />
            <span class="form-text" asp-validation-for="Password"></span>
        </div>
        <div class="form-check">
            <label class="custom-control custom-checkbox">
                <input type="checkbox" class="custom-control-input" asp-for="RememberMe" />
                <span class="custom-control-indicator"></span>
                <span class="custom-control-description">
                    @Html.DisplayNameFor(m => m.RememberMe)
                </span>
            </label>
        </div>
        <button type="submit" class="btn btn-primary btn-block">Login</button>
    </form>
</div>
</code>```

See the asp-controller on the form element, and those asp- attributes on inputs? They're built-in tag helpers from ASP.NET Core.

For example, with asp- attributes on form element, it will create a form with POST method attribute and action attribute pointing to /account/login. And hopefully you have an Account controller Login method to handle that request.

Optional: for client side validation to work, you need jquery-validation and jquery-validation-unobtrusive packages.

Ajax Form Post

To use AJAX for the form post, there are some additional steps beside building forms like above.

Need to install package jquery-ajax-unobtrusive.

Need to specify ajax callbacks using data- on the form element.

Need to define the callback functions.

For example,

```<code><form asp-area="" asp-controller="account", asp-action="login"
    data-ajax="true" data-ajax-method="post" data-ajax-begin="onFormBegin"
    data-ajax-complete="onFormComplete">
...
</form>
</code>```

For a complete list of Unobtrusive ajax helpers, please see here: https://dotnetthoughts.net/jquery-unobtrusive-ajax-helpers-in-aspnet-core/

And then you need to define the callback functions.

```<code>@section scripts {
    <script type="text/javascripts">
        $(function() {
            window.onFormBegin = function() {
                ...
            };

            window.onFormComplete = function(request, status) {
                ...

                // if the status is not valid
                //     keep displaying the form?
                // just an idea...

                ...
            };
        });
    </script>
}
</code>```

My Taste

This is just my opinion. Whenever I deal with account login and other security related stuff, I tend to use regular form post instead of ajax. I don't want anything fancy there, because when something goes wrong, I want the server to give the user a fresh page, or redirect user to somewhere directly and immediately, instead of keeping the page that has invalid information and using ajax to communicate.

Again this is just my personal taste.

Body:
Let me start off by saying that I an new to Core 2.0 as well as MVC so please forgive my ignorance

I have used webforms for many years and would use AJAX to handle this, but I have had a hard time finding the answer for MVC.

I believe the issue I am having is that when I click the button on the page, that it is doing a full post and not using Ajax to partially post. The only reason this makes a difference is that on this login screen I have the login form fly down on page load.

If the user were to enter incorrect information and I have to display an error, the login form will once again fly in from the top.

So my question is two fold.

For starters is there any easy way to stop it from floating in on a postback?
With webforms I could access the HTML directly in the code behind and remove the class before I return.
Maybe I could do something like adding a state to my ViewModel and then I could switch the class based on that in Razer.

Alternatively it would be nice to be able to use AJAX like I am able to do in webforms as I am sure I will have additional more complex UI issues associated with page loading and current status of elements. Does anyone know of a good resource for this?

RECAP

Using Asp.net Core 2.0 MVC

Issue with the JQuery ready method firing on postback

This causes my login form to fly in again

Am I going to have to hack the UI as in item 1

Should I focus on AJAX and what would be a good resource based on my needs.

Sample page: http://demos.creative-tim.com/material-dashboard-pro/examples/pages/login.html

Solution

First off a big thanks to David Lang for pointing me in the right direction. Between his post and the link I was able to work this out.

A word of caution, much of my issues were caused by a nuget package not installing correctly. The Microsoft unobtrusive Ajax installed, but because I didn't have a folder called scripts, it never put the JS files in my project. Once I got those in my project the rest became easier.

Start by adding the script for the jQuery unobtrusive to your page.

Add the minimum form tags

<form asp-action="CheckPassword" data-ajax="true" data-ajax-method="post" data-ajax-success="onSuccess" >

In your controller check your data, and in my case return a viewModel (not a view)

[HttpPost]
public ActionResult CheckPassword([Bind("userName, password")] LoginVM loginModel)
{
    if (loginModel.userName == "somename" && loginModel.password == "1234")
    {
        loginModel.invalidUser = false;
        return Ok(loginModel);
    }
    else
    {
        loginModel.invalidUser = true;
        return Ok(loginModel);
    }
}

Create JS function to do something with the returned data.

var onSuccess = function (context) {
    var errorMessage = $("#errorMessage");
    errorMessage.html("");

    if (context.invalidUser)
    {
        errorMessage.html("Invalid Credentials");
    }
    else
    {
        errorMessage.html("Valid user!");
    }
};

Body:
Since you're new to ASP.NET Core 2.0, I am not going to explain things in details but I very want to encourage you to go research them and later on master them by yourself.

Regular Form Post

LoginViewModel.cs

namespace DL.SO.Project.Reporting.Accounts
{
    public class LoginViewModel
    {
        [Required]
        public string Username { get; set; }

        [Required]
        [DataType(DataType.Password)]
        public string Password { get; set; }

        [Display(Name = "Remember my login?")]
        public bool RememberMe { get; set; }

        public string ReturnUrl { get; set; }
    }
}

Login.cshtml

@model DL.SO.Project.Reporting.Accounts.LoginViewModel
@{
    ViewBag.Title = "Login";
    Layout = "~/Views/Shared/_CenteredLayout.cshtml";
}

<div class="widget">
    <form asp-area="" asp-controller="account" asp-action="login">
        <input type="hidden" asp-for="ReturnUrl" />

        <div asp-validation-summary="ModelOnly" class="text-danger"></div>

        <div class="form-group">
            <label asp-for="Username" class="required"></label>
            <input type="text" class="form-control" asp-for="Username" autofocus="autofocus" />
            <span class="form-text" asp-validation-for="Username"></span>
        </div>
        <div class="form-group">
            <label asp-for="Password" class="required"></label>
            <input type="password" class="form-control" asp-for="Password" autocomplete="off" />
            <span class="form-text" asp-validation-for="Password"></span>
        </div>
        <div class="form-check">
            <label class="custom-control custom-checkbox">
                <input type="checkbox" class="custom-control-input" asp-for="RememberMe" />
                <span class="custom-control-indicator"></span>
                <span class="custom-control-description">
                    @Html.DisplayNameFor(m => m.RememberMe)
                </span>
            </label>
        </div>
        <button type="submit" class="btn btn-primary btn-block">Login</button>
    </form>
</div>

See the asp-controller on the form element, and those asp- attributes on inputs? They're built-in tag helpers from ASP.NET Core.

For example, with asp- attributes on form element, it will create a form with POST method attribute and action attribute pointing to /account/login. And hopefully you have an Account controller Login method to handle that request.

Optional: for client side validation to work, you need jquery-validation and jquery-validation-unobtrusive packages.

Ajax Form Post

To use AJAX for the form post, there are some additional steps beside building forms like above.

Need to install package jquery-ajax-unobtrusive.

Need to specify ajax callbacks using data- on the form element.

Need to define the callback functions.

For example,

<form asp-area="" asp-controller="account", asp-action="login"
    data-ajax="true" data-ajax-method="post" data-ajax-begin="onFormBegin"
    data-ajax-complete="onFormComplete">
...
</form>

For a complete list of Unobtrusive ajax helpers, please see here: https://dotnetthoughts.net/jquery-unobtrusive-ajax-helpers-in-aspnet-core/

And then you need to define the callback functions.

@section scripts {
    <script type="text/javascripts">
        $(function() {
            window.onFormBegin = function() {
                ...
            };

            window.onFormComplete = function(request, status) {
                ...

                // if the status is not valid
                //     keep displaying the form?
                // just an idea...

                ...
            };
        });
    </script>
}

My Taste

This is just my opinion. Whenever I deal with account login and other security related stuff, I tend to use regular form post instead of ajax. I don't want anything fancy there, because when something goes wrong, I want the server to give the user a fresh page, or redirect user to somewhere directly and immediately, instead of keeping the page that has invalid information and using ajax to communicate.

Again this is just my personal taste.


问:
How to receive AJAX (json) response in a divs with same class name individually?
I've been getting crazier day after day with this, I can't find an answer, I've spent like 100h+ with this... I hope someone could help me out!

UPDATE:
So to make myself more clear on this issue and be able to get help from others, I basically have 3 containers named "main-container" they all have 3 containers as childs all with the same class name, and when I submit the button, I trigger an ajax function to load the JSON strings comming from php into the child divs, the problem is that I get the 3 "main_containers" to load the ajax at the same time, I only want to load the ajax if I press the button of each "main_container" individually.

I've been using jquery and vanilla JS as well but seems I just can't get it done!

This is how I currently trigger the button with jquery:

```<code>$('.trigger_button_inside_divs').click(my_ajax_function);
</code>```

And this is how my ajax looks like:

```<code>function my_ajax_function(){
$.ajax({
        dataType: "JSON",
        type: 'POST',
        url: test.php,
        success: function(data) {

     $('.div_to_render_JSON_1').html(data.PHP_JSON_1_RECEIVED);
     $('.div_to_render_JSON_2').html(data.PHP_JSON_2_RECEIVED);
     $('.div_to_render_JSON_3').html(data.PHP_JSON_3_RECEIVED);

        }
    });
}
</code>```

HTML looks like this:

```<code><div class="main_container">
    <div class="my_div">
     //div_to_render_JSON_1
    </div>

        <div class="my_div">
          //div_to_render_JSON_2
        </div>

   <div class="my_div">
   //div_to_render_JSON_3
   </div>

   <button class="trigger_ajax_function_btn">Click to load ajax</button> //this btn loads ajax into the div class "my_div"
</div>

<div class="main_container">
    <div class="my_div">
     //div_to_render_JSON_1
    </div>

        <div class="my_div">
          //div_to_render_JSON_2
        </div>

   <div class="my_div">
   //div_to_render_JSON_3
   </div>

   <button class="trigger_ajax_function_btn">Click to load ajax</button> //this btn loads ajax into the div class "my_div"
</div>

<div class="main_container">
    <div class="my_div">
     //div_to_render_JSON_1
    </div>

        <div class="my_div">
          //div_to_render_JSON_2
        </div>

   <div class="my_div">
   //div_to_render_JSON_3
   </div>

   <button class="trigger_ajax_function_btn">Click to load ajax</button> //this btn loads ajax into the div class "my_div"
</div>
</code>```

So in conclusion, each of those 6 "divs" has a button that triggers an function containing my ajax to render inside that particular div. But what I get is that every time I click that triggering button, I get the ajax to render in all of the 6 divs, instead of render on each particular div only when I click its particular button.

Thanks a lot people, I really hope to get this done!
Cheers.

PD:
This is something a programmer did to achieve what I'm trying to achieve but I just can't figure out what in this code is that is making possible clicking 1 button and affect THAT html element , even though they all have the same class.

```<code>(function(){
$("form input[type=submit]").click(function() {
    $("input[type=submit]", $(this).parents("form")).removeAttr("clicked");
    $(this).attr("clicked", "true");
});

var xhr = new XMLHttpRequest();
var el;

function SetDataInTheForm()
{
    var resp = JSON.parse(xhr.response)
    var pt=0
    var ct=0
    var gt=0

    Array.prototype.forEach.call(el.querySelectorAll(".test"),function(e,i){
        e.innerHTML=resp[i].name
    })
    Array.prototype.forEach.call(el.querySelectorAll(".p"),function(e,i){
        e.innerHTML=parseFloat(resp[i].p).toFixed(0)
        pt+=parseFloat(resp[i].p)
    })
    Array.prototype.forEach.call(el.querySelectorAll(".c"),function(e,i){
        e.innerHTML=parseFloat(resp[i].c).toFixed(0)
        ct+=parseFloat(resp[i].c)
    })
    Array.prototype.forEach.call(el.querySelectorAll(".g"),function(e,i){
        e.innerHTML=parseFloat(resp[i].g).toFixed(0)
        gt+=parseFloat(resp[i].g)
    })

    el.querySelector(".wtp").innerHTML=parseFloat(resp[0].total).toFixed(0)+" "+resp[0].unit
    el.querySelector(".wtc").innerHTML=parseFloat(resp[1].total).toFixed(0)+" "+resp[1].unit
    el.querySelector(".wtg").innerHTML=parseFloat(resp[2].total).toFixed(0)+" "+resp[2].unit

    el.querySelector(".pt").innerHTML=pt.toFixed(0)
    el.querySelector(".ct").innerHTML=ct.toFixed(0)
    el.querySelector(".gt").innerHTML=gt.toFixed(0)
}

function HandleSubmit(e)
{
    el=e.currentTarget
    e.preventDefault();
    xhr.open("POST","/url_here.php",true)
    xhr.setRequestHeader("content-type","application/x-www-form-urlencoded")
    xhr.onload=SetDataInTheForm
    var button=e.currentTarget.querySelector("input[type=submit][clicked=true]")
    button.removeAttribute("clicked")
    xhr.send($("#"+e.currentTarget.id).serialize()+"&"+button.getAttribute("name")+"=on")
}

[].forEach.call(document.querySelectorAll("._form_"),function(form){
    form.addEventListener("submit",HandleSubmit,false);
})

})()
</code>```

答:
Remember that $('.div_container_to_render_JSON') is a new selector that selects all elements with a class div_container_to_render_JSON. What you want to happen is figuring out where that click came from, and find the corresponding div_container_to_render_JSON.

Luckily for you, a jQuery click handler sets the this keyword to the HTMLElement where the click was captured. You can use this to get the parent element.

```<code>$('.your-button').on('click', function () {
  const myButton = $(this);

  $.ajax({
    // ...
    success (data) {
      myButton.parent().html(data.PHP_JSON_RECEIVED);

      // or if you need to find a parent further up in the chain
      // myButton.parents('.div_container_to_render_JSON').html(data.PHP_JSON_RECEIVED);
    }
  });
});
</code>```

Body:
I've been getting crazier day after day with this, I can't find an answer, I've spent like 100h+ with this... I hope someone could help me out!

UPDATE:
So to make myself more clear on this issue and be able to get help from others, I basically have 3 containers named "main-container" they all have 3 containers as childs all with the same class name, and when I submit the button, I trigger an ajax function to load the JSON strings comming from php into the child divs, the problem is that I get the 3 "main_containers" to load the ajax at the same time, I only want to load the ajax if I press the button of each "main_container" individually.

I've been using jquery and vanilla JS as well but seems I just can't get it done!

This is how I currently trigger the button with jquery:

$('.trigger_button_inside_divs').click(my_ajax_function);

And this is how my ajax looks like:

function my_ajax_function(){
$.ajax({
        dataType: "JSON",
        type: 'POST',
        url: test.php,
        success: function(data) {

     $('.div_to_render_JSON_1').html(data.PHP_JSON_1_RECEIVED);
     $('.div_to_render_JSON_2').html(data.PHP_JSON_2_RECEIVED);
     $('.div_to_render_JSON_3').html(data.PHP_JSON_3_RECEIVED);

        }
    });
}

HTML looks like this:

     //div_to_render_JSON_1

          //div_to_render_JSON_2

   //div_to_render_JSON_3

   <button class="trigger_ajax_function_btn">Click to load ajax</button> //this btn loads ajax into the div class "my_div"

     //div_to_render_JSON_1

          //div_to_render_JSON_2

   //div_to_render_JSON_3

   <button class="trigger_ajax_function_btn">Click to load ajax</button> //this btn loads ajax into the div class "my_div"

     //div_to_render_JSON_1

          //div_to_render_JSON_2

   //div_to_render_JSON_3

   <button class="trigger_ajax_function_btn">Click to load ajax</button> //this btn loads ajax into the div class "my_div"

So in conclusion, each of those 6 "divs" has a button that triggers an function containing my ajax to render inside that particular div. But what I get is that every time I click that triggering button, I get the ajax to render in all of the 6 divs, instead of render on each particular div only when I click its particular button.

Thanks a lot people, I really hope to get this done!
Cheers.

PD:
This is something a programmer did to achieve what I'm trying to achieve but I just can't figure out what in this code is that is making possible clicking 1 button and affect THAT html element , even though they all have the same class.

(function(){
$("form input[type=submit]").click(function() {
    $("input[type=submit]", $(this).parents("form")).removeAttr("clicked");
    $(this).attr("clicked", "true");
});

var xhr = new XMLHttpRequest();
var el;

function SetDataInTheForm()
{
    var resp = JSON.parse(xhr.response)
    var pt=0
    var ct=0
    var gt=0

    Array.prototype.forEach.call(el.querySelectorAll(".test"),function(e,i){
        e.innerHTML=resp[i].name
    })
    Array.prototype.forEach.call(el.querySelectorAll(".p"),function(e,i){
        e.innerHTML=parseFloat(resp[i].p).toFixed(0)
        pt+=parseFloat(resp[i].p)
    })
    Array.prototype.forEach.call(el.querySelectorAll(".c"),function(e,i){
        e.innerHTML=parseFloat(resp[i].c).toFixed(0)
        ct+=parseFloat(resp[i].c)
    })
    Array.prototype.forEach.call(el.querySelectorAll(".g"),function(e,i){
        e.innerHTML=parseFloat(resp[i].g).toFixed(0)
        gt+=parseFloat(resp[i].g)
    })

    el.querySelector(".wtp").innerHTML=parseFloat(resp[0].total).toFixed(0)+" "+resp[0].unit
    el.querySelector(".wtc").innerHTML=parseFloat(resp[1].total).toFixed(0)+" "+resp[1].unit
    el.querySelector(".wtg").innerHTML=parseFloat(resp[2].total).toFixed(0)+" "+resp[2].unit

    el.querySelector(".pt").innerHTML=pt.toFixed(0)
    el.querySelector(".ct").innerHTML=ct.toFixed(0)
    el.querySelector(".gt").innerHTML=gt.toFixed(0)
}

function HandleSubmit(e)
{
    el=e.currentTarget
    e.preventDefault();
    xhr.open("POST","/url_here.php",true)
    xhr.setRequestHeader("content-type","application/x-www-form-urlencoded")
    xhr.onload=SetDataInTheForm
    var button=e.currentTarget.querySelector("input[type=submit][clicked=true]")
    button.removeAttribute("clicked")
    xhr.send($("#"+e.currentTarget.id).serialize()+"&"+button.getAttribute("name")+"=on")
}

[].forEach.call(document.querySelectorAll("._form_"),function(form){
    form.addEventListener("submit",HandleSubmit,false);
})

})()

Body:
Remember that $('.div_container_to_render_JSON') is a new selector that selects all elements with a class div_container_to_render_JSON. What you want to happen is figuring out where that click came from, and find the corresponding div_container_to_render_JSON.

Luckily for you, a jQuery click handler sets the this keyword to the HTMLElement where the click was captured. You can use this to get the parent element.

$('.your-button').on('click', function () {
  const myButton = $(this);

  $.ajax({
    // ...
    success (data) {
      myButton.parent().html(data.PHP_JSON_RECEIVED);

      // or if you need to find a parent further up in the chain
      // myButton.parents('.div_container_to_render_JSON').html(data.PHP_JSON_RECEIVED);
    }
  });
});


问:
Nested select statement w/ multiple joins (MS Access)
I'm having issues transferring a query that works in SQL Server Management Studio to MS Access. I'm getting an error:

Syntax error in JOIN operation

The line 'FROM ProductRun' is highlighted when I get this error.

I think Access requires brackets when dealing with multiple Join statement which I've done. I'm stuck. Please help.

```<code>SELECT
    LoadTable.DateTimeStamp, ProgramTable.Value 1, PL.Value 2, PL.Value 3
FROM
    ((LoadTable
LEFT JOIN
    ProgramTable ON LoadTable.DateTimeStamp = ProgramTable.DateTimeStamp)
LEFT JOIN
    PL ON LoadTable.DateTimeStamp = PL.DateTimeStamp)
LEFT JOIN
    (SELECT [StartTime], [EndTime]
     FROM ProductRun
     WHERE ProductRun.StartTime >= '11/1/2017'
       AND ProductRun.Startime <= '12/1/2017') ON (LoadTable.DateTimeStamp >= DATEADD(MINUTE, 15, ProductRun.StartTime)
                                               AND LoadTable.DateTimeStamp <= DATEADD(MINUTE, -15, ProductRun.EndTime))
ORDER BY
    LoadTable.DateTimeStamp;
</code>```

This is my nested select statement in Management Studio which works just fine:

```<code>LEFT JOIN (SELECT [StartTime]
      ,[EndTime]
FROM [ProductionReporting].[dbo].ProductRun
 WHERE StartTime between '11/1/2017 12:00:00 AM' and '11/25/2017 12:00:00 AM') as M3
 ON M1.DateTimeStamp between DATEADD(MINUTE,15, M3.StartTime) and DATEADD(MINUTE,-15, M3.EndTime)
</code>```

答:
Try this:</p>

```<code>SELECT loadtable.datetimestamp,
       programtable.value AS 1,
       pl.value           AS 2,
       pl.value           AS 3
FROM   ((loadtable
         LEFT JOIN programtable
                ON loadtable.datetimestamp = programtable.datetimestamp)
        LEFT JOIN pl
               ON loadtable.datetimestamp = pl.datetimestamp)
       LEFT JOIN (SELECT starttime,
                         endtime
                  FROM   productrun
                  WHERE  productrun.starttime >=#11/1/2017#
                         AND productrun.starttime <=#12/1/2017# ) a
              ON loadtable.datetimestamp >= Dateadd("n", 15, a.starttime)
                 AND loadtable.datetimestamp <= Dateadd("n", -15, a.endtime)
ORDER  BY loadtable.datetimestamp;
</code>```

Body:
I'm having issues transferring a query that works in SQL Server Management Studio to MS Access. I'm getting an error:

Syntax error in JOIN operation

The line 'FROM ProductRun' is highlighted when I get this error.

I think Access requires brackets when dealing with multiple Join statement which I've done. I'm stuck. Please help.

SELECT
    LoadTable.DateTimeStamp, ProgramTable.Value 1, PL.Value 2, PL.Value 3
FROM
    ((LoadTable
LEFT JOIN
    ProgramTable ON LoadTable.DateTimeStamp = ProgramTable.DateTimeStamp)
LEFT JOIN
    PL ON LoadTable.DateTimeStamp = PL.DateTimeStamp)
LEFT JOIN
    (SELECT [StartTime], [EndTime]
     FROM ProductRun
     WHERE ProductRun.StartTime >= '11/1/2017'
       AND ProductRun.Startime <= '12/1/2017') ON (LoadTable.DateTimeStamp >= DATEADD(MINUTE, 15, ProductRun.StartTime)
                                               AND LoadTable.DateTimeStamp <= DATEADD(MINUTE, -15, ProductRun.EndTime))
ORDER BY
    LoadTable.DateTimeStamp;

This is my nested select statement in Management Studio which works just fine:

LEFT JOIN (SELECT [StartTime]
      ,[EndTime]
FROM [ProductionReporting].[dbo].ProductRun
 WHERE StartTime between '11/1/2017 12:00:00 AM' and '11/25/2017 12:00:00 AM') as M3
 ON M1.DateTimeStamp between DATEADD(MINUTE,15, M3.StartTime) and DATEADD(MINUTE,-15, M3.EndTime)

Body:
Try this:

SELECT loadtable.datetimestamp,
       programtable.value AS 1,
       pl.value           AS 2,
       pl.value           AS 3
FROM   ((loadtable
         LEFT JOIN programtable
                ON loadtable.datetimestamp = programtable.datetimestamp)
        LEFT JOIN pl
               ON loadtable.datetimestamp = pl.datetimestamp)
       LEFT JOIN (SELECT starttime,
                         endtime
                  FROM   productrun
                  WHERE  productrun.starttime >=#11/1/2017#
                         AND productrun.starttime <=#12/1/2017# ) a
              ON loadtable.datetimestamp >= Dateadd("n", 15, a.starttime)
                 AND loadtable.datetimestamp <= Dateadd("n", -15, a.endtime)
ORDER  BY loadtable.datetimestamp;


问:
Docker container exiting immediately after running php code
I'm currently developing a RESTful API with the Slim framework and I'm trying to run it on a docker container. The problem, however, is that the script runs only once and than automatically exits from docker with the exit code 0, i.e. it catches the first http request for the index.php page, returns it and then it exits.

I'm sure, there must be a way to run apache on a container, so that every time I make a request for a specific URL(like localhost:8080/api/something) on my local browser, so that the apache server that is running in the container would handle those requests. However, since I didn't have any previous experience with docker, I'm currently not able to solve this.

Here's my Dockerfile:

```<code>FROM php:7.0-cli
COPY . /usr/src/my_app
WORKDIR /usr/src/my_app/public
CMD [ "php", "./index.php" ]
</code>```

Here's my Docker-compose file:

```<code>version: '2'

services:
   app:
      build: ./app
      volumes:
         - ./app:/usr/src/app
      ports:
         - 5001:80
</code>```

Can someone tell my how to change my Dockerfile or Docker-compose file, so that the apache server does not exits after the first requests, but it still runs and listens for other requests.

Thank you in advance!

答:
Here is an example of an image with Apache configured to run PHP7:

```<code>FROM ubuntu:latest
MAINTAINER webmaster@localhost

RUN apt-get update
RUN apt-get install php php-mysql php-cgi libapache2-mod-php -y

COPY your/web/stuff/ var/www/html/

CMD /usr/sbin/apache2ctl -D FOREGROUND
</code>```

In this case I am installing the PHP mods for Apache and running the webserver in the foreground. Here is an example of a build command for this Dockerfile:

```<code>docker build -t "myApache" .
</code>```

Now that I have an image I can run the container with this run command:

```<code>docker run -p 8080:80 -p 4433:443 --name my_web_server -P -d myApache
</code>```

With this running you should be able to access the web server on port 8080 (http://localhost:8080)

Body:
I'm currently developing a RESTful API with the Slim framework and I'm trying to run it on a docker container. The problem, however, is that the script runs only once and than automatically exits from docker with the exit code 0, i.e. it catches the first http request for the index.php page, returns it and then it exits.

I'm sure, there must be a way to run apache on a container, so that every time I make a request for a specific URL(like localhost:8080/api/something) on my local browser, so that the apache server that is running in the container would handle those requests. However, since I didn't have any previous experience with docker, I'm currently not able to solve this.

Here's my Dockerfile:

FROM php:7.0-cli
COPY . /usr/src/my_app
WORKDIR /usr/src/my_app/public
CMD [ "php", "./index.php" ]

Here's my Docker-compose file:

version: '2'

services:
   app:
      build: ./app
      volumes:
         - ./app:/usr/src/app
      ports:
         - 5001:80

Can someone tell my how to change my Dockerfile or Docker-compose file, so that the apache server does not exits after the first requests, but it still runs and listens for other requests.

Thank you in advance!

Body:
Here is an example of an image with Apache configured to run PHP7:

FROM ubuntu:latest
MAINTAINER webmaster@localhost

RUN apt-get update
RUN apt-get install php php-mysql php-cgi libapache2-mod-php -y

COPY your/web/stuff/ var/www/html/

CMD /usr/sbin/apache2ctl -D FOREGROUND

In this case I am installing the PHP mods for Apache and running the webserver in the foreground. Here is an example of a build command for this Dockerfile:

docker build -t "myApache" .

Now that I have an image I can run the container with this run command:

docker run -p 8080:80 -p 4433:443 --name my_web_server -P -d myApache

With this running you should be able to access the web server on port 8080 (http://localhost:8080)


问:
Angular 4 Safari - settings object without keyValue property defined
In Safari,

In primeng input text field, while typing into the text box I can see logged into the console errors of the form.

handleKeypress — injected.entry.js:8231TypeError: undefined is not an
  object (evaluating 'settings.keyValue.charCodeAt')

Essentially, it looks like the settings object is lacking some of the expected properties.
This happens as soon as type in the first character on the box.

This is the following javascript function of the injected.entry.js that breaks:

```<code>function handleKeypress(e) {
        var applyMeta = settings.useMetaKey ? e.metaKey : true;
        var applyShift = settings.useShiftKey ? e.shiftKey : true;
        var applyCtrl = settings.useCtrlKey ? e.ctrlKey : true;
        var applyAlt = settings.useAltKey ? e.altKey : true;
        var applyKey = settings.keyValue.charCodeAt(0) === e.keyCode;
        if (applyMeta && applyShift && applyCtrl && applyAlt && applyKey) {
            e.preventDefault();
            getSelectedText();
        }
</code>```

The line that is broken is the following:

```<code>var applyKey = settings.keyValue.charCodeAt(0) === e.keyCode;
</code>```

This particular file, seems to be safari specific. In chrome, in the sources tab, at least, if I search "cmd + o" for the file, I do not find it.

In Safari, the URL for this file would be:
safari-extension://co.randompaper.safari.polyglot-58XDWHK3JX/295b5352/injected.entry.js

This URL is obtained by copy a link reference to the file.

The following code snippet illustrates the input text field where the issue takes place.

```<code><input id="emailInput" pInputText type="email" placeholder="Email" [(ngModel)]="eMail" name="eMail">
</code>```

Is anyone aware of the cause of this problem?

答:
The issue I was experiencing on the web page was associated to a Safari extension called polyglot.

By checking Safari > Preferences > Extensions and disabling polyglot, the issue could be made to go away.

This issue seems to be correlated with the following open issue:
https://github.com/uetchy/Polyglot/issues/21

For the time being I am disabling the extension, it does not seem to be hurting me but the anoyance of being an error on every key press leads me to disable the extension.

Body:
In Safari,

In primeng input text field, while typing into the text box I can see logged into the console errors of the form.

handleKeypress — injected.entry.js:8231TypeError: undefined is not an
  object (evaluating 'settings.keyValue.charCodeAt')

Essentially, it looks like the settings object is lacking some of the expected properties.
This happens as soon as type in the first character on the box.

This is the following javascript function of the injected.entry.js that breaks:

function handleKeypress(e) {
        var applyMeta = settings.useMetaKey ? e.metaKey : true;
        var applyShift = settings.useShiftKey ? e.shiftKey : true;
        var applyCtrl = settings.useCtrlKey ? e.ctrlKey : true;
        var applyAlt = settings.useAltKey ? e.altKey : true;
        var applyKey = settings.keyValue.charCodeAt(0) === e.keyCode;
        if (applyMeta && applyShift && applyCtrl && applyAlt && applyKey) {
            e.preventDefault();
            getSelectedText();
        }

The line that is broken is the following:

var applyKey = settings.keyValue.charCodeAt(0) === e.keyCode;

This particular file, seems to be safari specific. In chrome, in the sources tab, at least, if I search "cmd + o" for the file, I do not find it.

In Safari, the URL for this file would be:
safari-extension://co.randompaper.safari.polyglot-58XDWHK3JX/295b5352/injected.entry.js

This URL is obtained by copy a link reference to the file.

The following code snippet illustrates the input text field where the issue takes place.

<input id="emailInput" pInputText type="email" placeholder="Email" [(ngModel)]="eMail" name="eMail">

Is anyone aware of the cause of this problem?


问:
Point given 2 other points, an angle, and a distance
I'm in need of a general algorithm to calculate the (x,y) coordinates of a point (b), when I have two other points (origin and a), an angle (angle), and a distance (distance).

They will be used like this, to form a solid-filled radial progress indicator:

origin is placed at the center of a GUI view

a is placed just beyond one of the edges of the view

angle is the angle formed from a to origin to b

b will be placed somewhere else beyond the edges of the view, such that when the path from a to origin to b is closed and filled, they form a shape with one point at the center and two lines extending to the sides.

distance can be considered functionally infinite. For ease of calculation, it can be considered to be equal to the perimeter of the view's bounding box.

Example:
Where `o` is the origin and `A` is the angle:

     a
     .  ------+
     |        |
+----|----+   |
|    |    |   | I can draw more shapes as
|    .A   | --+ necessary to fill other
|   o \   |   | quadrants. I just need `A`
|      \  |   |
+-------\-+   |
         \    |
          \   |
           \  |
            \
             .b
```

This way, by changing the value of angle and repainting the view, I can have a countdown-clock-style shape.

How do I find the coordinates of b in a generalized algorithm? (I'll be implementing this in more than one language)

答:
If a is directly right of the origin and only b moves:
This assumes b is 'leading' a, remember angles are always measured counter-clockwise. In your example A would be the big outer angle, not the small inner one. If you want a to lead b, just use -A instead.

```<code>b = (dist x cos(A), dist x sin(A))
</code>```

If a is anywhere else than directly right, you have to add the 'starting angle' (between the line formed by going from the origin to the right and the line from the origin to a) to alpha like this:

```<code>beta = angle(right, origin, a)
b = (dist x cos(A + beta), dist x sin(A + beta))
</code>```

If origin is not at (0, 0), you will have to add these coordinates to b.

```<code>b = (origin_x + (dist x cos(A + beta)), origin_y + (dist x sin(A + beta)))
</code>```

Body:
I'm in need of a general algorithm to calculate the (x,y) coordinates of a point (b), when I have two other points (origin and a), an angle (angle), and a distance (distance).

They will be used like this, to form a solid-filled radial progress indicator:

origin is placed at the center of a GUI view

a is placed just beyond one of the edges of the view

angle is the angle formed from a to origin to b

b will be placed somewhere else beyond the edges of the view, such that when the path from a to origin to b is closed and filled, they form a shape with one point at the center and two lines extending to the sides.

distance can be considered functionally infinite. For ease of calculation, it can be considered to be equal to the perimeter of the view's bounding box.

Example:
Where `o` is the origin and `A` is the angle:

     a
     .  ------+
     |        |
+----|----+   |
|    |    |   | I can draw more shapes as
|    .A   | --+ necessary to fill other
|   o \   |   | quadrants. I just need `A`
|      \  |   |
+-------\-+   |
         \    |
          \   |
           \  |
            \
             .b

This way, by changing the value of angle and repainting the view, I can have a countdown-clock-style shape.

How do I find the coordinates of b in a generalized algorithm? (I'll be implementing this in more than one language)

Body:
If a is directly right of the origin and only b moves:
This assumes b is 'leading' a, remember angles are always measured counter-clockwise. In your example A would be the big outer angle, not the small inner one. If you want a to lead b, just use -A instead.

b = (dist x cos(A), dist x sin(A))

If a is anywhere else than directly right, you have to add the 'starting angle' (between the line formed by going from the origin to the right and the line from the origin to a) to alpha like this:

beta = angle(right, origin, a)
b = (dist x cos(A + beta), dist x sin(A + beta))

If origin is not at (0, 0), you will have to add these coordinates to b.

b = (origin_x + (dist x cos(A + beta)), origin_y + (dist x sin(A + beta)))


问:
Git stash pop Auto merged after the following done
I'm trying to restore my unsaved files (stashed files)

I had to make a small code change for that first my remote is one commit a head with 1 file change(file1). I need to update my local first with remote and push my changes, for that I have to stash my changes in my local as I have the same file modified (file1) in my local. So I have done the following.

```<code>$git stash
  Saved working directory and index state WIP on dev: 4eb5499

$git pull
  Updating 4eb5499..db82e7c
  Fast-forward

$git add file2 //this is different file.
$git commit
$git push

//with this done on my dev branch I also want to update my master branch with remote

So

$git checkout master
  Switched to branch 'master'
  Your branch is behind 'origin/master' by 1 commit, and can be fast-forwarded.

$git pull
  Updating 4eb5499..db82e7c
  Fast-forward

$git merge dev //to update my changes on master
$git push

  with this done my remote is updated with my changes. both on dev/master branch.

  Now I have switched my branch again.

$git checkout dev
$git stash pop
  Auto-merging **file1**
  CONFLICT (content): Merge conflict in **file1**

  As i have done
$git status

  On branch dev
  Your branch is up-to-date with 'origin/dev'.

Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

   So I have performed the following
$ git reset HEAD

$ git status
  On branch dev
  Your branch is up-to-date with 'origin/dev'.

  Changes not staged for commit:
    (use "git add <file>..." to update what will be committed)
    (use "git checkout -- <file>..." to discard changes in working directory)

$ git stash list
  stash@{0}: WIP on dev: 4eb5499 //I want the changes which are here.
  stash@{1}: WIP on master: 9dac6b5

$ git stash pop
  error: Your local changes to the following files would be overwritten by merge:
</code>```

I just want my stashed files to be used again.

答:
I found that git has added few lines on the files, which looks like there is some bug in the files (by compiler), So went into file and deleted the lines added by git

```<code><<<<<<< Updated upstream

between this
code may be replicated again please check and delete.

=======
>>>>>>> Stashed changes
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to restore my unsaved files (stashed files)

I had to make a small code change for that first my remote is one commit a head with 1 file change(file1). I need to update my local first with remote and push my changes, for that I have to stash my changes in my local as I have the same file modified (file1) in my local. So I have done the following.

$git stash
  Saved working directory and index state WIP on dev: 4eb5499

$git pull
  Updating 4eb5499..db82e7c
  Fast-forward

$git add file2 //this is different file.
$git commit
$git push

//with this done on my dev branch I also want to update my master branch with remote

So

$git checkout master
  Switched to branch 'master'
  Your branch is behind 'origin/master' by 1 commit, and can be fast-forwarded.

$git pull
  Updating 4eb5499..db82e7c
  Fast-forward

$git merge dev //to update my changes on master
$git push

  with this done my remote is updated with my changes. both on dev/master branch.

  Now I have switched my branch again.

$git checkout dev
$git stash pop
  Auto-merging **file1**
  CONFLICT (content): Merge conflict in **file1**

  As i have done
$git status

  On branch dev
  Your branch is up-to-date with 'origin/dev'.

Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

   So I have performed the following
$ git reset HEAD

$ git status
  On branch dev
  Your branch is up-to-date with 'origin/dev'.

  Changes not staged for commit:
    (use "git add <file>..." to update what will be committed)
    (use "git checkout -- <file>..." to discard changes in working directory)

$ git stash list
  stash@{0}: WIP on dev: 4eb5499 //I want the changes which are here.
  stash@{1}: WIP on master: 9dac6b5

$ git stash pop
  error: Your local changes to the following files would be overwritten by merge:

I just want my stashed files to be used again.

Body:
I found that git has added few lines on the files, which looks like there is some bug in the files (by compiler), So went into file and deleted the lines added by git

<<<<<<< Updated upstream

between this
code may be replicated again please check and delete.

=======
>>>>>>> Stashed changes


问:
Get GitHub account using StackExchange API
I am trying to use the StackExchange API to retrieve the GitHub link a user has set in his profile.

I am talking about this one:

However I'm not finding methods to retrieve that data. I'm also not sure whether the API offers access to that data.

Here are some documentations I found:

https://api.stackexchange.com/docs/users

https://api.stackexchange.com/2.2/users/?order=desc&sort=reputation&site=stackoverflow

So can I use this API to retrieve the GitHub account of a user?

答: There is nothing in the API for a users a git hub account.</p>


问:
c# sql server backup percent read
sql command

```<code>BACKUP DATABASE [databasesample] TO  DISK = N'D:\kkk\test.bat' WITH  INIT ,  NOUNLOAD ,
NAME = N'name test',  NOSKIP ,
STATS = 5,  DESCRIPTION = N'test',  NOFORMAT
</code>```

result

```<code>5 percent processed.
10 percent processed.
15 percent processed.
20 percent processed.
25 percent processed.
30 percent processed.
35 percent processed.
40 percent processed.
45 percent processed.
50 percent processed.
55 percent processed.
60 percent processed.
65 percent processed.
70 percent processed.
75 percent processed.
80 percent processed.
85 percent processed.
90 percent processed.
95 percent processed.
Processed 30960 pages for database 'databasesample', file 'sample_Data' on file 1.
100 percent processed.
</code>```

I want to catch the percentage with C#. I think BeginExecuteNonQuery() function is done. but I do not know exactly how. Suggestions?

答:
Yes, as others have (now!) said, the SMO namespace is very useful.  Here's a snippet from my backup application.  it's in VB, not C#, and it runs the backup synchronously, unlike the earlier example, but it works well.  We run it in a loop for all the 20-odd databases on our server.  Very reliable.

```<code>Dim bkp As Backup = New Backup()
With bkp

    .Devices.AddDevice(Me.currentBackupFileName, DeviceType.File)

    .Database = conn.DatabaseName
    .Action = BackupActionType.Database
    .Initialize = True
    .PercentCompleteNotification = 20
    AddHandler .PercentComplete, AddressOf HandleBackupProgress
    .SqlBackup(svr)

    Me.backupFiles.Add(Me.currentBackupFileName)

End With
</code>```

The handler receives a PercentCompleteEventArgs e  as its argument, and you just pull the percentage complete out of it using e.Percent.

Title: c# sql server backup percent read

Body:
sql command

BACKUP DATABASE [databasesample] TO  DISK = N'D:\kkk\test.bat' WITH  INIT ,  NOUNLOAD ,
NAME = N'name test',  NOSKIP ,
STATS = 5,  DESCRIPTION = N'test',  NOFORMAT

result

5 percent processed.
10 percent processed.
15 percent processed.
20 percent processed.
25 percent processed.
30 percent processed.
35 percent processed.
40 percent processed.
45 percent processed.
50 percent processed.
55 percent processed.
60 percent processed.
65 percent processed.
70 percent processed.
75 percent processed.
80 percent processed.
85 percent processed.
90 percent processed.
95 percent processed.
Processed 30960 pages for database 'databasesample', file 'sample_Data' on file 1.
100 percent processed.

I want to catch the percentage with C#. I think BeginExecuteNonQuery() function is done. but I do not know exactly how. Suggestions?

Body:
Yes, as others have (now!) said, the SMO namespace is very useful.  Here's a snippet from my backup application.  it's in VB, not C#, and it runs the backup synchronously, unlike the earlier example, but it works well.  We run it in a loop for all the 20-odd databases on our server.  Very reliable.

Dim bkp As Backup = New Backup()
With bkp

    .Devices.AddDevice(Me.currentBackupFileName, DeviceType.File)

    .Database = conn.DatabaseName
    .Action = BackupActionType.Database
    .Initialize = True
    .PercentCompleteNotification = 20
    AddHandler .PercentComplete, AddressOf HandleBackupProgress
    .SqlBackup(svr)

    Me.backupFiles.Add(Me.currentBackupFileName)

End With

The handler receives a PercentCompleteEventArgs e  as its argument, and you just pull the percentage complete out of it using e.Percent.


问:
Rerunning program on MARS-simulator without resetting memory
I want to test my program on random inputs, but each time I reset it, all of the registers and data reset.

Is it possible to run the program again without the registers and data resetting each time?

答: If there's no other way, the best option I found is just adding a chunk of code that adds the values to all the registers/data before running the actual program.</p>


问:
Angular 4 Enum doesn't update in list
I have a field (item.state) in my list (*ngFor) that I load from API, treat in a method and display in the screen this way:

```<code><div class="posts col-md-12" *ngFor="let item of objectives.results" (click)="openItem(modalObjective, item)">
        <div class="row">
            <h4 class="col-md-11">{{item.title}}</h4>
        </div>
        <div class="row">
            <span class="col-md-2">{{item.description}}</span>
            <span class="col-md-3">{{item.ownerPersonName}}</span>
            <span class="col-md-3">{{setStateEnum(item.state)}}</span>
            <div class="progress col-md-4">
                <span class="col-md-2">{{item.state}}%</span>
                <div class="progress-bar" role="progressbar" aria-valuenow="70" aria-valuemin="0" aria-valuemax="100" style="width:70%">
                    <span class="sr-only">70% Complete</span>
                </div>
            </div>
        </div>
    </div>
</code>```

When click in an item, I display a modal with the details of this item. In this modal, I can change the "state" of this item through a "select html component". It's ok, but, when I change the state and close the modal, this item has a state updated, but this time with a number. The property is not getting into the method "setStateEnum" again, this just show the value returned from API (an integer). How can I do to every time I update a state, the property pass into "setStateEnum" method again to show the string value?

setStateEnum method in TS:

```<code>rivate setStateEnum(state: any) {
    switch (state) {
        case 0:
            return "Waiting";
        case 1:
            return "Running";
        case 2:
            return "Finished";
        case 3:
            return "Approved";
        default:
            return state;
    }
}
</code>```

Thanks!

UPDATE

I just needed to add a parseInt to my switch case and than it worked!! Like masterfloda said. The problem is: the property was passing through the method "setStateEnum" and going to "default", because the method was receiving a string from the update!

Like this:

```<code>private setStateEnum(state: any) {
    switch (parseInt(state)) {
        case 0:
            return "Waiting";
        case 1:
            return "Running";
        case 2:
            return "Finished";
        case 3:
            return "Approved";
        default:
            return state;
    }
}
</code>```

答:
My guess is that after you change state, it is a string, not an integer and that's why the switch goes to default:. And you don't get an error, because the method accepts any parameter type.

Try checking for switch(parseInt(state)):

Although the cleaner way would be passing an integer to the method and changing the parameter declaration to state: number, because then you will be informed about malformated input parameters.

Title: Angular 4 Enum doesn't update in list

Body:
I have a field (item.state) in my list (*ngFor) that I load from API, treat in a method and display in the screen this way:

{{item.title}}

            {{item.description}}
            {{item.ownerPersonName}}
            {{setStateEnum(item.state)}}

                {{item.state}}%

                    70% Complete

When click in an item, I display a modal with the details of this item. In this modal, I can change the "state" of this item through a "select html component". It's ok, but, when I change the state and close the modal, this item has a state updated, but this time with a number. The property is not getting into the method "setStateEnum" again, this just show the value returned from API (an integer). How can I do to every time I update a state, the property pass into "setStateEnum" method again to show the string value?

setStateEnum method in TS:

rivate setStateEnum(state: any) {
    switch (state) {
        case 0:
            return "Waiting";
        case 1:
            return "Running";
        case 2:
            return "Finished";
        case 3:
            return "Approved";
        default:
            return state;
    }
}

Thanks!

UPDATE

I just needed to add a parseInt to my switch case and than it worked!! Like masterfloda said. The problem is: the property was passing through the method "setStateEnum" and going to "default", because the method was receiving a string from the update!

Like this:

private setStateEnum(state: any) {
    switch (parseInt(state)) {
        case 0:
            return "Waiting";
        case 1:
            return "Running";
        case 2:
            return "Finished";
        case 3:
            return "Approved";
        default:
            return state;
    }
}


问:
Using Timestamp as ModifiedDate in the Azure Table Storage
I was using the Timestamp column of an Azure Table as ModifiedDateTime for MyEntity, and locally it seems pretty cool.

But once on the server, is not really clear if the TimeStamp is in local server time or in the UTC... because apprears the question how to display that column to the users...

NB 1

I did some tests, and the timestamp seem to follow the current UTC time, but I am not sure is because of the rule, or because the server actual location is in same timezone as the UK's UTC...

NB 2

There was already a similar question in this thread... but I didn't find something in the azure documentation explicitly on the Timestamp.

答:
The built-in Timestamp property is of type DateTime, which is UTC-based, and maintained by the storage service.

You can see this defined here.


问:
Can I move from one TextBox to another TextBox by pressing the enter button on the keyboard?
I have two files test.py and test.kv.

I want to move from one TextBox to another TextBox by pressing the enter key. How can this be accomplished?

test.py

```<code>from kivy.uix.screenmanager import Screen
from kivy.app import App
from kivy.lang import Builder
from kivy.core.window import Window
from kivy.properties import ObjectProperty

Window.size = (500, 330)

class TestScreen(Screen):
    popup = ObjectProperty(None)

class Test(App):
    def build(self):
        self.root = Builder.load_file('test.kv')
        return self.root

if __name__ == '__main__':
    Test().run()
</code>```

test.kv

```<code>#:kivy 1.10.0
TestScreen:

    GridLayout:
        cols: 2
        padding : 30,30
        spacing: 10, 10
        row_default_height: '40dp'

        Label:
            text: 'Name'

        TextInput:
            id: name

        Label:
            text: 'Class'

        TextInput:
            id: clas

        Button:
            text: 'Ok'

        Button:
            text: 'Cancel'
</code>```

答:
Since you want to use Enter to change the focus, I guess you do not want a multiline texinput. Therefore, one option would be use on_text_validate event:

on_text_validate

  Fired only in multiline=False mode when the user hits ‘enter’. This will also unfocus the textinput.

In your kv file you can do something like:

```<code>#:kivy 1.10.0
TestScreen:

    GridLayout:
        cols: 2
        padding : 30,30
        spacing: 10, 10
        row_default_height: '40dp'

        Label:
            text: 'Name'

        TextInput:
            id: name
            multiline: False
            on_text_validate: clas.focus = True   # <<<<<<<<<<<

        Label:
            text: 'Class'

        TextInput:
            id: clas
            multiline: False

        Button:
            text: 'Ok'

        Button:
            text: 'Cancel'
</code>```

Body:
I have two files test.py and test.kv.

I want to move from one TextBox to another TextBox by pressing the enter key. How can this be accomplished?

test.py

from kivy.uix.screenmanager import Screen
from kivy.app import App
from kivy.lang import Builder
from kivy.core.window import Window
from kivy.properties import ObjectProperty

Window.size = (500, 330)

class TestScreen(Screen):
    popup = ObjectProperty(None)

class Test(App):
    def build(self):
        self.root = Builder.load_file('test.kv')
        return self.root

if __name__ == '__main__':
    Test().run()

test.kv

#:kivy 1.10.0
TestScreen:

    GridLayout:
        cols: 2
        padding : 30,30
        spacing: 10, 10
        row_default_height: '40dp'

        Label:
            text: 'Name'

        TextInput:
            id: name

        Label:
            text: 'Class'

        TextInput:
            id: clas

        Button:
            text: 'Ok'

        Button:
            text: 'Cancel'

Body:
Since you want to use Enter to change the focus, I guess you do not want a multiline texinput. Therefore, one option would be use on_text_validate event:

on_text_validate

  Fired only in multiline=False mode when the user hits ‘enter’. This will also unfocus the textinput.

In your kv file you can do something like:

#:kivy 1.10.0
TestScreen:

    GridLayout:
        cols: 2
        padding : 30,30
        spacing: 10, 10
        row_default_height: '40dp'

        Label:
            text: 'Name'

        TextInput:
            id: name
            multiline: False
            on_text_validate: clas.focus = True   # <<<<<<<<<<<

        Label:
            text: 'Class'

        TextInput:
            id: clas
            multiline: False

        Button:
            text: 'Ok'

        Button:
            text: 'Cancel'


问:
is there A Communication Manager for vue components?
I was Vue.js now for a project and created and used a lot of components.
Now I started to have the problem  of having too many eventemitters and props that I need to keep track of.

I guess to illustrate the problem  the best I will use an example:

Lets say you have a main.vue and 2 or 3 Components.
One contains a button that should manipulate the other 2 components or switch them out.

Now I need to emit an event to the main.vue and then main.vue has to change a binded variable and pass props down to the other 2 components.
Alright: Now lets put the button in a component of of a component. You need to make sure that every link between a parent and a child is correct.

Now create a bit project and put a button in another components and you have to change everything.

So is there a good way to avoid this?
Something like a broadcast function so that every component is receiving the event?
Or a Manager that is handling the communication of all components?

答:
use a flux pattern (vuex)

At first you may think that this does not really answer the question, since it deals with storage of data, and not handling of events. The flux pattern changes the architecture of your application by creating a single store (think database) that all components can read and write from. Coupled with the reactive nature of the reactive frameworks such as vue (or react), the components will react to a change in data. So instead of tightly coupling component A to D through B and C, you'd have component A listen to mutations in object X, and component D makes changes to object X. When the change happens, component A gets updated without having to listen to any of the children's $emit functions firing. At first it may seem daunting, but the investment is worthwhile.


问:
PHP string array to php array
I have this string array:

```<code>["652","110","111","1032","118","416","147","121","112","1033","113","1031","868"]
</code>```

I need to read each value so to get

```<code>652
110
111
1032
</code>```

i try to convert string array using explode and then foreach but is not working...

```<code>$channels = explode('"', $string_array);

foreach($channels as &$channel) {
    echo $channel.'<br>';
}
</code>```

Title: PHP string array to php array

Body:
I have this string array:

["652","110","111","1032","118","416","147","121","112","1033","113","1031","868"]

I need to read each value so to get

652
110
111
1032

i try to convert string array using explode and then foreach but is not working...

$channels = explode('"', $string_array);

foreach($channels as &$channel) {
    echo $channel.'
';
}

Body:
it's an JSON format, so use json_decode

$json = '["652","110","111","1032","118","416","147","121","112","1033","113","1031","868"]';
$array = json_decode($json, true);
foreach($array AS $channel) {
    echo $channel.'<br>';
}


问:
Web app with RingCentral API
I am trying to get my C# web application to log into RingCentral using their API.
I am new to using Web API, and not sure how to use RC.  I have viewed their docs, but I have had no success. https://github.com/ringcentral/ringcentral-csharp-client

I know my credz work, because I can log into their portal, and all my key's have not changed.

First error I receive when adding the "await" key word is it want to change my method from Page_Load to an "async" method.
Secondly is page inheritance should this be System.web.ui.page or Ringcentral.page?

In the end I want to be able to login and retrieve inbound and outbound call logs and display them in a gridview.

I am using VS 2017, and it's a Web Forms app. I did NOT choose MVC or Web API.
I can't even break on a break point.

```<code>  public partial class _Default : Page
{
    //https://github.com/ringcentral/ringcentral-csharp-client

    private static String appKey = ConfigurationManager.AppSettings["appKey"].ToString();
    private static String appSecret = ConfigurationManager.AppSettings["appSecretKey"].ToString();
    private static bool isProduction = Convert.ToBoolean(ConfigurationManager.AppSettings["IsProduction"].ToString());

    private static String userName = ConfigurationManager.AppSettings["username"].ToString();
    private static String extension = ConfigurationManager.AppSettings["extension"].ToString();
    private static String password = ConfigurationManager.AppSettings["password"].ToString();
    private RestClient rc = null;

    protected async void Page_LoadAsync(object sender, EventArgs e)
    {

        rc = new RestClient(appKey, appSecret, isProduction);
        await rc.Authorize(userName, extension, password);

    }
}
</code>```

An example web app or stubbed out code for a web app would be very helpful.
Thanks,
KSS

答:
An example web app or stubbed out code for a web app would be very helpful.

For an example web app using the RingCentral C# Client SDK, see the following OAuth Auth Code demo which uses the Nancy web framework (http://nancyfx.org/).

https://github.com/ringcentral/ringcentral-demos-oauth/tree/master/csharp-nancy

Title: Web app with RingCentral API

Body:
I am trying to get my C# web application to log into RingCentral using their API.
I am new to using Web API, and not sure how to use RC.  I have viewed their docs, but I have had no success. https://github.com/ringcentral/ringcentral-csharp-client

I know my credz work, because I can log into their portal, and all my key's have not changed.

First error I receive when adding the "await" key word is it want to change my method from Page_Load to an "async" method.
Secondly is page inheritance should this be System.web.ui.page or Ringcentral.page?

In the end I want to be able to login and retrieve inbound and outbound call logs and display them in a gridview.

I am using VS 2017, and it's a Web Forms app. I did NOT choose MVC or Web API.
I can't even break on a break point.

  public partial class _Default : Page
{
    //https://github.com/ringcentral/ringcentral-csharp-client

    private static String appKey = ConfigurationManager.AppSettings["appKey"].ToString();
    private static String appSecret = ConfigurationManager.AppSettings["appSecretKey"].ToString();
    private static bool isProduction = Convert.ToBoolean(ConfigurationManager.AppSettings["IsProduction"].ToString());

    private static String userName = ConfigurationManager.AppSettings["username"].ToString();
    private static String extension = ConfigurationManager.AppSettings["extension"].ToString();
    private static String password = ConfigurationManager.AppSettings["password"].ToString();
    private RestClient rc = null;

    protected async void Page_LoadAsync(object sender, EventArgs e)
    {

        rc = new RestClient(appKey, appSecret, isProduction);
        await rc.Authorize(userName, extension, password);

    }
}

An example web app or stubbed out code for a web app would be very helpful.
Thanks,
KSS