问:
Initialise a class with a parameterized constructor in the constructor of a Service Class using Castle Windsor
Please note that I have changed the code in the question.

Please see the server side code below (WCF Service):

```<code>using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

using Castle.MicroKernel.Registration;
using Castle.MicroKernel.SubSystems.Configuration;
using Castle.Windsor;

namespace WcfService1
{
    public class WindsorInstaller : IWindsorInstaller
    {
        public void Install(IWindsorContainer container, IConfigurationStore store)
        {
            container.Register(
                Component.For<IGreeting, Greeting>(),
                Component.For<IGreetingService, GreetingService>());
        }
    }

    public interface ILanguage
    {
        string SayHello();
    }

    public class Spanish : ILanguage
    {
        public string SayHello()
        {
            return "Hola";
        }
    }

    public interface IGreeting
    {
        string SayHello();
    }

    public class Greeting: IGreeting
    {
        ILanguage Language;

        public Greeting (ILanguage language)
        {
            Language = language;
        }

        public string SayHello()
        {
            return Language.SayHello();
        }
    }

    public interface IGreetingFactory
    {
        IGreeting Create(ILanguage Language);
    }

    [ServiceContract]
    public interface IGreetingService
    {
        [OperationContract]
        string SayHello(string strLanguage);
    }

    public class GreetingService : IGreetingService
    {
        private readonly IGreetingFactory greetingFactory;
        private IGreeting greeting;

        public GreetingService()
        {
        }

        public GreetingService(IGreetingFactory greetingFactory)
        {
            // store the factory until we need it
            this.greetingFactory = greetingFactory;
        }

        public string SayHello (string strLanguage)
        {
            if (strLanguage == "S")
            {
                ILanguage Language = new Spanish();
                Language = new Spanish();
                greeting = new Greeting(Language);
            }
            return greeting.SayHello();
        }

    }
}
</code>```

and the client side code below:

```<code>ServiceReference1.GreetingServiceClient s1 = new ServiceReference1.GreetingServiceClient();
            string greeting = s1.SayHello("S");
</code>```

ServiceReference1.GreetingServiceClient is a service reference.

The code works as I would expect i.e. Castle Windsor allows me to inject a Greeting into the constructor of the service.  However, the Greeting class itself has a parameterized constructor (it requires a Language).  In the code above I have to initialise the Greeting (with a language) in the Say Hello method of the service.  How can I initialise the Greeting (with a language) in the constructor of the service?

答:
One primary method* of providing run-time, user-driven, or otherwise dynamic dependencies is using factories to create your objects.  Castle Windsor provides several different facilities to help with this, or you can use the kernel and implement a factory yourself.

Windsor's facility allows you to provide delegate-based factories, which are just methods for creating an object.  You could use that here, but you lose some flexibility in what you can create (if you were to replace the implementation of ICalculator to some other class, you'd have to update this method).

For maximum flexibility, you'll want to use Windsor's interface-based factories.  With these, you provide a factory's interface and then Windsor will generate an implementation of it automatically.

Let's use a simplified version of your code above as an example.  If you have just have this object:

```<code>public class Calculator : ICalculator
{
    string Operator;

    public Calculator(string operator)
    {
        Operator=operator;
    }
}
</code>```

And you wanted to pass operator in when you create the object, you'd define a factory like so:

```<code>public interface ICalculatorFactory
{
    ICalculator Create(string operator);
}
</code>```

Then you'd register it in your installer:

```<code>kernel.Register(Component.For<ICalulatorFactory>().AsFactory());
</code>```

Now, anywhere you wanted to use a calculator, you'd inject a factory for it, then just invoke Create:

```<code>public class CalculatorUseExample
{
    private readonly ICalculator addCalculator;
    private readonly ICalculator subCalculator;

    public CalculatorUseExample(ICalculatorFactory calculatorFactory)
    {
        addCalculator = calculatorFactory.Create("+");
        subCalculator = calculatorFactory.Create("-");
    }
}
</code>```

Note that the name of the operator parameter matters; by default (you can change this if you want), Windsor matches parameters by name.

If we add your CalculatorService class back into the mix, you could use the same pattern:

```<code>public interface ICalculatorServiceFactory
{
    ICalculatorService Create(string operator);
}

public class CalculatorService : ICalculatorService
{
    private readonly ICalculator Calculator;

    public CalculatorService(string operator, ICalculatorFactory calculatorFactory)
    {
        Calculator=calculatorFactory.Create(operator);
    }
}
</code>```

But I don't really like that because why should the service care what the operator is? That's a detail of the calculator.  Instead, change the factory to just accept an ICalculator and compose the objects together where you're creating this service:

```<code>public interface ICalculatorServiceFactory
{
    ICalculatorService Create(ICalculator calculator);
}

public class CalculatorService : ICalculatorService
{
    private readonly ICalculator Calculator;

    public CalculatorService(ICalculator calculator)
    {
        Calculator=calculator;
    }
}

public class CalculatorServiceUseExample
{
    public CalculatorServiceUseExample(ICalculatorServiceFactory calculatorServiceFactory, ICalculatorFactory calculatorFactory)
    {
        var addCalculator = calculatorFactory.Create("+");
        var service = calculatorServiceFactory.Create(addCalculator);

        // TODO: use the service
    }
}
</code>```

There are advantages and disadvantages to use this pattern, which I go over in my answer here.  Some advantages are that you can protect yourself from future changes and avoid service locator patterns.  Disadvantages include a proliferation of interface objects and potentially viral usage of factories (see my first solution above where we had to create another factory).

* There are others of course, this is just the way I'd solve this particular situation because, to me, it indicates intent and is the most discoverable for readers of your code.

Based on your edit regarding WCF and what I understand you're trying to do, I'd implement the service contract like so:

```<code>public class CalculatorService : ICalculatorService
{
    private readonly ICalculatorFactory calculatorFactory;
    private ICalculator calculator;

    public CalculatorService(ICalculatorFactory calculatorFactory)
    {
        // store the factory until we need it
        this.calculatorFactory = calculatorFactory;
    }

    public void ChangeCalculatorServiceClient(string operator)
    {
        // A new operator, we'll need a new calculator
        calculator = calculatorFactory.Create(operator);
    }
}
</code>```

Well, again you've changed your question to include another wrinkle; now you want to instantiate a different type based on a parameter.  You can and should still use a factory for this, and this is how I'd go about it:

```<code>using Castle.Facilities.TypedFactory;

public class WindsorInstaller : IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.Register(
            Component.For<IGreeting, Greeting>(),
            Component.For<IGreetingFactory>().AsFactory(),
            Component.For<IGreetingService, GreetingService>(),
            Component.For<ILanguageFactory, LanguageFactory>());
    }
}

public interface ILanguageFactory
{
    ILanguage Create(string language);
}

public class LanguageFactory : ILanguageFactory
{
    private readonly IKernel kernel;

    public LanguageFactory(IKernel kernel)
    {
        this.kernel = kernel;
    }

    public ILanguage Create(string language)
    {
        switch (language)
        {
            case "S":
                return kernel.Resolve<Spanish>();
            default:
                throw new ArgumentException();
        }
    }
}

public class GreetingService : IGreetingService
{
    private readonly IGreetingFactory greetingFactory;
    private readonly ILanguageFactory languageFactory;
    private IGreeting greeting;

    public GreetingService(IGreetingFactory greetingFactory, ILanguageFactory languageFactory)
    {
        // store the factory until we need it
        this.greetingFactory = greetingFactory;
    }

    public string SayHello (string strLanguage)
    {
        var language = languageFactory.Create(strLanguage);
        greeting = greetingFactory.Create(language);
        return greeting.SayHello();
    }
}
</code>```

Body:
Please note that I have changed the code in the question.

Please see the server side code below (WCF Service):

using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

using Castle.MicroKernel.Registration;
using Castle.MicroKernel.SubSystems.Configuration;
using Castle.Windsor;

namespace WcfService1
{
    public class WindsorInstaller : IWindsorInstaller
    {
        public void Install(IWindsorContainer container, IConfigurationStore store)
        {
            container.Register(
                Component.For<IGreeting, Greeting>(),
                Component.For<IGreetingService, GreetingService>());
        }
    }

    public interface ILanguage
    {
        string SayHello();
    }

    public class Spanish : ILanguage
    {
        public string SayHello()
        {
            return "Hola";
        }
    }

    public interface IGreeting
    {
        string SayHello();
    }

    public class Greeting: IGreeting
    {
        ILanguage Language;

        public Greeting (ILanguage language)
        {
            Language = language;
        }

        public string SayHello()
        {
            return Language.SayHello();
        }
    }

    public interface IGreetingFactory
    {
        IGreeting Create(ILanguage Language);
    }

    [ServiceContract]
    public interface IGreetingService
    {
        [OperationContract]
        string SayHello(string strLanguage);
    }

    public class GreetingService : IGreetingService
    {
        private readonly IGreetingFactory greetingFactory;
        private IGreeting greeting;

        public GreetingService()
        {
        }

        public GreetingService(IGreetingFactory greetingFactory)
        {
            // store the factory until we need it
            this.greetingFactory = greetingFactory;
        }

        public string SayHello (string strLanguage)
        {
            if (strLanguage == "S")
            {
                ILanguage Language = new Spanish();
                Language = new Spanish();
                greeting = new Greeting(Language);
            }
            return greeting.SayHello();
        }

    }
}

and the client side code below:

ServiceReference1.GreetingServiceClient s1 = new ServiceReference1.GreetingServiceClient();
            string greeting = s1.SayHello("S");

ServiceReference1.GreetingServiceClient is a service reference.

The code works as I would expect i.e. Castle Windsor allows me to inject a Greeting into the constructor of the service.  However, the Greeting class itself has a parameterized constructor (it requires a Language).  In the code above I have to initialise the Greeting (with a language) in the Say Hello method of the service.  How can I initialise the Greeting (with a language) in the constructor of the service?

Body:
One primary method* of providing run-time, user-driven, or otherwise dynamic dependencies is using factories to create your objects.  Castle Windsor provides several different facilities to help with this, or you can use the kernel and implement a factory yourself.

Windsor's facility allows you to provide delegate-based factories, which are just methods for creating an object.  You could use that here, but you lose some flexibility in what you can create (if you were to replace the implementation of ICalculator to some other class, you'd have to update this method).

For maximum flexibility, you'll want to use Windsor's interface-based factories.  With these, you provide a factory's interface and then Windsor will generate an implementation of it automatically.

Let's use a simplified version of your code above as an example.  If you have just have this object:

public class Calculator : ICalculator
{
    string Operator;

    public Calculator(string operator)
    {
        Operator=operator;
    }
}

And you wanted to pass operator in when you create the object, you'd define a factory like so:

public interface ICalculatorFactory
{
    ICalculator Create(string operator);
}

Then you'd register it in your installer:

kernel.Register(Component.For<ICalulatorFactory>().AsFactory());

Now, anywhere you wanted to use a calculator, you'd inject a factory for it, then just invoke Create:

public class CalculatorUseExample
{
    private readonly ICalculator addCalculator;
    private readonly ICalculator subCalculator;

    public CalculatorUseExample(ICalculatorFactory calculatorFactory)
    {
        addCalculator = calculatorFactory.Create("+");
        subCalculator = calculatorFactory.Create("-");
    }
}

Note that the name of the operator parameter matters; by default (you can change this if you want), Windsor matches parameters by name.

If we add your CalculatorService class back into the mix, you could use the same pattern:

public interface ICalculatorServiceFactory
{
    ICalculatorService Create(string operator);
}

public class CalculatorService : ICalculatorService
{
    private readonly ICalculator Calculator;

    public CalculatorService(string operator, ICalculatorFactory calculatorFactory)
    {
        Calculator=calculatorFactory.Create(operator);
    }
}

But I don't really like that because why should the service care what the operator is? That's a detail of the calculator.  Instead, change the factory to just accept an ICalculator and compose the objects together where you're creating this service:

public interface ICalculatorServiceFactory
{
    ICalculatorService Create(ICalculator calculator);
}

public class CalculatorService : ICalculatorService
{
    private readonly ICalculator Calculator;

    public CalculatorService(ICalculator calculator)
    {
        Calculator=calculator;
    }
}

public class CalculatorServiceUseExample
{
    public CalculatorServiceUseExample(ICalculatorServiceFactory calculatorServiceFactory, ICalculatorFactory calculatorFactory)
    {
        var addCalculator = calculatorFactory.Create("+");
        var service = calculatorServiceFactory.Create(addCalculator);

        // TODO: use the service
    }
}

There are advantages and disadvantages to use this pattern, which I go over in my answer here.  Some advantages are that you can protect yourself from future changes and avoid service locator patterns.  Disadvantages include a proliferation of interface objects and potentially viral usage of factories (see my first solution above where we had to create another factory).

* There are others of course, this is just the way I'd solve this particular situation because, to me, it indicates intent and is the most discoverable for readers of your code.

Based on your edit regarding WCF and what I understand you're trying to do, I'd implement the service contract like so:

public class CalculatorService : ICalculatorService
{
    private readonly ICalculatorFactory calculatorFactory;
    private ICalculator calculator;

    public CalculatorService(ICalculatorFactory calculatorFactory)
    {
        // store the factory until we need it
        this.calculatorFactory = calculatorFactory;
    }

    public void ChangeCalculatorServiceClient(string operator)
    {
        // A new operator, we'll need a new calculator
        calculator = calculatorFactory.Create(operator);
    }
}

Well, again you've changed your question to include another wrinkle; now you want to instantiate a different type based on a parameter.  You can and should still use a factory for this, and this is how I'd go about it:

using Castle.Facilities.TypedFactory;

public class WindsorInstaller : IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.Register(
            Component.For<IGreeting, Greeting>(),
            Component.For<IGreetingFactory>().AsFactory(),
            Component.For<IGreetingService, GreetingService>(),
            Component.For<ILanguageFactory, LanguageFactory>());
    }
}

public interface ILanguageFactory
{
    ILanguage Create(string language);
}

public class LanguageFactory : ILanguageFactory
{
    private readonly IKernel kernel;

    public LanguageFactory(IKernel kernel)
    {
        this.kernel = kernel;
    }

    public ILanguage Create(string language)
    {
        switch (language)
        {
            case "S":
                return kernel.Resolve<Spanish>();
            default:
                throw new ArgumentException();
        }
    }
}

public class GreetingService : IGreetingService
{
    private readonly IGreetingFactory greetingFactory;
    private readonly ILanguageFactory languageFactory;
    private IGreeting greeting;

    public GreetingService(IGreetingFactory greetingFactory, ILanguageFactory languageFactory)
    {
        // store the factory until we need it
        this.greetingFactory = greetingFactory;
    }

    public string SayHello (string strLanguage)
    {
        var language = languageFactory.Create(strLanguage);
        greeting = greetingFactory.Create(language);
        return greeting.SayHello();
    }
}


来源: stackexchange

问:
How to apply similar rules to many cells in Excel 2016?
Disclaimer: I'm pretty novice at excel.

I have 2 rules:

If the dropdown cell = Used, then color itself and the 4 cells to the left yellow.

If the dropdown cell = Available, then color itself and the 4 cells to the left Green.

```<code>Rule                  Format                  Applies to
=$G$5="Used"          Yellow Fill             =$C$5:$G$5
=$G$5="Available"     Green Fill              =$C$5:$G$5
</code>```

My question is: How can I apply these 2 rules to about 2000 other cells in the G column?

ex:

```<code>Rule                  Format                  Applies to
=$G$401="Used"          Yellow Fill           =$C$401:$G$401
=$G$401="Available"     Green Fill            =$C$401:$G$401
</code>```

答:
Change the Row in the formula to be relative:

```<code>=$G5="Used"
</code>```

And the Applies to: to:

```<code>=$C$5:$G$2000
</code>```

Do the same to the other formula and Applies To: range.

ContentLicense: CC BY-SA 3.0

Body:
Disclaimer: I'm pretty novice at excel.

I have 2 rules:

If the dropdown cell = Used, then color itself and the 4 cells to the left yellow.

If the dropdown cell = Available, then color itself and the 4 cells to the left Green.

Rule                  Format                  Applies to
=$G$5="Used"          Yellow Fill             =$C$5:$G$5
=$G$5="Available"     Green Fill              =$C$5:$G$5

My question is: How can I apply these 2 rules to about 2000 other cells in the G column?

ex:

Rule                  Format                  Applies to
=$G$401="Used"          Yellow Fill           =$C$401:$G$401
=$G$401="Available"     Green Fill            =$C$401:$G$401

Body:
Change the Row in the formula to be relative:

=$G5="Used"

And the Applies to: to:

=$C$5:$G$2000

Do the same to the other formula and Applies To: range.


问:
Access ViewController in DependencyService to present MFMailComposeViewController
How can i access the ViewController in my DependencyService to present a MFMailComposeViewController? I tried using Application.Context but this seems to be only working on Android. Any advice?</p>

答:
I would like to add an additional answer based off of the KeyWindow not always being the main window.  (this occurs when you are presenting your controller after the user has interacted with an action sheet or alert dialog)

```<code>public static UIViewController GetCurrentUIController()
    {
        UIViewController viewController;
        var window = UIApplication.SharedApplication.KeyWindow;
        if (window == null)
        {
            throw new InvalidOperationException("There's no current active window");
        }

        if (window.RootViewController.PresentedViewController == null)
        {
            window = UIApplication.SharedApplication.Windows
                     .First(i => i.RootViewController != null &&
                                 i.RootViewController.GetType().FullName
                                 .Contains(typeof(Xamarin.Forms.Platform.iOS.Platform).FullName));
        }

        viewController = window.RootViewController;

        while (viewController.PresentedViewController != null)
        {
            viewController = viewController.PresentedViewController;
        }

        return viewController;
    }
</code>```

This will guarantee that you get the Xamarin Forms platform renderer window, then find the foremost presented ViewController and return it for use presenting whatever UI or view controller you need to present.

Body:
I would like to add an additional answer based off of the KeyWindow not always being the main window.  (this occurs when you are presenting your controller after the user has interacted with an action sheet or alert dialog)

public static UIViewController GetCurrentUIController()
    {
        UIViewController viewController;
        var window = UIApplication.SharedApplication.KeyWindow;
        if (window == null)
        {
            throw new InvalidOperationException("There's no current active window");
        }

        if (window.RootViewController.PresentedViewController == null)
        {
            window = UIApplication.SharedApplication.Windows
                     .First(i => i.RootViewController != null &&
                                 i.RootViewController.GetType().FullName
                                 .Contains(typeof(Xamarin.Forms.Platform.iOS.Platform).FullName));
        }

        viewController = window.RootViewController;

        while (viewController.PresentedViewController != null)
        {
            viewController = viewController.PresentedViewController;
        }

        return viewController;
    }

This will guarantee that you get the Xamarin Forms platform renderer window, then find the foremost presented ViewController and return it for use presenting whatever UI or view controller you need to present.


问:
Overlapping background image through different elements
How can I get the main background image (the topography) to start from the very top all the way to the very bottom.

The golden "bars/elements" and blue "bars/elements" functionality is that they are like an accordion. So by clicking them, the element below it becomes visible or vice versa. So the the topography would be overlapping the golden and blue bars and continuing to the next section be it either another bar or the element that is visible. The topography image should never break throughout the entire page.

答:
It is not clear what do you mean by Topography but if you want an image to start from top and end at the bottom of the page, you can use the following method :

CSS:

```<code>.background {
  position: absolute;
  height: 100%;
  width: 100%;
  left: 0;
  top: 0;
  pointer-events: none;
}
</code>```

HTML:

```<code><body>
  <span class="background"><img src="xxxxx" /></span>
  <!-- your content goes here -->
</body>
</code>```

What this will do is, create a div that will be equal to the height of the body tag and will be always aligned to the top left corner of the page. The image may get skewed.

I hope this helps.

Body:
It is not clear what do you mean by Topography but if you want an image to start from top and end at the bottom of the page, you can use the following method :

CSS:

.background {
  position: absolute;
  height: 100%;
  width: 100%;
  left: 0;
  top: 0;
  pointer-events: none;
}

HTML:

<body>
  <span class="background"><img src="xxxxx" /></span>
  <!-- your content goes here -->
</body>

What this will do is, create a div that will be equal to the height of the body tag and will be always aligned to the top left corner of the page. The image may get skewed.

I hope this helps.


问:
Process isn't responding Android studio emulator
Everytime I run the android studio, it gives me the error message "Process isn't responding"  I am so confused, since yesterday emulator worked good. But today suddenly it doesn't work

答:
Try changing RAM size and resolution of your emulator and you should decrease them .
see this page : Error Message: emulator-arm.exe has stopped working</p>


问:
Image didn't load in JPanel
I have a JPanel name "imagePanel" and a button name "browseBtn". All contained in a JFrame class. When pressing the browseBtn, a file chooser will open up and after choosing a PNG image file, the image will appear directly in the imagePanel.

This is the action event for the browseBtn

```<code>private void browseBtnActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
      JFileChooser fc = new JFileChooser();
    int result = fc.showOpenDialog(null);
    if (result == JFileChooser.APPROVE_OPTION) {
        File file = fc.getSelectedFile();
        if (accept(file)) {
            try {
                ImageIcon image = new ImageIcon(file.getPath());
                JLabel l = new JLabel(image);
                imagePanel.add(l);
            } catch (Exception e) {
                JOptionPane.showMessageDialog(this, "Error reading file !");
            }
        }
        else {
            JOptionPane.showMessageDialog(this, "Choose png file only !");
        }
    }

}

public boolean accept(File file) {
    return file.isDirectory() || file.getAbsolutePath().endsWith(".png");
}
</code>```

I have choose the correct .png file but i don't understand why the image didn't show up in the imagePanel. Can you guy explain on that ?
Cheers.

答:
Or you might try this :</p>

```<code>browseBtn.addActionListener(new ActionListener() {
@Override
 public void actionPerformed(ActionEvent e) {
  JFileChooser fc = new JFileChooser();
  int result = fc.showOpenDialog(null);
  if (result == JFileChooser.APPROVE_OPTION) {
  File file = fc.getSelectedFile();
  if (accept(file)) {
  try {
   ImageIcon imageIcon = new ImageIcon(new   ImageIcon(file.getPath()).getImage().getScaledInstance(20, 20,    Image.SCALE_DEFAULT)); //resizing
   label.setIcon(imageIcon);

  /*try { // or try this
     InputStream inStream =  this.getClass().getClassLoader().getResourceAsStream(file.getPath());
     BufferedImage img = ImageIO.read(inStream);
     Image rimg = img.getScaledInstance(width, height,  Image.SCALE_STANDARD);
     label.setIcon(rimg);
    } catch (IOException e) {}*/
  } catch (Exception ex) {JOptionPane.showMessageDialog(this, "Error reading file !");}
  } else {JOptionPane.showMessageDialog(this, "Choose png file  only  !");}
 }
 }
  public boolean accept(File file) {
   return file.isDirectory() || file.getAbsolutePath().endsWith(".png");
  }
 });
</code>```

Title: Image didn't load in JPanel

Body:
I have a JPanel name "imagePanel" and a button name "browseBtn". All contained in a JFrame class. When pressing the browseBtn, a file chooser will open up and after choosing a PNG image file, the image will appear directly in the imagePanel.

This is the action event for the browseBtn

private void browseBtnActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
      JFileChooser fc = new JFileChooser();
    int result = fc.showOpenDialog(null);
    if (result == JFileChooser.APPROVE_OPTION) {
        File file = fc.getSelectedFile();
        if (accept(file)) {
            try {
                ImageIcon image = new ImageIcon(file.getPath());
                JLabel l = new JLabel(image);
                imagePanel.add(l);
            } catch (Exception e) {
                JOptionPane.showMessageDialog(this, "Error reading file !");
            }
        }
        else {
            JOptionPane.showMessageDialog(this, "Choose png file only !");
        }
    }

}

public boolean accept(File file) {
    return file.isDirectory() || file.getAbsolutePath().endsWith(".png");
}

I have choose the correct .png file but i don't understand why the image didn't show up in the imagePanel. Can you guy explain on that ?
Cheers.

Body:
Or you might try this :

browseBtn.addActionListener(new ActionListener() {
@Override
 public void actionPerformed(ActionEvent e) {
  JFileChooser fc = new JFileChooser();
  int result = fc.showOpenDialog(null);
  if (result == JFileChooser.APPROVE_OPTION) {
  File file = fc.getSelectedFile();
  if (accept(file)) {
  try {
   ImageIcon imageIcon = new ImageIcon(new   ImageIcon(file.getPath()).getImage().getScaledInstance(20, 20,    Image.SCALE_DEFAULT)); //resizing
   label.setIcon(imageIcon);

  /*try { // or try this
     InputStream inStream =  this.getClass().getClassLoader().getResourceAsStream(file.getPath());
     BufferedImage img = ImageIO.read(inStream);
     Image rimg = img.getScaledInstance(width, height,  Image.SCALE_STANDARD);
     label.setIcon(rimg);
    } catch (IOException e) {}*/
  } catch (Exception ex) {JOptionPane.showMessageDialog(this, "Error reading file !");}
  } else {JOptionPane.showMessageDialog(this, "Choose png file  only  !");}
 }
 }
  public boolean accept(File file) {
   return file.isDirectory() || file.getAbsolutePath().endsWith(".png");
  }
 });


问:
Git refusing to merge unrelated histories on rebase
During git rebase origin/development the following error message is shown from Git:

```<code>fatal: refusing to merge unrelated histories
Error redoing merge 1234deadbeef1234deadbeef
</code>```

My Git version is 2.9.0. It used to work fine in the previous version.

How can I continue this rebase allowing unrelated histories with the forced flag introduced in the new release?

答:
I got this error when I set up a local repository first. Then I went to GitHub and created a new repository. Then I ran

```<code>git remote add origin <repository url>
</code>```

When I tried to push or pull, I got the same fatal: unrelated_histories error every time.

Here is how I fixed it:

```<code>git pull origin master --allow-unrelated-histories
git merge origin origin/master
... add and commit here...
git push origin master
</code>```

ContentLicense: CC BY-SA 4.0

Body:
During git rebase origin/development the following error message is shown from Git:

fatal: refusing to merge unrelated histories
Error redoing merge 1234deadbeef1234deadbeef

My Git version is 2.9.0. It used to work fine in the previous version.

How can I continue this rebase allowing unrelated histories with the forced flag introduced in the new release?

Body:
I got this error when I set up a local repository first. Then I went to GitHub and created a new repository. Then I ran

git remote add origin <repository url>

When I tried to push or pull, I got the same fatal: unrelated_histories error every time.

Here is how I fixed it:

git pull origin master --allow-unrelated-histories
git merge origin origin/master
... add and commit here...
git push origin master


问:
Turn Off Translucent Bars on SFSafariViewController
In iOS 10, Apple added the property PreferredBarTintColor to set the color of the NavigationBar at the top and TabBar at the bottom to match the color of your app.  Which is great, except that the bars have translucency turned on, which I prefer to have turned off in my app.

Is there a way to turn off this transparency, which causes the colors in my app to not match up?

The color of my app looks like below image

But SafariViewController looks like below one

答: From iOS 11, Apple solved this problem and it should not be transparant anymore!</p>


问:
md5() works with literal, but not with column data
While testing out PostgreSQL's md5() function I noticed very bizarre behavior:

Works as expected

```<code>SELECT md5('abc')
--"900150983cd24fb0d6963f7d28e17f72"
</code>```

But using the md5() function in a query:

```<code>SELECT request_id, md5(request_id)
FROM Request
ORDER BY request_id
</code>```

results in this error:

```<code>ERROR:  function md5(integer) does not exist
LINE 1: SELECT request_id, md5(request_id)
                           ^
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.

********** Error **********

ERROR: function md5(integer) does not exist
SQL state: 42883
Hint: No function matches the given name and argument types. You might need to add explicit type casts.
Character: 20
</code>```

How can the function not exist if it worked in the first query? What am I doing wrong; what is the correct way to use md5() in a SELECT query?

答:
I'm just trying to generate a non-obvious, non-repeating, value which
  can be used to look-up a record.

What you need is a bijective hash. I use the CRC CPU function in a custom C function. For CPUs that don't have the function, one can use a lookup table.

This approach is guaranteed to give you a unique "random looking" number for every unique 32-bit input.

If you know how to generate C functions (not trivial), it will be a simple task to look up how to use CRC.

Body:
While testing out PostgreSQL's md5() function I noticed very bizarre behavior:

Works as expected

SELECT md5('abc')
--"900150983cd24fb0d6963f7d28e17f72"

But using the md5() function in a query:

SELECT request_id, md5(request_id)
FROM Request
ORDER BY request_id

results in this error:

ERROR:  function md5(integer) does not exist
LINE 1: SELECT request_id, md5(request_id)
                           ^
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.

********** Error **********

ERROR: function md5(integer) does not exist
SQL state: 42883
Hint: No function matches the given name and argument types. You might need to add explicit type casts.
Character: 20

How can the function not exist if it worked in the first query? What am I doing wrong; what is the correct way to use md5() in a SELECT query?


问:
How to select all checkboxes with a class name inside a table by table id
I have several tables on my page, and a table with the id of workOneTable. I have several rows in the table with class name of .rsvLine and more with class name .vtoLine. I need to be able to select all checkboxes in workOneTable with class name .rsvLine.
I have tried several things.

```<code>$( '#workOneTable :checkbox.rsvLine' ).prop( 'checked', this.checked );

$( '#workOneTable' ).find( 'input[type=checkbox]' ).prop( 'checked', true );

$( '#workOneTable tbody .rsvLine :checkbox' ).prop( 'checked' );
</code>```

Any help is greatly appreciated.

EDIT

Here is the most relevant part of the html code.

```<code><table id=workOneTable>
<thead>
    several rows here
</thead>
<tbody>
    <tr>
        <td class="rsvLine"><input type="checkbox" ></td>
        <td class="rsvLine"><input type="checkbox" ></td>
        <td class="rsvLine"><input type="checkbox" ></td>
        <td class="vtoLine"><input type="checkbox" ></td>
        <td class="vtoLine"><input type="checkbox" ></td>
        <td class="vtoLine"><input type="checkbox" ></td>
        <td class="rsvLine">other stuff</td>
        <td class="rsvLine">other stuff</td>
    </tr>
</tbody>
</code>```

I can select the right ones if I do not use the table id. It will select the .rsvLine in all tables. this is the code I used for that.

```<code>$( '.rsvLine :checkbox' ).each( function ()
            {
                if ( !$( this ).prop( "checked" ) )
                {
                    this.click();
                }
            } );
</code>```

答:
You don't need to use the "each" method. This is enough:</p>

```<code>$("#workOneTable td.rsvLine :checkbox").prop("checked", true);
</code>```

Body:
I have several tables on my page, and a table with the id of workOneTable. I have several rows in the table with class name of .rsvLine and more with class name .vtoLine. I need to be able to select all checkboxes in workOneTable with class name .rsvLine.
I have tried several things.

$( '#workOneTable :checkbox.rsvLine' ).prop( 'checked', this.checked );

$( '#workOneTable' ).find( 'input[type=checkbox]' ).prop( 'checked', true );

$( '#workOneTable tbody .rsvLine :checkbox' ).prop( 'checked' );

Any help is greatly appreciated.

EDIT

Here is the most relevant part of the html code.

    several rows here

        <input type="checkbox" >
        <input type="checkbox" >
        <input type="checkbox" >
        <input type="checkbox" >
        <input type="checkbox" >
        <input type="checkbox" >
        other stuff
        other stuff

I can select the right ones if I do not use the table id. It will select the .rsvLine in all tables. this is the code I used for that.

$( '.rsvLine :checkbox' ).each( function ()
            {
                if ( !$( this ).prop( "checked" ) )
                {
                    this.click();
                }
            } );

Body:
You don't need to use the "each" method. This is enough:

$("#workOneTable td.rsvLine :checkbox").prop("checked", true);


问:
Azure Search to return ONLY record count
I have the situation in Azure Search where I need to return ONLY count of matched search results- and not the actual results (will be done separately based on user request). This to reduce payload and hence improve performance.

When I use these parameters to the searchindex
$count=true&search=ruby,
I get @odata.count": 373 but also get the 373 records

I am able to reduce the records returned by introducing $skip but this is inefficient

Is there a way to only get result count and not the actual records

答: You can use the query parameter $top=0. The docs are here.


问:
Can't create procedure and function in sql plus oracle
Can't create any procedure/function in pl/sql. Always getting procedure created with compilation error. Last try with following code

```<code>SQL>  CREATE OR REPLACE PROCEDURE REPORT(NAME VARCHAR2, VERSION VARCHAR2,
  2     STARTDATE DATE, ENDDATE DATE) AS
  3   BEGIN
  4   END REPORT;
  5   /

Warning: Procedure created with compilation errors.

SQL> show error procedure report;
Errors for PROCEDURE REPORT:

LINE/COL ERROR
-------- -----------------------------------------------------------------
4/2      PLS-00103: Encountered the symbol "END" when expecting one of the
         following:
         begin case declare exit for goto if loop mod null pragma
         raise return select update while with <an identifier>
         <a double-quoted delimited-identifier> <a bind variable> <<
         close current delete fetch lock insert open rollback
         savepoint set sql execute commit forall merge pipe
</code>```

function

```<code>CREATE OR REPLACE FUNCTION GETEMPSALARY (EMPNUMBER IN INTEGER) RETURN INTEGER
IS
DECLARE
EMPSALARY INTEGER;
BEGIN
SELECT SAL INTO EMPSALARY FROM EMP WHERE EMP.EMPNO = EMPNUMBER;
RETURN EMPSALARY;
END GETEMPSALARY;
/
</code>```

any suggestions ?

答:
Your procedure has no statements.  At least put a
NULL statement in there to get it to compile:</p>

```<code>CREATE OR REPLACE PROCEDURE REPORT(NAME VARCHAR2, VERSION VARCHAR2,
      STARTDATE DATE, ENDDATE DATE) AS
BEGIN
  NULL;
END REPORT;
</code>```

Body:
Can't create any procedure/function in pl/sql. Always getting procedure created with compilation error. Last try with following code

SQL>  CREATE OR REPLACE PROCEDURE REPORT(NAME VARCHAR2, VERSION VARCHAR2,
  2     STARTDATE DATE, ENDDATE DATE) AS
  3   BEGIN
  4   END REPORT;
  5   /

Warning: Procedure created with compilation errors.

SQL> show error procedure report;
Errors for PROCEDURE REPORT:

LINE/COL ERROR
-------- -----------------------------------------------------------------
4/2      PLS-00103: Encountered the symbol "END" when expecting one of the
         following:
         begin case declare exit for goto if loop mod null pragma
         raise return select update while with <an identifier>
           <<
         close current delete fetch lock insert open rollback
         savepoint set sql execute commit forall merge pipe

function

CREATE OR REPLACE FUNCTION GETEMPSALARY (EMPNUMBER IN INTEGER) RETURN INTEGER
IS
DECLARE
EMPSALARY INTEGER;
BEGIN
SELECT SAL INTO EMPSALARY FROM EMP WHERE EMP.EMPNO = EMPNUMBER;
RETURN EMPSALARY;
END GETEMPSALARY;
/

any suggestions ?

Body:
Your procedure has no statements.  At least put a
NULL statement in there to get it to compile:

CREATE OR REPLACE PROCEDURE REPORT(NAME VARCHAR2, VERSION VARCHAR2,
      STARTDATE DATE, ENDDATE DATE) AS
BEGIN
  NULL;
END REPORT;


问:
Get All StreamField Blocks of Specific Type
I have created a custom photoBlock to embed photos in a blog post. I am trying to create a template tag that would allow me to get every photoBlock that is stored in the database, almost like you query pages in Wagtail. I would prefer not to have to create a separate page for every photo, but instead be able to display them on a different page if possible via the template tag.

```<code>class photoBlock(blocks.StructBlock):
     date = blocks.DateBlock("Date Image Was Taken")
     location = blocks.CharBlock(max_length=100)
     image = ImageChooserBlock()
     latitude = blocks.DecimalBlock(max_digits=9, decimal_places=6)
     longitude = blocks.DecimalBlock(max_digits=9, decimal_places=6)
     description = blocks.RichTextBlock()
</code>```

I am able to get the following to work, but it feels like the query is very heavy and will get bogged down once I have a bunch of posts.

```<code>for page in BlogPage.objects.all():
     for block in page.body.stream_data:
          if block['type'] == 'photoBlock':
               return block
</code>```

Is there any better way to query a specific block from Streamfield? Anytime I try something like this

```<code>photoBlock.objects.all()
</code>```

I always get an error response that photoBlock doesn't have attribute Object. Any ideas?

答: Unfortunately there's no more efficient way to query StreamField blocks than looping over all the pages that contain them, as you're doing in your code snippet. This is a limitation of StreamField's implementation - the data is stored as a string of JSON on the page object, rather than the blocks being "true" database objects.</p>

Body:
I have created a custom photoBlock to embed photos in a blog post. I am trying to create a template tag that would allow me to get every photoBlock that is stored in the database, almost like you query pages in Wagtail. I would prefer not to have to create a separate page for every photo, but instead be able to display them on a different page if possible via the template tag.

class photoBlock(blocks.StructBlock):
     date = blocks.DateBlock("Date Image Was Taken")
     location = blocks.CharBlock(max_length=100)
     image = ImageChooserBlock()
     latitude = blocks.DecimalBlock(max_digits=9, decimal_places=6)
     longitude = blocks.DecimalBlock(max_digits=9, decimal_places=6)
     description = blocks.RichTextBlock()

I am able to get the following to work, but it feels like the query is very heavy and will get bogged down once I have a bunch of posts.

for page in BlogPage.objects.all():
     for block in page.body.stream_data:
          if block['type'] == 'photoBlock':
               return block

Is there any better way to query a specific block from Streamfield? Anytime I try something like this

photoBlock.objects.all()

I always get an error response that photoBlock doesn't have attribute Object. Any ideas?


问:
What difference is there between calling tkinter.mainloop() and window.mainloop()?
If I want to create an empty window (i.e. one with no widgets) I can do so by running a program with this code:

```<code>import tkinter
window = tkinter.Tk()
window.mainloop()
</code>```

I can make (apparently) the same thing with the code:

```<code>import tkinter
window = tkinter.Tk()
tkinter.mainloop()
</code>```

What, if anything, is the overall difference between the two pieces of code? In addition, could there be a situation in which the two lines

```<code>tkinter.mainloop()
</code>```

and

```<code>window.mainloop()
</code>```

result in a visibly different output?

答:
What difference is there between calling tkinter.mainloop() and window.mainloop()?

There is no difference.

Body:
If I want to create an empty window (i.e. one with no widgets) I can do so by running a program with this code:

import tkinter
window = tkinter.Tk()
window.mainloop()

I can make (apparently) the same thing with the code:

import tkinter
window = tkinter.Tk()
tkinter.mainloop()

What, if anything, is the overall difference between the two pieces of code? In addition, could there be a situation in which the two lines

tkinter.mainloop()

and

window.mainloop()

result in a visibly different output?


问:
Laravel Project table default unit
I have got a Laravel Projetk where I have a table (time, track, length). If a user make a input I want that per default der is "km"(length) or "min"(time), so that the user only has to tipe a number but in the table stands a unit next to the number.

```<code>            $table->string('track', 150);
</code>```

Thats how i put numbers in my table.

答:
I belive the best way is convert the data.

Using mask in the view

Convert to persist um database

Title: Laravel Project table default unit

Body:
I have got a Laravel Projetk where I have a table (time, track, length). If a user make a input I want that per default der is "km"(length) or "min"(time), so that the user only has to tipe a number but in the table stands a unit next to the number.

            $table->string('track', 150);

Thats how i put numbers in my table.


问:
Regex: How to get regex matches to overlap?
I have a string formatted as follows:

'0 = text defining value 1 = text2 2 = text3, text3 (text3) 3 = text4'

with an unknown number of values. I'm trying to get a regex to match the 0 and 'text defining value' together for each number description pair. Right now, I have

'([0-9]{1,2}) ?= ?(.*?) ?[0-9]{0,2} ?[=$]'

as my regex, but this only matches to every other value in the field. Any suggestions on how to get it to match to all of them?

Thanks

答:
You can use lookahead to figure out where the next partition is:

```<code>import re

pattern = re.compile(r"(\d+)\s+=\s+(.*?)(?=\s+\d+\s+|$)")

your_text = "0 = text defining value 1 = text2 2 = text3, text3 (text3) 3 = text4"

pairs = pattern.findall(your_text)
# [('0', 'text defining value'),
#  ('1', 'text2'),
#  ('2', 'text3, text3 (text3)'),
#  ('3', 'text4')]
</code>```

If that's what you're looking for, your question is a bit murky.

Body:
You can use lookahead to figure out where the next partition is:

import re

pattern = re.compile(r"(\d+)\s+=\s+(.*?)(?=\s+\d+\s+|$)")

your_text = "0 = text defining value 1 = text2 2 = text3, text3 (text3) 3 = text4"

pairs = pattern.findall(your_text)
# [('0', 'text defining value'),
#  ('1', 'text2'),
#  ('2', 'text3, text3 (text3)'),
#  ('3', 'text4')]

If that's what you're looking for, your question is a bit murky.


问:
Ask the user to enter an integer that is over 500. Work out the square root of that number and display it to 2 decimal places
Iv been asked to write a program wich asks the user to enter an integer that is over 500. Then I need to work out the square root of that number and display it to 2 decimal places.

So far I have:

```<code>import math
mumber= int(input("Please enter a number over 500")
if number<500:
       print ("That's too low")
else:
      print (math.sqrt(number))
</code>```

Everything works but where do I place the print(round(number,2)) ?

EDIT:
I typed the code, so YES the indenting is wrong.

答:
You could do something like this:

```<code>import math

number = -1
while number < 500:
    number= int(input("Please enter a number over 500: "))
    if number < 500:
        print("Number entered is too low. Please enter a number that is larger than 500.")

print(round(math.sqrt(number), 2))
</code>```

Basically, it keeps asking for user input until the value is larger than 500.

If you later want to add checking to not allow float numbers to be entered but only have them enter integer values you can do this by just changing the loop a little:

```<code># Same as before
while number < 500:
    try:
        number= int(input("Please enter a number over 500: "))
    except ValueError:
        print("An integer value was not entered.")

# Same as before
</code>```

Credits to u/e4c5 for the round(math.sqrt(number), 2))

Body:
Iv been asked to write a program wich asks the user to enter an integer that is over 500. Then I need to work out the square root of that number and display it to 2 decimal places.

So far I have:

import math
mumber= int(input("Please enter a number over 500")
if number<500:
       print ("That's too low")
else:
      print (math.sqrt(number))

Everything works but where do I place the print(round(number,2)) ?

EDIT:
I typed the code, so YES the indenting is wrong.

Body:
You could do something like this:

import math

number = -1
while number < 500:
    number= int(input("Please enter a number over 500: "))
    if number < 500:
        print("Number entered is too low. Please enter a number that is larger than 500.")

print(round(math.sqrt(number), 2))

Basically, it keeps asking for user input until the value is larger than 500.

If you later want to add checking to not allow float numbers to be entered but only have them enter integer values you can do this by just changing the loop a little:

# Same as before
while number < 500:
    try:
        number= int(input("Please enter a number over 500: "))
    except ValueError:
        print("An integer value was not entered.")

# Same as before

Credits to u/e4c5 for the round(math.sqrt(number), 2))


问:
NXC communication through USB
How would you send data through the USB port and receive the data in my Linux machine?

```<code>task main ()
{
byte data[2] = {1,2};
while (1)
{
  Wait(1000);
  SetUSBOutputBuffer(0, 2, data);
}
}
</code>```

Compiled it with:

```<code>nbc -d -Z2 usb.nxc
</code>```

dmesg:

```<code>usb 2-1.2: reset full-speed USB device number 6 using ehci_hcd
</code>```

Now how do I get the "data" what was sent by the NXT?How would I write a Linux program in C that would read the USB buffer?

答: The Fantom SDK doesn't support Linux. Instead, use libnxt. The one in the Debian repositories is still being maintained.</p>

Title: NXC communication through USB

Body:
How would you send data through the USB port and receive the data in my Linux machine?

task main ()
{
byte data[2] = {1,2};
while (1)
{
  Wait(1000);
  SetUSBOutputBuffer(0, 2, data);
}
}

Compiled it with:

nbc -d -Z2 usb.nxc

dmesg:

usb 2-1.2: reset full-speed USB device number 6 using ehci_hcd

Now how do I get the "data" what was sent by the NXT?How would I write a Linux program in C that would read the USB buffer?


问:
Whenever I have two conflicting greater than how do I set a limit there
Hi I'm kind of new to programming. I used Game Maker before this so I need help.
Whenever I have two conflicting greater than how do I set a limit there. Example:
if (weight>=20): (print(example))
if (weight>=30): (print(example)) So if I were to type in 35 it would print both things. So how do I make it print only one thing. Thank you for your time.
P.S I'm using python 3.6.

答:
The answer is in the elif statement</p>

```<code>if x > a:
    # x is greater than a
    #do something
    pass
elif x > b:
    # x is not greater than a, but greater than b
    # do something
    pass
else:
    # do something else
    pass
</code>```

Body:
The answer is in the elif statement

if x > a:
    # x is greater than a
    #do something
    pass
elif x > b:
    # x is not greater than a, but greater than b
    # do something
    pass
else:
    # do something else
    pass


问:
XQuery library under Python
Is there any existing way to run XQuery under python? (not starting to build a parser yourself in other words).

I got a ton of legacy XQuery that I want to port to our new system, or rather I want to
port the framework and not XQuery.

Therefore: Is there any library  that allows me to run XQuery under python?

答:
I had problems like Ted and tried to use answer from vadim.
However, I had still problems to load zorba_api properly, complaining "ImportError DLL load failed" (not telling which one, using %1 as great nickname).

Finally, I got the solution:

Environment

WindowsXP

Python 2.6 installed at c:\Python26

Installation

Zorba 1.2 or 1.4 installed to standard location

Path to Zorba bin as first item in PATH

both files from Zorba bin\python (zorba_api.py and _zorba_api.pyd) moved to C:\Python26\LIB\site-packages

As result, I was able to run C:\Program Files\Zorba XQuery Processor 1.4.0\share\doc\zorba-1.4.0\python\examples\python_test.py from any folder in my computer, even without the python line, modifying PATH

NB:

PATH problem might be related to too long string there.

Process Monitor was of good help finding, which DLL cannot be loaded

ContentLicense: CC BY-SA 2.5

Title: XQuery library under Python


问:
how to write if statement in accordance to the "name" in a cell and the amount of characters
Using google docs script:

I want to write a code that will check all of row B(lets say B2), using a loop, and if it says "dogs" i want the correcponding cells(lets say D2) to have 8 characters("00000000") and have multiple of these with different words will check if the corresponding column has a certain number of characters.

I also want it to show an error if there is more or less than the allowed charaters in the correcsponding column.

答:
Try this:

```<code>function countChar(){

var ss = SpreadsheetApp.getActiveSpreadsheet();
 var sheet = ss.getSheets()[0];

  var range = sheet.getRange("B4");
  var char = range.getValue();
  Logger.log(char)
  Logger.log("length: "+ char.length);

}
</code>```

According to this document:

Google Apps Script is a scripting language based on JavaScript that lets you do new and cool things with G Suite products like Docs, Sheets, and Forms.

Since GAS is based from Javascript you can use JavaScript String length Property to get the length of a variable.

Hope this helps.

Body:
Try this:

function countChar(){

var ss = SpreadsheetApp.getActiveSpreadsheet();
 var sheet = ss.getSheets()[0];

  var range = sheet.getRange("B4");
  var char = range.getValue();
  Logger.log(char)
  Logger.log("length: "+ char.length);

}

According to this document:

Google Apps Script is a scripting language based on JavaScript that lets you do new and cool things with G Suite products like Docs, Sheets, and Forms.

Since GAS is based from Javascript you can use JavaScript String length Property to get the length of a variable.

Hope this helps.


问:
React - Separating app into multiple git repos
I wanted to get your input on a project I'm working on.
I have my main React App repo. From there my plan is to have a Component A repo and a Component B Repo. Then I would like to run my main App and if I load a certain route (/componentA) the component would be pulled in from the Component A git repo. Is this possible? Thanks in advance!</p>

答:
I have the solution for you.

https://lernajs.io/

lerna will enable you to have multiple repos talk to each other, and easily update one, to reflect on all the repos that uses it.

Splitting up large codebases into separate independently versioned packages is extremely useful for code sharing. However, making changes across many repositories is messy and difficult to track, and testing across repositories gets complicated really fast.

To solve these (and many other) problems, some projects will organize their codebases into multi-package repositories. Projects like Babel, React, Angular, Ember, Meteor, Jest, and many others develop all of their packages within a single repository.

Lerna is a tool that optimizes the workflow around managing multi-package repositories with git and npm.

jump to the get started to see how it works, I've started using it for our large code base, and its doing beautiful so far


问:
CASE Syntax error when > is used in the WHEN clause
This Query runs fine when I do not have the ">" symbol in the WHEN clause however I need this to work when the ProposalDate is any date later than '2017-04-10 00:00:00.000'. Not sure why I am getting a Syntax error when I add the > into the WHEN clause.</p>

```<code>SELECT *,
    CASE ProposalDate WHEN > '2017-04-10 00:00:00.000'
        THEN (OrderTotal - ProposalWholesalePrice) +
             (ProposalWholesalePrice * 1.02)
        ELSE OrderTotal
    END "New_OrderTotal"
FROM webservices.dbo.DT_Open_Orders_Baseprice
WHERE ProposalSerialNumber = '639036'
</code>```

答:
SQL CASE expression has two forms:

The simple CASE expression, and

The searched CASE expression.

Simple CASE, i.e. CASE ProposalDate WHEN ... cannot be used with comparison operators; you need a searched CASE instead:

```<code>SELECT
    *
,   CASE
        WHEN ProposalDate > '2017-04-10 00:00:00.000'
        THEN (OrderTotal - ProposalWholesalePrice) + (ProposalWholesalePrice * 1.02)
        ELSE OrderTotal
    END "New_OrderTotal"
FROM webservices.dbo.DT_Open_Orders_Baseprice
WHERE ProposalSerialNumber = '639036'
</code>```

Body:
This Query runs fine when I do not have the ">" symbol in the WHEN clause however I need this to work when the ProposalDate is any date later than '2017-04-10 00:00:00.000'. Not sure why I am getting a Syntax error when I add the > into the WHEN clause.

SELECT *,
    CASE ProposalDate WHEN > '2017-04-10 00:00:00.000'
        THEN (OrderTotal - ProposalWholesalePrice) +
             (ProposalWholesalePrice * 1.02)
        ELSE OrderTotal
    END "New_OrderTotal"
FROM webservices.dbo.DT_Open_Orders_Baseprice
WHERE ProposalSerialNumber = '639036'

Body:
SQL CASE expression has two forms:

The simple CASE expression, and

The searched CASE expression.

Simple CASE, i.e. CASE ProposalDate WHEN ... cannot be used with comparison operators; you need a searched CASE instead:

SELECT
    *
,   CASE
        WHEN ProposalDate > '2017-04-10 00:00:00.000'
        THEN (OrderTotal - ProposalWholesalePrice) + (ProposalWholesalePrice * 1.02)
        ELSE OrderTotal
    END "New_OrderTotal"
FROM webservices.dbo.DT_Open_Orders_Baseprice
WHERE ProposalSerialNumber = '639036'


问:
Jquery toggle not working when toggling back
I am using jquery toggle, to show one image and then when the user clicks on an element, change to another image and if they click again show the original image. Like an open close kind of thing. It works when I first click, but nothing after that. Here is my jquery

```<code> $(".filterInventory").on("click", function () {

    $(".inventory-search").toggle();
    $(".filer-arrow.down").hide();
    $(".filer-arrow.up").show();

    return false;

});
</code>```

and here is the HTML

```<code><div class="container container-padding-top inventory-search-button">
        <div class="row">
            <div class="col-md-12">
                <a href="#" class="filterInventory">Filter <img src="~/Images/icons/down-arrow-white.png" class="filer-arrow down" alt="Filter Arrow" /><img src="~/Images/icons/up-arrow-white.png" class="filer-arrow up" alt="Filter Arrow" /></a>
            </div>
        </div>
    </div>
</code>```

CSS:

```<code>#communities a.filterInventory img.up {
    display: none;
}

#communities .filterInventory .filer-arrow {
    height: 10px;
}
</code>```

答:
```<code>$("#communities .inventory-search button.dropdown-toggle").on("click", function () {

        $("#communities .inventory-search button.dropdown-toggle").toggleClass('button-down', !state).toggleClass('button-up',state);

    });
</code>```

just jquery

Body:
I am using jquery toggle, to show one image and then when the user clicks on an element, change to another image and if they click again show the original image. Like an open close kind of thing. It works when I first click, but nothing after that. Here is my jquery

 $(".filterInventory").on("click", function () {

    $(".inventory-search").toggle();
    $(".filer-arrow.down").hide();
    $(".filer-arrow.up").show();

    return false;

});

and here is the HTML

                Filter

CSS:

#communities a.filterInventory img.up {
    display: none;
}

#communities .filterInventory .filer-arrow {
    height: 10px;
}

Body:
$("#communities .inventory-search button.dropdown-toggle").on("click", function () {

        $("#communities .inventory-search button.dropdown-toggle").toggleClass('button-down', !state).toggleClass('button-up',state);

    });

just jquery


问:
Rails 5 - Strong Parameters for Nested Attributes on Associated Objects
I am trying to create a nested attribute form for my Request model.

My parameters are not saving correctly when the Create action is triggered. Though in my console, the data is structured correctly for how I want it to be entered.

The :quantity attribute is on the JoinTable model of RequestDrink.

How can I white-list these parameters correctly?

Console Output

```<code>Started POST "/requests" for 127.0.0.1 at 2017-06-08 12:38:40 -0400
Processing by RequestsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"3ljcH44E7ZrEXNztlgGacyA0nyumNsTX6NyMMu9N+3SY0rCRXSsj/hsg0JP8jtVfDFkcEWOWHi/VwHrgertlLg==", "request"=>{"concierge_name"=>"Alex", "concierge_number"=>"954-123-4567", "concierge_email"=>"alex@email.com", "client_name"=>"Adam", "client_number"=>"954-765-4321", "client_email"=>"adam@email.com", "hotel_employee"=>"0", "concierge_service"=>"0", "vip_promoter"=>"0", "arriving_with_client"=>"1", "client_alone"=>"0", "males"=>"", "females"=>"1", "table_minimum"=>"1000", "event_date_id"=>"1", "arrival_time(1i)"=>"2017", "arrival_time(2i)"=>"6", "arrival_time(3i)"=>"8", "arrival_time(4i)"=>"16", "arrival_time(5i)"=>"38", "drinks_attributes"=>[{"id"=>"1", "quantity"=>"1"}, {"id"=>"2", "quantity"=>""}, {"id"=>"3", "quantity"=>""}, {"id"=>"4", "quantity"=>""}],  "commit"=>"Submit"}
Completed 404 Not Found in 18ms (ActiveRecord: 0.0ms)

ActiveRecord::RecordNotFound (Couldn't find Drink with ID=1 for Request with ID=):

app/controllers/requests_controller.rb:34:in `create'
</code>```

app/models/request.rb

```<code>class Request < ApplicationRecord
    has_many :request_drinks
    has_many :drinks, through: :request_drinks

    accepts_nested_attributes_for :drinks
end
</code>```

app/models/drinks.rb

```<code>class Drink < ApplicationRecord
    has_many :request_drinks
    has_many :requests, through: :request_drinks
end
</code>```

app/models/request_drink.rb

```<code>class RequestDrink < ApplicationRecord
    belongs_to :request
    belongs_to :drink
end
</code>```

app/controllers/request_controller.rb

```<code>class RequestsController < ApplicationController
  before_action :set_request, only: [:show,
                                     :edit,
                                     :update,
                                     :destroy]

  def index
    redirect_to root_path unless admin_signed_in?
    @requests = Request.search(params[:term], params[:filter], params[:page])
  end

  def show
  end

  def new
    @request = Request.new
    @drinks = Drink.active
    @chasers = Chaser.active
    @table_locations = TableLocation.active
    @event_dates = EventDate.active
  end

  def edit
  end

  def create
    @request = Request.new(request_params)
    @request.people = (@request.males || 0) + (@request.females || 0)

    @drinks = Drink.active
    @chasers = Chaser.active
    @table_locations = TableLocation.active
    @event_dates = EventDate.active

    respond_to do |format|
      if @request.save
        format.html { redirect_to thanks_path, notice: 'Request was successfully created.' }
        format.json { render :show, status: :created, location: @request }
      else
        format.html { render :new }
        format.json { render json: @request.errors, status: :unprocessable_entity }
      end
    end
  end

  def update
    respond_to do |format|
      if @request.update(request_params)
        format.html { redirect_to @request, notice: 'Request was successfully updated.' }
        format.json { render :show, status: :ok, location: @request }
      else
        format.html { render :edit }
        format.json { render json: @request.errors, status: :unprocessable_entity }
      end
    end
  end

  def destroy
    @request.destroy
    respond_to do |format|
      format.html { redirect_to requests_url, notice: 'Request was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private

    def set_request
      @request = Request.find(params[:id])
    end

    def request_params
      params.require(:request).permit(:concierge_name,
                                      :concierge_number,
                                      :concierge_email,
                                      :client_name,
                                      :client_number,
                                      :client_email,
                                      :hotel_employee,
                                      :concierge_service,
                                      :vip_promoter,
                                      :arriving_with_client,
                                      :client_alone,
                                      :people,
                                      :males,
                                      :females,
                                      :table_minimum,
                                      :arrival_time,
                                      :comments,
                                      :event_date_id,
                                      :drinks_attributes => [:id, :quantity]
      )
    end
end
</code>```

app/views/requests/_form.html.erb

```<code><%= form_with(model: request, local: true) do |f| %>
...
      <h4>Drinks</h4>
      <% @drinks.all.each do |d| %>
        <%= hidden_field_tag "request[drinks_attributes][][id]", d.id %>
        <%= number_field_tag "request[drinks_attributes][][quantity]", 0, in: 0..10 %>
        <%= d.name %>
        <br />
      <% end %>
...
<% end %>
</code>```

答:
The :quantity attribute is on the JoinTable model of RequestDrink.

Yet your are using drinks instead of request_drinks. Try changing your code to use the latter:

Model:

```<code>class Request < ApplicationRecord
  has_many :request_drinks
  has_many :drinks, through: :request_drinks

  accepts_nested_attributes_for :request_drinks
end
</code>```

View:

```<code>...
  <%= hidden_field_tag "request[request_drinks_attributes][][id]", d.id %>
  <%= number_field_tag "request[request_drinks_attributes][][quantity]", 0, in: 0..10 %>
...
</code>```

Controller:

```<code>class RequestsController < ApplicationController
  # other actions

  def request_params
    params.require(:request).permit(..., :request_drinks_attributes => [:id, :quantity])
  end
end
</code>```

Body:
I am trying to create a nested attribute form for my Request model.

My parameters are not saving correctly when the Create action is triggered. Though in my console, the data is structured correctly for how I want it to be entered.

The :quantity attribute is on the JoinTable model of RequestDrink.

How can I white-list these parameters correctly?

Console Output

Started POST "/requests" for 127.0.0.1 at 2017-06-08 12:38:40 -0400
Processing by RequestsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"3ljcH44E7ZrEXNztlgGacyA0nyumNsTX6NyMMu9N+3SY0rCRXSsj/hsg0JP8jtVfDFkcEWOWHi/VwHrgertlLg==", "request"=>{"concierge_name"=>"Alex", "concierge_number"=>"954-123-4567", "concierge_email"=>"alex@email.com", "client_name"=>"Adam", "client_number"=>"954-765-4321", "client_email"=>"adam@email.com", "hotel_employee"=>"0", "concierge_service"=>"0", "vip_promoter"=>"0", "arriving_with_client"=>"1", "client_alone"=>"0", "males"=>"", "females"=>"1", "table_minimum"=>"1000", "event_date_id"=>"1", "arrival_time(1i)"=>"2017", "arrival_time(2i)"=>"6", "arrival_time(3i)"=>"8", "arrival_time(4i)"=>"16", "arrival_time(5i)"=>"38", "drinks_attributes"=>[{"id"=>"1", "quantity"=>"1"}, {"id"=>"2", "quantity"=>""}, {"id"=>"3", "quantity"=>""}, {"id"=>"4", "quantity"=>""}],  "commit"=>"Submit"}
Completed 404 Not Found in 18ms (ActiveRecord: 0.0ms)

ActiveRecord::RecordNotFound (Couldn't find Drink with ID=1 for Request with ID=):

app/controllers/requests_controller.rb:34:in `create'

app/models/request.rb

class Request < ApplicationRecord
    has_many :request_drinks
    has_many :drinks, through: :request_drinks

    accepts_nested_attributes_for :drinks
end

app/models/drinks.rb

class Drink < ApplicationRecord
    has_many :request_drinks
    has_many :requests, through: :request_drinks
end

app/models/request_drink.rb

class RequestDrink < ApplicationRecord
    belongs_to :request
    belongs_to :drink
end

app/controllers/request_controller.rb

class RequestsController < ApplicationController
  before_action :set_request, only: [:show,
                                     :edit,
                                     :update,
                                     :destroy]

  def index
    redirect_to root_path unless admin_signed_in?
    @requests = Request.search(params[:term], params[:filter], params[:page])
  end

  def show
  end

  def new
    @request = Request.new
    @drinks = Drink.active
    @chasers = Chaser.active
    @table_locations = TableLocation.active
    @event_dates = EventDate.active
  end

  def edit
  end

  def create
    @request = Request.new(request_params)
    @request.people = (@request.males || 0) + (@request.females || 0)

    @drinks = Drink.active
    @chasers = Chaser.active
    @table_locations = TableLocation.active
    @event_dates = EventDate.active

    respond_to do |format|
      if @request.save
        format.html { redirect_to thanks_path, notice: 'Request was successfully created.' }
        format.json { render :show, status: :created, location: @request }
      else
        format.html { render :new }
        format.json { render json: @request.errors, status: :unprocessable_entity }
      end
    end
  end

  def update
    respond_to do |format|
      if @request.update(request_params)
        format.html { redirect_to @request, notice: 'Request was successfully updated.' }
        format.json { render :show, status: :ok, location: @request }
      else
        format.html { render :edit }
        format.json { render json: @request.errors, status: :unprocessable_entity }
      end
    end
  end

  def destroy
    @request.destroy
    respond_to do |format|
      format.html { redirect_to requests_url, notice: 'Request was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private

    def set_request
      @request = Request.find(params[:id])
    end

    def request_params
      params.require(:request).permit(:concierge_name,
                                      :concierge_number,
                                      :concierge_email,
                                      :client_name,
                                      :client_number,
                                      :client_email,
                                      :hotel_employee,
                                      :concierge_service,
                                      :vip_promoter,
                                      :arriving_with_client,
                                      :client_alone,
                                      :people,
                                      :males,
                                      :females,
                                      :table_minimum,
                                      :arrival_time,
                                      :comments,
                                      :event_date_id,
                                      :drinks_attributes => [:id, :quantity]
      )
    end
end

app/views/requests/_form.html.erb

<%= form_with(model: request, local: true) do |f| %>
...

Drinks

      <% @drinks.all.each do |d| %>
        <%= hidden_field_tag "request[drinks_attributes][][id]", d.id %>
        <%= number_field_tag "request[drinks_attributes][][quantity]", 0, in: 0..10 %>
        <%= d.name %>

      <% end %>
...
<% end %>

Body:
The :quantity attribute is on the JoinTable model of RequestDrink.

Yet your are using drinks instead of request_drinks. Try changing your code to use the latter:

Model:

class Request < ApplicationRecord
  has_many :request_drinks
  has_many :drinks, through: :request_drinks

  accepts_nested_attributes_for :request_drinks
end

View:

...
  <%= hidden_field_tag "request[request_drinks_attributes][][id]", d.id %>
  <%= number_field_tag "request[request_drinks_attributes][][quantity]", 0, in: 0..10 %>
...

Controller:

class RequestsController < ApplicationController
  # other actions

  def request_params
    params.require(:request).permit(..., :request_drinks_attributes => [:id, :quantity])
  end
end


问:
PushSharp's notification to Apple generate temp RSA files on server
I'm having a problem with my WCF push notification service.
Every time it sends a push notification to apple, a new RSA is generated inside the "C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys" folder.
I think that the problem causing this might be related to the Apple p12 Certificate.

Why does that happen? Is there any way to prevent the generating of those RSA?

I'm using PushSharp library and my code looks like this:

```<code>pushBroker = new PushBroker();
pushBroker.RegisterAppleService(
    new PushSharp.Apple.ApplePushChannelSettings(false, appleCert, p12Pass, false)
    , null);
</code>```

答:
The temporary file is where Windows has put the RSA private key that it loaded out of the appleCert PFX blob.

If the file appears, then disappears (since you called it a "temp" file), then everything's working as expected.  If it appears and stays forever then PushSharp is loading the certificate with PersistKeySet, which says that the private key shouldn't be deleted.

I don't know if https://github.com/has-taiar/PushSharp.Web/blob/master/PushSharp.Apple/ApplePushChannelSettings.cs is the real source of ApplePushChannelSettings, but it'll do.  Looking at that source, they seem to be using PersistKeySet, making the file permanent.

You have two practical approaches:

1) Load the certificate into an X509Store as a one-time operation (using PersistKeySet on load because you need to for store persistence).  The file becomes permanent, but gets used for forever, so it's cool.

2) Load the certificate yourself from the PFX and (ideally) Dispose the certificate when you're done.  I don't know if you have any sort of on-shutdown notification that you can more-or-less reliably use, but calling cert.Dispose() (or, on older Framework versions, cert.Close()) is more reliable than waiting on the GC and Finalizer to do the cleanup for you.

If you do have a good shutdown event:

```<code>// Note that I'm not specifying any X509KeyStorageFlags here.
// You don't want it PersistKeySet (that's the whole point) and you don't
// need it to be exportable (unless you get exceptions without Exportable, in which case
// PushSharp is doing something naughty).
private X509Certificate _cert = new X509Certificate2(appleCert, p12CerPass);

...
_broker.RegisterAppleService(new PushSharp.Apple.ApplePushChannelSettings(_cert, false));

...
// In some OnShutdown type location
_cert.Dispose();
</code>```

If not:

```<code>// Still don't specify any load flags.  Especially not PersistKeySet.
var cert = new X509Certificate2(appleCert, p12CerPass);
_broker.RegisterAppleService(new PushSharp.Apple.ApplePushChannelSettings(cert, false));
</code>```

No matter what you'll still end up with a permanently leaked file every time your process abnormally terminates, since the file-deletion code won't get a chance to kick in.

A solution exists to completely avoid creating the temporary file, and that is to use the EphemeralKeySet flag which was added to .NET Core 2.0 (currently in preview).  It's not yet available in .NET Framework.

```<code>// Keep the private key in memory, never let it touch the hard drive.
var cert = new X509Certificate2(appleCert, p12CerPass, X509KeyStorageFlags.EphemeralKeySet);
_broker.RegisterAppleService(new PushSharp.Apple.ApplePushChannelSettings(cert, false));
</code>```

But I don't know if PushSharp is available for .NET Core.

Body:
I'm having a problem with my WCF push notification service.
Every time it sends a push notification to apple, a new RSA is generated inside the "C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys" folder.
I think that the problem causing this might be related to the Apple p12 Certificate.

Why does that happen? Is there any way to prevent the generating of those RSA?

I'm using PushSharp library and my code looks like this:

pushBroker = new PushBroker();
pushBroker.RegisterAppleService(
    new PushSharp.Apple.ApplePushChannelSettings(false, appleCert, p12Pass, false)
    , null);

Body:
The temporary file is where Windows has put the RSA private key that it loaded out of the appleCert PFX blob.

If the file appears, then disappears (since you called it a "temp" file), then everything's working as expected.  If it appears and stays forever then PushSharp is loading the certificate with PersistKeySet, which says that the private key shouldn't be deleted.

I don't know if https://github.com/has-taiar/PushSharp.Web/blob/master/PushSharp.Apple/ApplePushChannelSettings.cs is the real source of ApplePushChannelSettings, but it'll do.  Looking at that source, they seem to be using PersistKeySet, making the file permanent.

You have two practical approaches:

1) Load the certificate into an X509Store as a one-time operation (using PersistKeySet on load because you need to for store persistence).  The file becomes permanent, but gets used for forever, so it's cool.

2) Load the certificate yourself from the PFX and (ideally) Dispose the certificate when you're done.  I don't know if you have any sort of on-shutdown notification that you can more-or-less reliably use, but calling cert.Dispose() (or, on older Framework versions, cert.Close()) is more reliable than waiting on the GC and Finalizer to do the cleanup for you.

If you do have a good shutdown event:

// Note that I'm not specifying any X509KeyStorageFlags here.
// You don't want it PersistKeySet (that's the whole point) and you don't
// need it to be exportable (unless you get exceptions without Exportable, in which case
// PushSharp is doing something naughty).
private X509Certificate _cert = new X509Certificate2(appleCert, p12CerPass);

...
_broker.RegisterAppleService(new PushSharp.Apple.ApplePushChannelSettings(_cert, false));

...
// In some OnShutdown type location
_cert.Dispose();

If not:

// Still don't specify any load flags.  Especially not PersistKeySet.
var cert = new X509Certificate2(appleCert, p12CerPass);
_broker.RegisterAppleService(new PushSharp.Apple.ApplePushChannelSettings(cert, false));

No matter what you'll still end up with a permanently leaked file every time your process abnormally terminates, since the file-deletion code won't get a chance to kick in.

A solution exists to completely avoid creating the temporary file, and that is to use the EphemeralKeySet flag which was added to .NET Core 2.0 (currently in preview).  It's not yet available in .NET Framework.

// Keep the private key in memory, never let it touch the hard drive.
var cert = new X509Certificate2(appleCert, p12CerPass, X509KeyStorageFlags.EphemeralKeySet);
_broker.RegisterAppleService(new PushSharp.Apple.ApplePushChannelSettings(cert, false));

But I don't know if PushSharp is available for .NET Core.


问:
How to test scalability and high availability of Kaa?
I need to collect the data and make analysis of scalability and high availability of Kaa IOT using Kaa cluster. What tool i need or any command if possible to represent its simulated data. So here i need two tools. first is tool for sending simulated data. second is tool to monitor scalability and HA.</p>

答:
For simulated data uploading you can use Data Collection demo application available from the Kaa Sandbox or Sample Applications repository on GitHub. With small modifications it can generate as much data as you need.

For the Kaa server load monitoring please read Kaa Performance monitoring documentation page. Please ignore its relation to Kaa 0.9 as it also aplies to the Kaa 0.10 (the new documentation lacks the respective page occasionally).


问:
How to filter on most recent value for specific column
Running a query that has multiple rows showing db table statistics, in both a before and after status after a scheduled job that runs on either Sat/Sun.

```<code>Select [batchNum] ,[RunDate] ,[tableName] ,[numberofRows] ,[dataSize]
FROM TableNames
ORDER BY RunDate ASC
</code>```

The before/after is differentiated by the batch number. So for example, this table has batch numbers 2-159. Where '158' is the 'before' job/batch from the scheduled job that ran this past weekend, and batch 159 would be the 'after.

```<code>    batchNum    RunDate             tableName   numberofRows    dataSize
    158         06/04/2017 04:30:51 TableData1  1700            104
    158         06/04/2017 04:30:51 TableData2  1276             99
    158         06/04/2017 04:30:51 TableData3  1700            157
    158         06/04/2017 04:30:51 TableData4   200             47

    159         06/04/2017 05:30:51 TableData1  1500             85
    159         06/04/2017 05:30:55 TableData2  1134             94
    159         06/04/2017 05:30:57 TableData3  1500            101
    159         06/04/2017 05:30:59 TableData4   167             40
</code>```

Since the batch will always be revolving, I'd like to filter this query to only return rows of most recent batchNum for the most recent weekend, any time i run it through out the year.

答:
```<code>Select [batchNum], [RunDate], [tableName], [numberofRows], [dataSize]
  FROM TableNames t1
 where not exists(select *
                    from TableNames t2
                   where t2.batchNum > t1.batchNum)
 ORDER BY RunDate ASC;
</code>```

Body:
Running a query that has multiple rows showing db table statistics, in both a before and after status after a scheduled job that runs on either Sat/Sun.

Select [batchNum] ,[RunDate] ,[tableName] ,[numberofRows] ,[dataSize]
FROM TableNames
ORDER BY RunDate ASC

The before/after is differentiated by the batch number. So for example, this table has batch numbers 2-159. Where '158' is the 'before' job/batch from the scheduled job that ran this past weekend, and batch 159 would be the 'after.

    batchNum    RunDate             tableName   numberofRows    dataSize
    158         06/04/2017 04:30:51 TableData1  1700            104
    158         06/04/2017 04:30:51 TableData2  1276             99
    158         06/04/2017 04:30:51 TableData3  1700            157
    158         06/04/2017 04:30:51 TableData4   200             47

    159         06/04/2017 05:30:51 TableData1  1500             85
    159         06/04/2017 05:30:55 TableData2  1134             94
    159         06/04/2017 05:30:57 TableData3  1500            101
    159         06/04/2017 05:30:59 TableData4   167             40

Since the batch will always be revolving, I'd like to filter this query to only return rows of most recent batchNum for the most recent weekend, any time i run it through out the year.


答:
Have you ever tried to put the "WHEN" before the column name?
For example:</p>

```<code>SELECT *, CASE WHEN ProposalDate > '2017-04-10 00:00:00.000'

THEN (OrderTotal - ProposalWholesalePrice) + (ProposalWholesalePrice * 1.02) ELSE OrderTotal

END "New_OrderTotal" FROM webservices.dbo.DT_Open_Orders_Baseprice WHERE ProposalSerialNumber = '639036'
</code>```

Title: CASE Syntax error when > is used in the WHEN clause

Body:
Have you ever tried to put the "WHEN" before the column name?
For example:

SELECT *, CASE WHEN ProposalDate > '2017-04-10 00:00:00.000'

THEN (OrderTotal - ProposalWholesalePrice) + (ProposalWholesalePrice * 1.02) ELSE OrderTotal

END "New_OrderTotal" FROM webservices.dbo.DT_Open_Orders_Baseprice WHERE ProposalSerialNumber = '639036'


问:
How do I adjust the transparency (alpha) of a button in Swift?
My button is flButton but when I try to set the alpha to 0, it gives me the error

Value of type '(Any) -> () has no member alpha".

Do I have to replace Any in the @IBAction line?

```<code>import UIKit

class FirstLaunchView: UIViewController {

    @IBOutlet weak var logo1: UIImageView!
    @IBOutlet weak var smiley1: UIImageView!
    @IBOutlet weak var subHapp1: UILabel!
    @IBOutlet weak var happ1: UILabel!
    @IBAction func flButton(_ sender: Any) {

        UserDefaults.standard.set(false, forKey: "name")
        //launchDetector = false

        performSegue(withIdentifier: "toMain", sender: self)
    }

    @IBOutlet weak var firstLaunch: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()

        logo1.alpha = 0
        smiley1.alpha = 0
        subHapp1.alpha = 0
        happ1.alpha = 0
        flButton.alpha = 0
    }
</code>```

答:
Your flButton is an @IBAction function. You should either create an @IBOutlet for your button or do this in your function if you want to keep it:

```<code>if let button = sender as? UIButton {
    button.alpha = 0
}
</code>```

Or you could just change the type of you @IBAction function from:

```<code>@IBAction func flButton(_ sender: Any)
</code>```

To:

```<code>@IBAction func flButton(_ sender: UIButton)
</code>```

And then just set sender.alpha = 0.

Body:
My button is flButton but when I try to set the alpha to 0, it gives me the error

Value of type '(Any) -> () has no member alpha".

Do I have to replace Any in the @IBAction line?

import UIKit

class FirstLaunchView: UIViewController {

    @IBOutlet weak var logo1: UIImageView!
    @IBOutlet weak var smiley1: UIImageView!
    @IBOutlet weak var subHapp1: UILabel!
    @IBOutlet weak var happ1: UILabel!
    @IBAction func flButton(_ sender: Any) {

        UserDefaults.standard.set(false, forKey: "name")
        //launchDetector = false

        performSegue(withIdentifier: "toMain", sender: self)
    }

    @IBOutlet weak var firstLaunch: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()

        logo1.alpha = 0
        smiley1.alpha = 0
        subHapp1.alpha = 0
        happ1.alpha = 0
        flButton.alpha = 0
    }

Body:
Your flButton is an @IBAction function. You should either create an @IBOutlet for your button or do this in your function if you want to keep it:

if let button = sender as? UIButton {
    button.alpha = 0
}

Or you could just change the type of you @IBAction function from:

@IBAction func flButton(_ sender: Any)

To:

@IBAction func flButton(_ sender: UIButton)

And then just set sender.alpha = 0.


问:
Calculate a group index across multiple columns of a data frame in R
What is the most efficient way to calculate a group index (group identifier) across multiple columns in a data frame  or data.table in R?

For example, in the data frame below, there are six unique combinations of columns A and B.

```<code>DF <- data.frame(a = rep(1:2,6), b = sort(letters[1:3]))

> DF
   a b
1  1 a
2  2 b
3  1 c
4  2 a
5  1 b
6  2 c
7  1 a
8  2 b
9  1 c
10 2 a
11 1 b
12 2 c
</code>```

I'd like to add column 'index' with a group identifier, like the one produced by this (obviously inefficient method for large data frames):

```<code>DF$index <- with(DF, as.numeric(factor(paste0(a, b))))

> DF
   a b index
1  1 a     1
2  2 b     5
3  1 c     3
4  2 a     4
5  1 b     2
6  2 c     6
7  1 a     1
8  2 b     5
9  1 c     3
10 2 a     4
11 1 b     2
12 2 c     6
</code>```

What's the fastest way to do this with very large data frames?

答:
How about this using data.table,

```<code>library(data.table)
setDT(df)[,group :=.GRP,by = .(a,b)]
</code>```

Output:

```<code>> df
    a b group
 1: 1 a     1
 2: 2 b     2
 3: 1 c     3
 4: 2 a     4
 5: 1 b     5
 6: 2 c     6
 7: 1 a     1
 8: 2 b     2
 9: 1 c     3
10: 2 a     4
11: 1 b     5
12: 2 c     6
</code>```

Body:
What is the most efficient way to calculate a group index (group identifier) across multiple columns in a data frame  or data.table in R?

For example, in the data frame below, there are six unique combinations of columns A and B.

DF <- data.frame(a = rep(1:2,6), b = sort(letters[1:3]))

> DF
   a b
1  1 a
2  2 b
3  1 c
4  2 a
5  1 b
6  2 c
7  1 a
8  2 b
9  1 c
10 2 a
11 1 b
12 2 c

I'd like to add column 'index' with a group identifier, like the one produced by this (obviously inefficient method for large data frames):

DF$index <- with(DF, as.numeric(factor(paste0(a, b))))

> DF
   a b index
1  1 a     1
2  2 b     5
3  1 c     3
4  2 a     4
5  1 b     2
6  2 c     6
7  1 a     1
8  2 b     5
9  1 c     3
10 2 a     4
11 1 b     2
12 2 c     6

What's the fastest way to do this with very large data frames?

Body:
How about this using data.table,

library(data.table)
setDT(df)[,group :=.GRP,by = .(a,b)]

Output:

> df
    a b group
 1: 1 a     1
 2: 2 b     2
 3: 1 c     3
 4: 2 a     4
 5: 1 b     5
 6: 2 c     6
 7: 1 a     1
 8: 2 b     2
 9: 1 c     3
10: 2 a     4
11: 1 b     5
12: 2 c     6


问:
Using plist in a DetailView
I have this tableview in my app which has a particular item name such as "Apple". When the user taps on that selected item they are directed to a detailView that views an image and description of that selected item. I was thinking to use plist´s to do this, but I don't know how to. Please help me.

I looked at some sources such as iCodeBlog but they don´t really explain retrieving and saving so well. Maybe you people can also give reference to some links that describe this better.

Heres a plist that I have tried. Each of the items (Orange, Apple) have the data that I want to display in my detailView. I basically want to display the data shown.

答:
Pass an NSString to the detail view and load the item based on the NSString, This could be a particular dictionary name, or item in an array.

```<code>newDetailViewController.currentItem = @"Array1";
</code>```

and in my detail view, define:

```<code>.h
    NSString *currentItem;
    @property(nonatomic,retain) NSString *currentItem;
.m
    @synthesize currentItem;
</code>```

Now currentItem in your detailView controller will be "Array1", since that is what we passed to it.

It all depends on really how your plist is setup, are you using an NSArray, an NSDictionary?

There are plenty of ways you can put this to use:

```<code>    NSString *current = [NSString stringWithFormat:@"%@/%@",appDocsPath,currentItem];
    NSMutableDictionary* dict = [[[NSMutableDictionary alloc] initWithContentsOfFile:current] autorelease];
</code>```

EDIT FROM QUESTION:
Using the example above:

```<code>aLabel.text = [dict objectForKey@"description"];
</code>```

Title: Using plist in a DetailView

Body:
Pass an NSString to the detail view and load the item based on the NSString, This could be a particular dictionary name, or item in an array.

newDetailViewController.currentItem = @"Array1";

and in my detail view, define:

.h
    NSString *currentItem;
    @property(nonatomic,retain) NSString *currentItem;
.m
    @synthesize currentItem;

Now currentItem in your detailView controller will be "Array1", since that is what we passed to it.

It all depends on really how your plist is setup, are you using an NSArray, an NSDictionary?

There are plenty of ways you can put this to use:

    NSString *current = [NSString stringWithFormat:@"%@/%@",appDocsPath,currentItem];
    NSMutableDictionary* dict = [[[NSMutableDictionary alloc] initWithContentsOfFile:current] autorelease];

EDIT FROM QUESTION:
Using the example above:

aLabel.text = [dict objectForKey@"description"];


问:
Locate a mouseover element using Selenium in Python?
I am trying to locate an element (a h3 tag which only shows up by hovering onto it). After some search, it seems like ActionChains in selenium is the way to go. The code has two steps: 1: locate the mouseover object and hovering onto it. step 2: locate the new appread h3 tag. So far, Step 1 is fine. But I got Unable to locate element: error for Step 2. For to mention, the appeared item an iframe object. Any suggestions are appreciated.

```<code>### Step 1: locate the mouseover object
each_username_h = review_block_html.find_element_by_xpath('.//div[starts-with(@class, "username")]')
Hover = ActionChains(driver).move_to_element(each_username_h)
Hover.perform()

### Step 2: locate new h3 tag
user_hyper_link = driver.find_element_by_xpath('.//h3[starts-with(@class, "username")]')
</code>```

Update (solved)

It seems like I need to click the hovered item. Then I also added a dynamic waiting item (thanks to michael satish) which makes sure to locate item when it is available.

```<code>### Step 1: locate the mouseover object
each_username_h = review_block_html.find_element_by_xpath('.//div[starts-with(@class, "username")]')
Hover = ActionChains(driver).move_to_element(each_username_h)
Hover.perform()

### Step 1.5: click the item
each_username_h.click()

### Step 2: locate new h3 tag
user_hyper_link = WebDriverWait(driver, 30).until(EC.visibility_of_element_located((By.XPATH, "//a[starts-with(@href, '/members/')]")))
</code>```

答:
check the time it takes for the new h3 tag to be available in DOM after hovering event.

May find_element_by_xpath is fired before the new h3 tag is created, if that the case you may want to dynamically wait for the new h3 tag

Body:
I am trying to locate an element (a h3 tag which only shows up by hovering onto it). After some search, it seems like ActionChains in selenium is the way to go. The code has two steps: 1: locate the mouseover object and hovering onto it. step 2: locate the new appread h3 tag. So far, Step 1 is fine. But I got Unable to locate element: error for Step 2. For to mention, the appeared item an iframe object. Any suggestions are appreciated.

### Step 1: locate the mouseover object
each_username_h = review_block_html.find_element_by_xpath('.//div[starts-with(@class, "username")]')
Hover = ActionChains(driver).move_to_element(each_username_h)
Hover.perform()

### Step 2: locate new h3 tag
user_hyper_link = driver.find_element_by_xpath('.//h3[starts-with(@class, "username")]')

Update (solved)

It seems like I need to click the hovered item. Then I also added a dynamic waiting item (thanks to michael satish) which makes sure to locate item when it is available.

### Step 1: locate the mouseover object
each_username_h = review_block_html.find_element_by_xpath('.//div[starts-with(@class, "username")]')
Hover = ActionChains(driver).move_to_element(each_username_h)
Hover.perform()

### Step 1.5: click the item
each_username_h.click()

### Step 2: locate new h3 tag
user_hyper_link = WebDriverWait(driver, 30).until(EC.visibility_of_element_located((By.XPATH, "//a[starts-with(@href, '/members/')]")))


问:
Using margin-top within a div applies margin to header
I'm trying to apply a margin to  text within a div, to have text centered horizontally and vertically. I'm not sure if there's a better way to do this, as I'm very new to HTML and programming in general.

Test Text

```

When I try to apply a margin to the
 element, the margin makes the header larger and doesn't affect the
 element's margin. How can I center an element vertically and horizontally? (The
 is a test. It will be replaced with a button)

答:
From the comments in your code it's clear that you are trying to create some navigation buttons. I'm not sure about bootstrap but in general I prefer using list items when I build navigation buttons. The reason is its really easy to control, edit and understand the structure.

Coming to your question, flex box are very comfortable to center align contents inside another, but I will not prefer that in this use case instead go with an,
or
 tag - > add the name inside and then set the gaps using padding.

```<code><ul class="navbtn">
      <li>button 1 </li>
      <li>button 2 </li>
      <li>button 3 </li>
</ul>
</code>```

Now the CSS will be

```<code>.navbtn li {
padding : 10px 5px;
}
</code>```

Play with the values as per your comfort
This will center align the text inside the box.

Using list item will be more conformable than anything else when it comes to adding navigation buttons.

Body:
I'm trying to apply a margin to  text within a div, to have text centered horizontally and vertically. I'm not sure if there's a better way to do this, as I'm very new to HTML and programming in general.

Test Text

When I try to apply a margin to the
 element, the margin makes the header larger and doesn't affect the
 element's margin. How can I center an element vertically and horizontally? (The
 is a test. It will be replaced with a button)

Body:
From the comments in your code it's clear that you are trying to create some navigation buttons. I'm not sure about bootstrap but in general I prefer using list items when I build navigation buttons. The reason is its really easy to control, edit and understand the structure.

Coming to your question, flex box are very comfortable to center align contents inside another, but I will not prefer that in this use case instead go with an, <li>or   <div> tag - > add the name inside and then set the gaps using padding.

<ul class="navbtn">
      <li>button 1 </li>
      <li>button 2 </li>
      <li>button 3 </li>
</ul>

Now the CSS will be

.navbtn li {
padding : 10px 5px;
}

Play with the values as per your comfort
This will center align the text inside the box.

Using list item will be more conformable than anything else when it comes to adding navigation buttons.