问:
Attempted to load class "MyApp" from namespace
I using symfony 2 and ratchet and memcache on a websocket chat project ratchet working good with symfony and i tested it on the "hello world" app on the offical web site docs
but the problem is when I run this line

```<code>    new Chat(new MyApp(), $this->getContainer()),
</code>```

i get this error

```<code>Attempted to load class "MyApp" from namespace
</code>```

my command line code

```<code><?php
// myapplication/src/sandboxBundle/Command/SocketCommand.php
// Change the namespace according to your bundle
namespace check\roomsBundle\Command;
use Ratchet\Session\SessionProvider;
use Symfony\Component\HttpFoundation\Session\Storage\Handler;
use Doctrine\Common\Cache\MemcacheCache;
use Ratchet\App;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\HttpFoundation\Session\Storage\Handler\MemcacheSessionHandler;
use Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage;
// Include ratchet libs
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
// Change the namespace according to your bundle
use check\roomsBundle\Sockets\Chat;
use Doctrine\ORM\EntityManager;
use Symfony\Component\HttpFoundation\Session\Session;

class WsServerCommand extends ContainerAwareCommand
{
    protected function configure()
    {
        $this->setName('sockets:start-chat')
            // the short description shown while running "php bin/console list"
            ->setHelp("Starts the chat socket demo")
            // the full command description shown when running the command with
            ->setDescription('Starts the chat socket demo')
        ;    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $output->writeln([
            'Chat socket',// A line
            '============',// Another line
            'Starting chat, open your browser.',// Empty line
        ]);
        $memcache = new \Memcache;
        $memcache->connect('localhost', 11211);

        $session = new SessionProvider(
            new Chat(new MyApp(), $this->getContainer()),
            new Handler\MemcacheSessionHandler($memcache)
        );

        $server = new App('localhost');
        $server->route('/sessDemo', $session);
        $server->run();
    }
}
</code>```

the Chat.php code

```<code><?php
namespace check\roomsBundle\Sockets;
use tuto\testBundle\Entity\Users;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Ratchet\WebSocket\WsServerInterface;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Doctrine\ORM\EntityManager;
use Symfony\Component\DependencyInjection\ContainerInterface as Container;
use Symfony\Component\HttpFoundation\Session\Session;

/**
 * This component will allow access to user data (FOSUserBundle)
 * for each connection in your Ratchet application.
 */
class Chat implements MessageComponentInterface, WsServerInterface
{
    /**
     * @var \Ratchet\MessageComponentInterface
     */
    protected $_app;
    /**
     * @var \Symfony\Component\DependencyInjection\ContainerInterface
     */
    protected $_container;
    /**
     * @param MessageComponentInterface $app
     * @param ContainerInterface $container
     */
    public function __construct(MessageComponentInterface $app, ContainerInterface $container)
    {
        $this->_app = $app;
        $this->_container = $container;
    }
    /**
     * {@inheritdoc}
     */
    public function onOpen(ConnectionInterface $conn)
    {
        if (!isset ($conn->Session) || !$conn->Session instanceof Session) {
            throw new \RuntimeException('Session is not defined. Make sure that SessionProvider is executed before FOSUserProvider.');
        }
        try {
            $token      = unserialize($conn->Session->get('_security_main'));
            $user       = $token->getUser();
            $provider   = $this->_container->get('fos_user.user_provider.username');
            $conn->User = $provider->refreshUser($user);
        } catch (Exception $ex) {
            $conn->User = null;
        }
        return $this->_app->onOpen($conn);
    }
</code>```

答:
There isn't any use MyApp; on the top of your page.
use AppBundle\Classes ? </p>

Body:
I using symfony 2 and ratchet and memcache on a websocket chat project ratchet working good with symfony and i tested it on the "hello world" app on the offical web site docs
but the problem is when I run this line

    new Chat(new MyApp(), $this->getContainer()),

i get this error

Attempted to load class "MyApp" from namespace

my command line code

<?php
// myapplication/src/sandboxBundle/Command/SocketCommand.php
// Change the namespace according to your bundle
namespace check\roomsBundle\Command;
use Ratchet\Session\SessionProvider;
use Symfony\Component\HttpFoundation\Session\Storage\Handler;
use Doctrine\Common\Cache\MemcacheCache;
use Ratchet\App;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\HttpFoundation\Session\Storage\Handler\MemcacheSessionHandler;
use Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage;
// Include ratchet libs
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
// Change the namespace according to your bundle
use check\roomsBundle\Sockets\Chat;
use Doctrine\ORM\EntityManager;
use Symfony\Component\HttpFoundation\Session\Session;

class WsServerCommand extends ContainerAwareCommand
{
    protected function configure()
    {
        $this->setName('sockets:start-chat')
            // the short description shown while running "php bin/console list"
            ->setHelp("Starts the chat socket demo")
            // the full command description shown when running the command with
            ->setDescription('Starts the chat socket demo')
        ;    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $output->writeln([
            'Chat socket',// A line
            '============',// Another line
            'Starting chat, open your browser.',// Empty line
        ]);
        $memcache = new \Memcache;
        $memcache->connect('localhost', 11211);

        $session = new SessionProvider(
            new Chat(new MyApp(), $this->getContainer()),
            new Handler\MemcacheSessionHandler($memcache)
        );

        $server = new App('localhost');
        $server->route('/sessDemo', $session);
        $server->run();
    }
}

the Chat.php code

<?php
namespace check\roomsBundle\Sockets;
use tuto\testBundle\Entity\Users;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Ratchet\WebSocket\WsServerInterface;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Doctrine\ORM\EntityManager;
use Symfony\Component\DependencyInjection\ContainerInterface as Container;
use Symfony\Component\HttpFoundation\Session\Session;

/**
 * This component will allow access to user data (FOSUserBundle)
 * for each connection in your Ratchet application.
 */
class Chat implements MessageComponentInterface, WsServerInterface
{
    /**
     * @var \Ratchet\MessageComponentInterface
     */
    protected $_app;
    /**
     * @var \Symfony\Component\DependencyInjection\ContainerInterface
     */
    protected $_container;
    /**
     * @param MessageComponentInterface $app
     * @param ContainerInterface $container
     */
    public function __construct(MessageComponentInterface $app, ContainerInterface $container)
    {
        $this->_app = $app;
        $this->_container = $container;
    }
    /**
     * {@inheritdoc}
     */
    public function onOpen(ConnectionInterface $conn)
    {
        if (!isset ($conn->Session) || !$conn->Session instanceof Session) {
            throw new \RuntimeException('Session is not defined. Make sure that SessionProvider is executed before FOSUserProvider.');
        }
        try {
            $token      = unserialize($conn->Session->get('_security_main'));
            $user       = $token->getUser();
            $provider   = $this->_container->get('fos_user.user_provider.username');
            $conn->User = $provider->refreshUser($user);
        } catch (Exception $ex) {
            $conn->User = null;
        }
        return $this->_app->onOpen($conn);
    }


来源: stackexchange

问:
html check if input is greater than other input after submit
I have two input fields and want to check if one field is greater than the other.
I want to check this before the submit-Button is clicked.

<input type="text" name = "minValue" pattern="(|-)?[0-9]{0,3}?" id="min_value" value="" required/>

<input type="text" name = "maxValue" pattern="(|-)?[0-9]{0,3}?" id="max_value" value="" required/>

<button type = "submit" name = "submitcheck" id = "submit_check"> Let´s Go </button>```

Do I need jquery? I want to do this check before checking the submt button.

答:
HTML is only a markup language. If you want your web to have some functionality you have to use JavaScript Jquery or Php.

You can try something like this:

Ust <form> tag attribute onsubmit:

```<code><form name="myForm" onsubmit="return validateForm()" method="post">
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have two input fields and want to check if one field is greater than the other.
I want to check this before the submit-Button is clicked.

<input type="text" name = "minValue" pattern="(|-)?[0-9]{0,3}?" id="min_value" value="" required/>

<input type="text" name = "maxValue" pattern="(|-)?[0-9]{0,3}?" id="max_value" value="" required/>

<button type = "submit" name = "submitcheck" id = "submit_check"> Let´s Go </button>

Do I need jquery? I want to do this check before checking the submt button.

Body:
HTML is only a markup language. If you want your web to have some functionality you have to use JavaScript Jquery or Php.

You can try something like this:

Ust <form> tag attribute onsubmit:

<form name="myForm" onsubmit="return validateForm()" method="post">


问:
Weird animation when hiding the navigation bar
I'm implementing a photo gallery via a UIPageViewController subclass (called GalleryController) embedded in a UINavigationController. The navigation bar hides when I tap, but the animation is odd:

https://www.youtube.com/watch?v=9SLF3Nq3uNE

Here's the code in GalleryController:

```<code>  override var navigationItem: UINavigationItem {
    let item = super.navigationItem
    // Access super and add items to it.
    // Don't create a new UINavigationItem instance — that breaks the back button.

    let space = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
    space.width = touchSize / 2

    item.rightBarButtonItems = [
      UIBarButtonItem(title: "All Photos", style: .plain, target: self, action: #selector(showAllPhotos)),
      space,
      UIBarButtonItem(title: "Delete", style: .plain, target: self, action: #selector(deletePhoto))
    ]
    return item
  }
</code>```

This problem started occuring only after the page view controller was introduced.

What's causing this, and how do I fix it?

答:
The solution turned out to be to do the following in the init of the UIPageViewController subclass:

```<code>automaticallyAdjustsScrollViewInsets = false
</code>```

I don't know why it works, but it does.

I was earlier doing this in the child view controller (that represents a single page of the page view controller), but that wasn't working.

Body:
I'm implementing a photo gallery via a UIPageViewController subclass (called GalleryController) embedded in a UINavigationController. The navigation bar hides when I tap, but the animation is odd:

https://www.youtube.com/watch?v=9SLF3Nq3uNE

Here's the code in GalleryController:

  override var navigationItem: UINavigationItem {
    let item = super.navigationItem
    // Access super and add items to it.
    // Don't create a new UINavigationItem instance — that breaks the back button.

    let space = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
    space.width = touchSize / 2

    item.rightBarButtonItems = [
      UIBarButtonItem(title: "All Photos", style: .plain, target: self, action: #selector(showAllPhotos)),
      space,
      UIBarButtonItem(title: "Delete", style: .plain, target: self, action: #selector(deletePhoto))
    ]
    return item
  }

This problem started occuring only after the page view controller was introduced.

What's causing this, and how do I fix it?

Body:
The solution turned out to be to do the following in the init of the UIPageViewController subclass:

automaticallyAdjustsScrollViewInsets = false

I don't know why it works, but it does.

I was earlier doing this in the child view controller (that represents a single page of the page view controller), but that wasn't working.


问:
PySide - Qt: Could not initialize OLE (error 80010106)
I'm using PySide with Python 2.7.3 x64, and when running my Qt application, I'm noticing the following error show up in the output of Wing IDE.

Qt: Could not initialize OLE (error 80010106)

This doesn't appear to be causing issues until I close the Qt application when I run it outside of Wing.  The closed app will throw up a pythonw.exe windows error.  I'm assuming the two are related, as it happens on even the most basic of Qt app.  But I'm not exactly sure what the deal is.  Any ideas would be really appreciated!

答:
This issue is resolved by call to CoInitialize before import clr:

https://github.com/pythonnet/pythonnet/issues/439


问:
Validate multiple email addresses in single field
Is there a way to validate one or multiple email addresses in a single input field?

The way that I'm currently exploring is by creating a custom directive that will split the input into different emails if a comma is detected. This is what I have so far:

```<code>angular.module('myApp')
  .directive('multipleEmails', function () {
    return {
      require: 'ngModel',
      link: function(scope, element, attrs, ctrl) {
        ctrl.$parsers.unshift(function(viewValue) {

          var emails = viewValue.split(',');
          // loop that checks every email, returns undefined if one of them fails.
        });
      }
    };
  });
</code>```

The issue that I have with this is that I have been unable to call the angular email validator manually.

Edit: plunkr

Edit 2: Turns out that I can use angular 1.3

答:
I know it's a late answer, but uses the Angular 1.x logic as much as possible and only adds the multiple support. Other answers all use their own validation regex.</p>

```<code><input type="email" data-ng-multiple-email data-ng-model="$ctrl.x">

angular.module("myApp")
    .directive("ngMultipleEmail", function () {
        return {
            restrict: "A",
            require: "?ngModel",
            link: function (scope, elm, attrs, ctrl) {
                if (ctrl && ctrl.$validators.email) {
                    let originalValidator = ctrl.$validators.email;
                    ctrl.$validators.email = function (modelValue,   viewValue) {
                        var value = modelValue || viewValue || "",
                            valueSplit = value.split(/[,;]+/);
                        valueSplit.forEach(function (email) {
                            var valid = originalValidator(email.trim());
                            if (!valid) {
                                return false;
                            }
                        });
                        return true;
                    };
                }
            }
        };
    });
</code>```

Body:
Is there a way to validate one or multiple email addresses in a single input field?

The way that I'm currently exploring is by creating a custom directive that will split the input into different emails if a comma is detected. This is what I have so far:

angular.module('myApp')
  .directive('multipleEmails', function () {
    return {
      require: 'ngModel',
      link: function(scope, element, attrs, ctrl) {
        ctrl.$parsers.unshift(function(viewValue) {

          var emails = viewValue.split(',');
          // loop that checks every email, returns undefined if one of them fails.
        });
      }
    };
  });

The issue that I have with this is that I have been unable to call the angular email validator manually.

Edit: plunkr

Edit 2: Turns out that I can use angular 1.3

Body:
I know it's a late answer, but uses the Angular 1.x logic as much as possible and only adds the multiple support. Other answers all use their own validation regex.

<input type="email" data-ng-multiple-email data-ng-model="$ctrl.x">

angular.module("myApp")
    .directive("ngMultipleEmail", function () {
        return {
            restrict: "A",
            require: "?ngModel",
            link: function (scope, elm, attrs, ctrl) {
                if (ctrl && ctrl.$validators.email) {
                    let originalValidator = ctrl.$validators.email;
                    ctrl.$validators.email = function (modelValue,   viewValue) {
                        var value = modelValue || viewValue || "",
                            valueSplit = value.split(/[,;]+/);
                        valueSplit.forEach(function (email) {
                            var valid = originalValidator(email.trim());
                            if (!valid) {
                                return false;
                            }
                        });
                        return true;
                    };
                }
            }
        };
    });


问:
How to use boto3 to find an EC2 jump host for ssh port forwarding to RDS?
I want to write a script using Python and boto3 to let me psql to a specified RDS instance using EC2 as a proxy, e.g. either use ssh -L port forwarding or tunneling.

I have a bunch of RDS and EC2 instances.  One RDS instance may used by many EC2 instances.  This is implemented using security groups and an inbound rule that hooks up the two security groups (for EC2 and RDS) for traffic on the database port (5432).

I can use boto3 to fetch information of EC2 and RDS instances, including security groups.  But I don't know which EC2 instance I need to ssh to act as proxy for a given RDS instance.

How do I configure EC2 server to act as proxy/jump-server for my external connection through ssh ?  Which EC2 instance should I choose ?

答:
There is still many information missing here.  Please add in the details so others can mod up your question.

First, ssh-tunneling/port-forwarding answer can be found  here.  Just change the port from mysql 3306 to your RDS psql port.

Second, if you want to use the connection from your local PC to EC2 ssh proxy, this is only possible :

The EC2 server have a public connected IP address, OR

You have a VPN connection to EC2 server that sit on VPC private subnet

ContentLicense: CC BY-SA 4.0


问:
which python package can be used for text to speech?
The purpose for using text to speech is to make the bot speak what is there in the specific division of the html body.
can I use jquery to do the above tts? if yes, what is the package i should be using?</p>

答:
If you use Javascript, I recommend you to use https://responsivevoice.org/.

It's easy to install and configure :

<input onclick='responsiveVoice.speak("Hello World");' type='button' value=' Play' />```

Body:
If you use Javascript, I recommend you to use https://responsivevoice.org/.

It's easy to install and configure :

<script src='https://code.responsivevoice.org/responsivevoice.js'></script>
<input onclick='responsiveVoice.speak("Hello World");' type='button' value=' Play' />


问:
Not receiving json object after returning boolean value in Spring
I don't know whether I do it right or not but it works so far.

The GetMapping should produce a json, but how exactly is it supposed to produce one if I'm giving it only one boolean and no Map type ? what is it exactly returning then ?

```<code>@GetMapping(value = "/getIsTrackedHistory/{name}" , produces = "application/json")
public @ResponseBody boolean getIsTrackedHistory(@PathVariable("name") String name) {
    boolean isTracked = template.getIsTrackedHistory(name);
    return isTracked;
}
</code>```

My request :

```<code>$http.get(localhostUrl + 'getIsTrackedHistory/' + $scope.name
.success(function (data) {
      console.log(JSON.stringify(data)); //prints just true or false, which doesn't look at all like a json object.
</code>```

答:
what you do here is absolutely right.  when you return a boolean it would be returned as a single object(as a boolean) in json format.
if you return an object that holds more  properties in it, that would be like as a json format.</p>

Body:
I don't know whether I do it right or not but it works so far.

The GetMapping should produce a json, but how exactly is it supposed to produce one if I'm giving it only one boolean and no Map type ? what is it exactly returning then ?

@GetMapping(value = "/getIsTrackedHistory/{name}" , produces = "application/json")
public @ResponseBody boolean getIsTrackedHistory(@PathVariable("name") String name) {
    boolean isTracked = template.getIsTrackedHistory(name);
    return isTracked;
}

My request :

$http.get(localhostUrl + 'getIsTrackedHistory/' + $scope.name
.success(function (data) {
      console.log(JSON.stringify(data)); //prints just true or false, which doesn't look at all like a json object.


问:
How to Store Previous Value Of Loop in variable
JSONObject jsonRoot = new JSONObject(response);

```<code>    ArrayList<Level2_Women> alUser = new ArrayList<>();
    JSONArray parentArray = jsonRoot.getJSONArray("categories");

    StringBuffer finalBufferData = new StringBuffer();

    for (int j = 0; j <parentArray.length(); j++) {

            JSONObject finalObject = parentArray.getJSONObject(j);

            user.setCategory(finalObject.getString("category"));
            String catid = finalObject.getString("category_id");

    }
    return user;
}
</code>```

I am Using this loop.In my Loop there are 12 elements,But its print only last value.How i can print all element in Listview?

答:
Your Loop should Go like this:

```<code>   for (int j = 0; j <parentArray.length(); j++) {

        JSONObject finalObject = parentArray.getJSONObject(j);

        user.setCategory(finalObject.getString("category"));
        String catid = finalObject.getString("category_id");
</code>```

return user;

}
    return user will return value everytime you iterate for loop.
Since i assume you are new to java this excelent tutorial will help you learn a lot

Body:
JSONObject jsonRoot = new JSONObject(response);

    ArrayList<Level2_Women> alUser = new ArrayList<>();
    JSONArray parentArray = jsonRoot.getJSONArray("categories");

    StringBuffer finalBufferData = new StringBuffer();

    for (int j = 0; j <parentArray.length(); j++) {

            JSONObject finalObject = parentArray.getJSONObject(j);

            user.setCategory(finalObject.getString("category"));
            String catid = finalObject.getString("category_id");

    }
    return user;
}

I am Using this loop.In my Loop there are 12 elements,But its print only last value.How i can print all element in Listview?

Body:
Your Loop should Go like this:

   for (int j = 0; j <parentArray.length(); j++) {

        JSONObject finalObject = parentArray.getJSONObject(j);

        user.setCategory(finalObject.getString("category"));
        String catid = finalObject.getString("category_id");

return user;

}
    return user will return value everytime you iterate for loop.
Since i assume you are new to java this excelent tutorial will help you learn a lot


问:
Create a dataframe from a hashmap with keys as column names and values as rows in Spark
I have a dataframe and I have a column which is a map in dataframe like this -

```<code>scala> df.printSchema
</code>```

root
 |-- A1: map (nullable = true)
 |    |-- key: string
 |    |-- value: string (valueContainsNull = true)
```

<p>I need to select all the keys from dataframe as column name and values as rows.</p>

<p>For eg:
Let say I have 2 records like this-</p>

<pre class="lang-none prettyprint-override"><code>1. key1 -> value1, key2 -> value2, key3 -> value3 ....
2. key1 -> value11, key3 -> value13, key4 -> value14 ...
</code>```

I want the output dataframe as

key1             key2                 key3             key4
value1           value2               value3            null
value11          null                 value13           value14
```

How can I do this?

答:
First we need to create an id column by which we can group your data, then explode the map column A1, and finally reshape your df using pivot():

```<code>import org.apache.spark.sql.functions.{monotonically_increasing_id, explode, first}

df.withColumn("id", (monotonically_increasing_id()))
  .select($"id", explode($"A1"))
  .groupBy("id")
  .pivot("key")
  .agg(first("value")).show()
+---+-------+------+-------+-------+
| id|   key1|  key2|   key3|   key4|
+---+-------+------+-------+-------+
|  0| value1|value2| value3|   null|
|  1|value11|  null|value13|value14|
+---+-------+------+-------+-------+
</code>```

Body:
I have a dataframe and I have a column which is a map in dataframe like this -

scala> df.printSchema

root
 |-- A1: map (nullable = true)
 |    |-- key: string
 |    |-- value: string (valueContainsNull = true)

I need to select all the keys from dataframe as column name and values as rows.

For eg:
Let say I have 2 records like this-

1. key1 -> value1, key2 -> value2, key3 -> value3 ....
2. key1 -> value11, key3 -> value13, key4 -> value14 ...

I want the output dataframe as

key1             key2                 key3             key4
value1           value2               value3            null
value11          null                 value13           value14

How can I do this?

Body:
First we need to create an id column by which we can group your data, then explode the map column A1, and finally reshape your df using pivot():

import org.apache.spark.sql.functions.{monotonically_increasing_id, explode, first}

df.withColumn("id", (monotonically_increasing_id()))
  .select($"id", explode($"A1"))
  .groupBy("id")
  .pivot("key")
  .agg(first("value")).show()
+---+-------+------+-------+-------+
| id|   key1|  key2|   key3|   key4|
+---+-------+------+-------+-------+
|  0| value1|value2| value3|   null|
|  1|value11|  null|value13|value14|
+---+-------+------+-------+-------+


问:
Using WPF Binding StringFormat with literals both for input and output
I have a font point size chooser in WPF desktop app UI. I have previously used converter in such cases and it may well be the way to go here too.

However, there is StringFormat that I can use on binding which looks like simpler way (avoids creating a converter). It works fine for numeric value but it seems that I cannot add literals to the format like this: StringFormat='{}{0:N} pt'

In XAML:

```<code><ComboBox Text="{Binding SampleFontSize, StringFormat='{}{0:N} pt', ValidatesOnDataErrors=True" IsEditable="True">
<ComboBoxItem>8</ComboBoxItem>
<ComboBoxItem>10</ComboBoxItem>
<ComboBoxItem>12</ComboBoxItem>
<ComboBoxItem>14</ComboBoxItem>
</code>```

Note the IsEditable=true

This will display "12,00 pt" in my locale but when I type in exactly the same value, it will trigger validation error:

```<code>System.Windows.Data Error: 7 : ConvertBack cannot convert value '12 pt' (type 'String'). BindingExpression:Path=SampleFontSize; DataItem='AnalysisSettingsViewModel' (HashCode=47173034); target element is 'ComboBox' (Name=''); target property is 'Text' (type 'String') FormatException:'System.FormatException: Input string was not in a correct format.
at System.Number.ParseDouble(String value, NumberStyles options, NumberFormatInfo numfmt)
at System.String.System.IConvertible.ToDouble(IFormatProvider provider)
at System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider)
at MS.Internal.Data.SystemConvertConverter.ConvertBack(Object o, Type type, Object parameter, CultureInfo culture)
at System.Windows.Data.BindingExpression.ConvertBackHelper(IValueConverter converter, Object value, Type sourceType, Object parameter, CultureInfo culture)'
</code>```

Shoudl I conclude that the StringFormat with literals works one way only, or am I using incorrect StringFormat? The StringFormat={}{0:N} works OK but not the StringFormat={}{0:N} pt

答:
Since "12 pt" is not a valid double value, the default converter won't be able to convert it back to a double. So yes, this indeed works one-way only.

You should use a custom converter that also knows how to convert the string to a double.

Body:
I have a font point size chooser in WPF desktop app UI. I have previously used converter in such cases and it may well be the way to go here too.

However, there is StringFormat that I can use on binding which looks like simpler way (avoids creating a converter). It works fine for numeric value but it seems that I cannot add literals to the format like this: StringFormat='{}{0:N} pt'

In XAML:

<ComboBox Text="{Binding SampleFontSize, StringFormat='{}{0:N} pt', ValidatesOnDataErrors=True" IsEditable="True">
<ComboBoxItem>8</ComboBoxItem>
<ComboBoxItem>10</ComboBoxItem>
<ComboBoxItem>12</ComboBoxItem>
<ComboBoxItem>14</ComboBoxItem>

Note the IsEditable=true

This will display "12,00 pt" in my locale but when I type in exactly the same value, it will trigger validation error:

System.Windows.Data Error: 7 : ConvertBack cannot convert value '12 pt' (type 'String'). BindingExpression:Path=SampleFontSize; DataItem='AnalysisSettingsViewModel' (HashCode=47173034); target element is 'ComboBox' (Name=''); target property is 'Text' (type 'String') FormatException:'System.FormatException: Input string was not in a correct format.
at System.Number.ParseDouble(String value, NumberStyles options, NumberFormatInfo numfmt)
at System.String.System.IConvertible.ToDouble(IFormatProvider provider)
at System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider)
at MS.Internal.Data.SystemConvertConverter.ConvertBack(Object o, Type type, Object parameter, CultureInfo culture)
at System.Windows.Data.BindingExpression.ConvertBackHelper(IValueConverter converter, Object value, Type sourceType, Object parameter, CultureInfo culture)'

Shoudl I conclude that the StringFormat with literals works one way only, or am I using incorrect StringFormat? The StringFormat={}{0:N} works OK but not the StringFormat={}{0:N} pt


问:
How can I close my close my browser or switch to pop up when automating Google sign in?
I am trying to refresh my Selenium knowledge.  So, I am writing a script to navigate through my Google account.  After I successfully sign in to Google, a pop up appears under my profile icon on the upper right side in Firefox.  I no longer get these pop ups when I sign manually.  This is probably because of cookies or some other browser setting.  I do not care about the reason why this occurs.

However, since it occurs, I believe it may be preventing my script from closing the browser with driver.close();  I also tried driver.quit();  Neither of these are causing the browser to close.

So, I thought I would try switching windows by doing an iteration through the windows.  This is not allowing me to select the pop up that appears to close it.

I also tried to create an Alert alert and switch to it:

driver.switchto.alert();

driver.dismiss();

This is not dismissing this pop up in Google either.

In the end, I do not care about this pop up.  I know I listed 2 separate issues here. But, in the end, I just want to close the browser.  If I can also learn how to switch to this pop up and click the x to close it, that is a bonus.

//Code added here -------------------------

```<code>public void sign_out( WebDriver driver )
{
    //At this point,I am already signed in.  But, that Google pop up appears
    //The pop up says "Get to Google faster. Switch your default search engine to Google."

    //Wait for "x" to appear
    myDynamicElement = (new WebDriverWait(driver, wait_for_element_time)).until(ExpectedConditions.visibilityOfElementLocated(By.xpath(x_path_x_pop_up)));

    //This is set above as a class member
    //final String x_path_x_pop_up = "/html/body/div/div[3]/div[1]/div/div/div/div[2]/div[4]/div/a";
    WebElement x_icon = driver.findElement(By.xpath(x_path_x_pop_up));

    //Click x to close it
    x_icon.click();

    String myWindowHandle = driver.getWindowHandle();
    String subWindowHandle = null;

    Set<String> handles = driver.getWindowHandles(); // get all window handles
    Iterator<String> iterator = handles.iterator();
    while (iterator.hasNext()){
        subWindowHandle = iterator.next();
    }
    driver.switchTo().window(subWindowHandle); // switch to popup window
</code>```

//      driver.switchTo().window(myWindowHandle);

// This never happens now on this click of the profile icon in Google to sign out.
        //Click on profile icon
        m_profile_icon.click();

```<code>    //Wait for "Sign Out" button to appear
    myDynamicElement = (new WebDriverWait(driver, wait_for_element_time)).until(ExpectedConditions.visibilityOfElementLocated(By.xpath(x_path_sign_out_button)));

    //Get sign out button
    WebElement sign_out_button = driver.findElement(By.xpath(x_path_sign_out_button) );

    sign_out_button.click();
}
</code>```

}

答:
Well as long as you are working in Java you can try the Robot framework and sendKeys as a workaround (ALT+F4):

```<code>import java.lang.reflect.*;
import java.awt.Robot;
import java.awt.event.KeyEvent;

public class RobotUtilities {

    public static void sendKeyCombo(String keys[]) {
        try {

            Robot robot = new Robot();

            Class<?> cl = KeyEvent.class;

            int [] intKeys = new int [keys.length];

            for (int i = 0; i < keys.length; i++) {
                Field field = cl.getDeclaredField(keys[i]);
                intKeys[i] = field.getInt(field);
                robot.keyPress(intKeys[i]);
            }

            for (int i = keys.length - 1; i >= 0; i--)
                robot.keyRelease(intKeys[i]);
        }
        catch (Throwable e) {
            System.err.println(e);
        }
    }

    // main for testing purposes
    public static void main(String args[]) {
        String [] keys = {"VK_ALT", "VK_F4"};
        sendKeyCombo(keys);
    }

}
</code>```

Alternative more robust solution using windowHandles:

I took this from here

You can switch between windows as below:

```<code>// Store the current window handle
String winHandleBefore = driver.getWindowHandle();

// Perform the click operation that opens new window

// Switch to new window opened
for(String winHandle : driver.getWindowHandles()){
    driver.switchTo().window(winHandle);
}

// Perform the actions on new window

// Close the new window, if that window no more required
driver.close();

// Switch back to original browser (first window)
driver.switchTo().window(winHandleBefore);

// Continue with original browser (first window)
</code>```

Body:
I am trying to refresh my Selenium knowledge.  So, I am writing a script to navigate through my Google account.  After I successfully sign in to Google, a pop up appears under my profile icon on the upper right side in Firefox.  I no longer get these pop ups when I sign manually.  This is probably because of cookies or some other browser setting.  I do not care about the reason why this occurs.

However, since it occurs, I believe it may be preventing my script from closing the browser with driver.close();  I also tried driver.quit();  Neither of these are causing the browser to close.

So, I thought I would try switching windows by doing an iteration through the windows.  This is not allowing me to select the pop up that appears to close it.

I also tried to create an Alert alert and switch to it:

driver.switchto.alert();

driver.dismiss();

This is not dismissing this pop up in Google either.

In the end, I do not care about this pop up.  I know I listed 2 separate issues here. But, in the end, I just want to close the browser.  If I can also learn how to switch to this pop up and click the x to close it, that is a bonus.

//Code added here -------------------------

public void sign_out( WebDriver driver )
{
    //At this point,I am already signed in.  But, that Google pop up appears
    //The pop up says "Get to Google faster. Switch your default search engine to Google."

    //Wait for "x" to appear
    myDynamicElement = (new WebDriverWait(driver, wait_for_element_time)).until(ExpectedConditions.visibilityOfElementLocated(By.xpath(x_path_x_pop_up)));

    //This is set above as a class member
    //final String x_path_x_pop_up = "/html/body/div/div[3]/div[1]/div/div/div/div[2]/div[4]/div/a";
    WebElement x_icon = driver.findElement(By.xpath(x_path_x_pop_up));

    //Click x to close it
    x_icon.click();

    String myWindowHandle = driver.getWindowHandle();
    String subWindowHandle = null;

    Set<String> handles = driver.getWindowHandles(); // get all window handles
    Iterator<String> iterator = handles.iterator();
    while (iterator.hasNext()){
        subWindowHandle = iterator.next();
    }
    driver.switchTo().window(subWindowHandle); // switch to popup window

//      driver.switchTo().window(myWindowHandle);

// This never happens now on this click of the profile icon in Google to sign out.
        //Click on profile icon
        m_profile_icon.click();

    //Wait for "Sign Out" button to appear
    myDynamicElement = (new WebDriverWait(driver, wait_for_element_time)).until(ExpectedConditions.visibilityOfElementLocated(By.xpath(x_path_sign_out_button)));

    //Get sign out button
    WebElement sign_out_button = driver.findElement(By.xpath(x_path_sign_out_button) );

    sign_out_button.click();
}

}

Body:
Well as long as you are working in Java you can try the Robot framework and sendKeys as a workaround (ALT+F4):

import java.lang.reflect.*;
import java.awt.Robot;
import java.awt.event.KeyEvent;

public class RobotUtilities {

    public static void sendKeyCombo(String keys[]) {
        try {

            Robot robot = new Robot();

            Class<?> cl = KeyEvent.class;

            int [] intKeys = new int [keys.length];

            for (int i = 0; i < keys.length; i++) {
                Field field = cl.getDeclaredField(keys[i]);
                intKeys[i] = field.getInt(field);
                robot.keyPress(intKeys[i]);
            }

            for (int i = keys.length - 1; i >= 0; i--)
                robot.keyRelease(intKeys[i]);
        }
        catch (Throwable e) {
            System.err.println(e);
        }
    }

    // main for testing purposes
    public static void main(String args[]) {
        String [] keys = {"VK_ALT", "VK_F4"};
        sendKeyCombo(keys);
    }

}

Alternative more robust solution using windowHandles:

I took this from here

You can switch between windows as below:

// Store the current window handle
String winHandleBefore = driver.getWindowHandle();

// Perform the click operation that opens new window

// Switch to new window opened
for(String winHandle : driver.getWindowHandles()){
    driver.switchTo().window(winHandle);
}

// Perform the actions on new window

// Close the new window, if that window no more required
driver.close();

// Switch back to original browser (first window)
driver.switchTo().window(winHandleBefore);

// Continue with original browser (first window)


问:
What is the use case of the declaration of array like below in C-Language (It is valid one dont say it is error)
In my company, when I am looking in the code part,
I was wondering when I see an array variable declaration similar to like this

int arr[0]; (Using c language)

Could anyone help me to state that what this declaration meant for?
How this declaration can make use of realtime of codepart?

答:
It is an error insofar that it is neither standard C nor standard C++.

This is the old (i.e. pre-C99) way of inserting a variable length array as a struct member, which was never standard C although some compilers (e.g. GCC) support it as an extension. It has to be the last member of the struct.

Post C99, the now standard way to do this is to use empty brackets.

For C++ you're out of luck - variable length arrays are not standard C++. But you can use std::vector instead.


问:
How do I serve an angular 2 app from django's development server?
I have a project where I am using Angular2 to consume a rest API that I built with Django-Rest-Framework.  Currently I have to start up the django api using django development server e.g., 'python manage.py runserver' and then I have to start up the angular 2 server using either 'npm start' or through the cli, 'ng serve'.  Is there any way I can setup my django project to serve the angular2 project?  </p>

答:
Put the index.html file in the templates/<project-name> directory.

use this function to serve index.html which is the entry point to angular

```<code>def index(request):
    return render(request, template_name='<project-name>/index.html')
</code>```

Put all your angular static files in the STATICFILES_DIRS so that they can be collected by collectstatic command.

Use {{ STATIC_URL }} in the path of your static files in index.html to access them

Now when you will access the index function your angular app will get served.

Body:
Put the index.html file in the templates/<project-name> directory.

use this function to serve index.html which is the entry point to angular

def index(request):
    return render(request, template_name='<project-name>/index.html')

Put all your angular static files in the STATICFILES_DIRS so that they can be collected by collectstatic command.

Use {{ STATIC_URL }} in the path of your static files in index.html to access them

Now when you will access the index function your angular app will get served.


问:
Javascript clock - server time
I need to show the server time on a clock. Below is the code i currently have. I get the server time with Ajax call. The problem is that if the user changes it's local/computer clock it will also update the script's clock which is not ok - it should continue without changing and i'm stuck. I've tried passing the serverTime within the setTimeout so it get's used every time as a reference but no luck with that.

var serverTime  = 1490856278000;
var localTime   = +Date.now();
var timeDiff    = serverTime - localTime;
var realTime;
var date;
var hours;
var minutes;
var seconds;
setInterval(function () {
  realTime = +Date.now() + timeDiff;
  date     = new Date(realTime);
  hours    = date.getHours();
  minutes  = date.getMinutes();
  seconds  = date.getSeconds();
  document.getElementById('clock').innerHTML = hours + ':' + minutes + ':' + seconds;
}, 1000);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="clock"></div></code>```

答: The time will change because Date.now(); is getting it's time from the Client machine. There are no AJAX calls in your script.

Title: Javascript clock - server time


答:
Update

You have to update all the native packages to latest like below.

```<code>  "@ionic-native/core": "3.4.3",
  "@ionic-native/splash-screen": "3.4.3",
  "@ionic-native/status-bar": "3.4.3",
</code>```

After that: npm i

Old Answer

You just need to do this on your package.json file.

Replace old one ("ionic-native": "2.2.11") with this "@ionic-native/core": "3.1.0",

after that run npm i

Note: You must use  "@angular/core": "2.4.8" with your Ionic2 app.No Angular4 support yet.

Your package.json file should be like this.

```<code>"dependencies": {
    "@angular/common": "2.4.8",
    "@angular/compiler": "2.4.8",
    "@angular/compiler-cli": "2.4.8",
    "@angular/core": "2.4.8",
    "@angular/forms": "2.4.8",
    "@angular/http": "2.4.8",
    "@angular/platform-browser": "2.4.8",
    "@angular/platform-browser-dynamic": "2.4.8",
    "@angular/platform-server": "2.4.8",
    "@ionic-native/core": "3.1.0",
    "@ionic-native/splash-screen": "3.1.0",
    "@ionic-native/status-bar": "3.1.0",
    "@ionic/storage": "2.0.0",
    "ionic-angular": "2.3.0",
    "ionicons": "3.0.0",
    "rxjs": "5.0.1",
    "sw-toolbox": "3.4.0",
    "zone.js": "0.7.2"
</code>```

},

Title: How to update ionic-native to vers 3x?

Body:
I'm trying to update ionic-native to a version 3.4.3

But it doesn't work. It has updated to version 2.9.0, which is the last 2.x version.

How can I update more?

If i change the version in package.json to 3.4.3, it says:

npm ERR! notarget No compatible version found: ionic-native@3.4.3
npm ERR! notarget Valid install targets:
npm ERR! notarget 2.9.0, 2.8.1, 2.8.0, 2.7.0, 2.6.0, 2.5.1, 2.5.0, 2.4.1, 2.4.0, 2.3.2, 2.3.1, 2.3.0, 2.2.17, 2.2.16, 2.2.15, 2.2.14, 2.2.13, 2.2.12, 2.2.11, 2.2.10, 2.2.9, 2.2.8, 2.2.7, 2.2.6, 2.2.5, 2.2.4, 2.2.3, 2.2.2, 2.2.1, 2.2.0, 2.1.9, 2.1.8, 2.1.7, 2.1.6, 2.1.5, 2.1.4, 2.1.3, 2.1.2, 2.0.3, 2.0.2, 2.0.1, 2.0.0, 1.3.27, 1.3.26, 1.3.25, 1.3.24, 1.3.23, 1.3.22, 1.3.21, 1.3.20, 1.3.19, 1.3.18, 1.3.17, 1.3.16, 1.3.15, 1.3.14, 1.3.13, 1.3.12, 1.3.11, 1.3.10, 1.3.9, 1.3.8, 1.3.7, 1.3.6, 1.3.5, 1.3.4, 1.3.3, 1.3.2, 1.3.1, 1.3.0, 1.2.4, 1.2.3, 1.2.2, 1.2.1, 1.2.0, 1.1.1, 1.1.0, 1.0.12, 1.0.11, 1.0.10, 1.0.9, 1.0.8, 1.0.7

Do you know why?

My ionic version:

Cordova CLI: 6.5.0
Ionic Framework Version: 2.3.0
Ionic CLI Version: 2.2.1
Ionic App Lib Version: 2.2.0
Ionic App Scripts Version: 1.2.3
ios-deploy version: 1.9.1
ios-sim version: 5.0.13

Thanks

EDIT:

package.json:

  "dependencies": {
    "@angular/common": "^4.0.1",
    "@angular/compiler": "4.0.1",
    "@angular/compiler-cli": "4.0.1",
    "@angular/core": "^4.0.1",
    "@angular/forms": "4.0.1",
    "@angular/http": "4.0.1",
    "@angular/platform-browser": "4.0.1",
    "@angular/platform-browser-dynamic": "4.0.1",
    "@angular/platform-server": "4.0.1",
    "@ionic-native/core": "^3.4.3",
    "@ionic/storage": "^2.0.1",
    "chart.js": "^2.4.0",
    "ionic-angular": "2.3.0",
    "ionic-native": "3.4.3",
    "ionicons": "3.0.0",
    "midata": "git+https://github.com/i4mi/midata.js.git#v1.4",
    "ng2-charts": "^1.4.4",
    "pouchdb": "^6.1.0",
    "rxjs": "5.2.0",
    "zone.js": "0.8.5"
  },

EDIT2:

"dependencies": {
    "@angular/common": "2.4.8",
    "@angular/compiler": "2.4.8",
    "@angular/compiler-cli": "2.4.8",
    "@angular/core": "2.4.8",
    "@angular/forms": "2.4.8",
    "@angular/http": "2.4.8",
    "@angular/platform-browser": "2.4.8",
    "@angular/platform-browser-dynamic": "2.4.8",
    "@angular/platform-server": "2.4.8",
    "@ionic-native/core": "3.1.0",
    "@ionic-native/splash-screen": "3.1.0",
    "@ionic-native/status-bar": "3.1.0",
    "@ionic/storage": "2.0.0",
    "ionic-angular": "2.3.0",
    "ionicons": "3.0.0",
    "rxjs": "5.0.1",
    "sw-toolbox": "3.4.0",
    "zone.js": "0.7.2"
  },
  "devDependencies": {
    "@ionic/app-scripts": "^1.0.0",
    "typescript": "2.2.2"
  },
  "cordovaPlugins": [
    "cordova-plugin-whitelist",
    "cordova-plugin-console",
    "cordova-plugin-statusbar",
    "cordova-plugin-device",
    "cordova-plugin-splashscreen",
    "ionic-plugin-keyboard",
    "ionic-plugin-keyboard@~2.2.1",
    "cordova-plugin-whitelist@1.3.1",
    "cordova-plugin-console@1.0.5",
    "cordova-plugin-statusbar@2.2.1",
    "cordova-plugin-device@1.1.4",
    "cordova-plugin-splashscreen@~4.0.1",
    "cordova-plugin-screen-orientation",
    "cordova-plugin-camera",
    "cordova-plugin-inappbrowser",
    "cordova-plugin-network-information",
    "cordova-sqlite-storage",
    "cordova-sqlite-storage@~2.0.2",
    "cordova-plugin-file",
    "cordova-plugin-secure-storage"
  ],
  "cordovaPlatforms": [
    "ios",
    {
      "platform": "ios",
      "version": "",
      "locator": "ios"
    }
  ],
  "description": "OnkoApp2: An Ionic project"
}

Body:
Update

You have to update all the native packages to latest like below.

  "@ionic-native/core": "3.4.3",
  "@ionic-native/splash-screen": "3.4.3",
  "@ionic-native/status-bar": "3.4.3",

After that: npm i

Old Answer

You just need to do this on your package.json file.

Replace old one ("ionic-native": "2.2.11") with this "@ionic-native/core": "3.1.0",

after that run npm i

Note: You must use  "@angular/core": "2.4.8" with your Ionic2 app.No Angular4 support yet.

Your package.json file should be like this.

"dependencies": {
    "@angular/common": "2.4.8",
    "@angular/compiler": "2.4.8",
    "@angular/compiler-cli": "2.4.8",
    "@angular/core": "2.4.8",
    "@angular/forms": "2.4.8",
    "@angular/http": "2.4.8",
    "@angular/platform-browser": "2.4.8",
    "@angular/platform-browser-dynamic": "2.4.8",
    "@angular/platform-server": "2.4.8",
    "@ionic-native/core": "3.1.0",
    "@ionic-native/splash-screen": "3.1.0",
    "@ionic-native/status-bar": "3.1.0",
    "@ionic/storage": "2.0.0",
    "ionic-angular": "2.3.0",
    "ionicons": "3.0.0",
    "rxjs": "5.0.1",
    "sw-toolbox": "3.4.0",
    "zone.js": "0.7.2"

},


问:
Use multiple collectionfixture on my test class in xUnit 2.x
I am writing test cases for my DataAccessRepository ( using entity framework) class. This class takes two argument in constructor.
1) connection object
2) Automapper object

Now, I am using collectionFixture in xunit to pass DatabaseFixture in my test class but I need to pass AutoMapper Fixture as well to the same test class. I tried adding two collection, one after another but it is not valid.  Can someone please throw some light on how to use more than one FixtureCollection on a test class in xunit.

My Unit test class looks as follows and it is throwing error as I can not use two CollectionFixture attribute on the class,

`

```<code>[Collection(Traits.DatabaseFixtureCollection)]
    [Collection(Traits.AutomapperFixtureCollection)]
    public class MyAssessmentRepositoryTests
    {
        private readonly IMyAssessmentsRepository _Repo;
        public MyAssessmentRepositoryTests(DatabaseFixture dbFixture,AutomapperFixture amFixture)
        {
            this._Repo = new MyAssessmentRepository(dbFixture.IcmDbContext,amFixture.Mapper);

        }
 }`
</code>```

答:
See https://xunit.net/docs/shared-context

A single test class can only be in one Test Collection (which is why there is such a constraint on the Attribute).

The solution is to declare a single 'virtual' Test Collection, which declares the two fixtures that a test in such a collection should have controlled access to via ICollectionFixture<X>s.

When this is in place, the Test Class ctor is furnished with any of the Fixture instances as needed.

(You can also use an IClassFixture at the Test Class level to declare stuff outside of the Collection [but such Fixtures will be spun up/down] per execution of tests in that Test Class as opposed to ones at Test Collection level which will be spun up/down just the once for the entire run and handed to all Test Classes in the collection as they take their turn to access the Collection Fixture])

Body:
I am writing test cases for my DataAccessRepository ( using entity framework) class. This class takes two argument in constructor.
1) connection object
2) Automapper object

Now, I am using collectionFixture in xunit to pass DatabaseFixture in my test class but I need to pass AutoMapper Fixture as well to the same test class. I tried adding two collection, one after another but it is not valid.  Can someone please throw some light on how to use more than one FixtureCollection on a test class in xunit.

My Unit test class looks as follows and it is throwing error as I can not use two CollectionFixture attribute on the class,

`

[Collection(Traits.DatabaseFixtureCollection)]
    [Collection(Traits.AutomapperFixtureCollection)]
    public class MyAssessmentRepositoryTests
    {
        private readonly IMyAssessmentsRepository _Repo;
        public MyAssessmentRepositoryTests(DatabaseFixture dbFixture,AutomapperFixture amFixture)
        {
            this._Repo = new MyAssessmentRepository(dbFixture.IcmDbContext,amFixture.Mapper);

        }
 }`


问:
Avoiding define macro when making a lot of similar method calls
The code below uses the #define macro. I'd like to avoid this but I don't see a way that uses C++ features and is more readable. The code is for testing a class ClassUnderTest that merges two instances of PoorLegacyClass into one. This PoorLegacyClass has many getters and setters and for testing purposes I need to call a lot of setters (or do I?).

In short, instead of writing

```<code>a.setValueX(20);
b.setValueX(30);
</code>```

I would like to write something like

```<code>set(a, b, ValueX, 20, 30);
// or
set<ValueX>(a, 20, b, 30);
// or even
set(a, b, &PoorLegacyClass::setValueX, 20, 30);
</code>```

Here is code similar to the code I use at the moment:

```<code>#include <boost/test/unit_test.hpp>

#include "ClassUnderTest.h"

BOOST_AUTO_TEST_SUITE(Test_ClassUnderTest);

#define SETTER_A_B(fieldname, valueA, valueB)\
        a.set##fieldname(valueA);\
        b.set##fieldname(valueB);

struct TestContext
{
    PoorLegacyClass a, b;
};

BOOST_FIXTURE_TEST_CASE(ClassUnderTest_meaningful_description1, TestContext)
{
    SETTER_A_B(ValueX, 20, 30);
    auto result = ClassUnderTest().merge(a, b);

    BOOST_TEST(20 == result.getValueX());
}

BOOST_FIXTURE_TEST_CASE(ClassUnderTest_meaningful_description2, TestContext)
{
    SETTER_A_B(ValueY, 21, 37);
    auto result = ClassUnderTest().merge(a, b);

    BOOST_TEST(21 + 37 == result.getValueY());
}

BOOST_FIXTURE_TEST_CASE(ClassUnderTest_meaningful_description3, TestContext)
{
    SETTER_A_B(ValueZ, 12, 83);
    auto result = ClassUnderTest().merge(a, b);

    BOOST_TEST(12 + 83 == result.getValueZ());
}

BOOST_FIXTURE_TEST_CASE(ClassUnderTest_meaningful_description4, TestContext)
{
    SETTER_A_B(ValueY, 212, 37);
    SETTER_A_B(ValueX, 20, 30);
    auto result = ClassUnderTest().merge(a, b);

    BOOST_TEST(a.getValueY() == result.getValueY());
}

// more test cases that are similar to those above

BOOST_AUTO_TEST_SUITE_END();
</code>```

While I will refactor PoorLegacyClass in the future that is not the subject of this question. What I would like to know, though, is how to avoid using the #define macro.

答:
Since you're willing to accept the syntax set(a, b, &PoorLegacyClass::setValueX, 20, 30);, implementing such a set should be easy:

```<code>template <class T>
void set(PoorLegacyClass &a, PoorLegacyClass &b, void (PoorLegacyClass::*setter)(T), T valForA, T valForB)
{
  (a.*setter)(valForA);
  (b.*setter)(valForB);
}
</code>```

You could also make it so that the valFor parameters use T in a non-deduced context, so that T can only be deduced from the setter and implicit conversions happen on the values:

```<code>template <class T>
struct NonDeduced { using type = T; }

template <class T>
void set(PoorLegacyClass &a, PoorLegacyClass &b, void (PoorLegacyClass::*setter)(T), typename NonDeduced<T>::type valForA, typename NonDeduced<T>::type valForB)
</code>```

Body:
The code below uses the #define macro. I'd like to avoid this but I don't see a way that uses C++ features and is more readable. The code is for testing a class ClassUnderTest that merges two instances of PoorLegacyClass into one. This PoorLegacyClass has many getters and setters and for testing purposes I need to call a lot of setters (or do I?).

In short, instead of writing

a.setValueX(20);
b.setValueX(30);

I would like to write something like

set(a, b, ValueX, 20, 30);
// or
set<ValueX>(a, 20, b, 30);
// or even
set(a, b, &PoorLegacyClass::setValueX, 20, 30);

Here is code similar to the code I use at the moment:

#include <boost/test/unit_test.hpp>

#include "ClassUnderTest.h"

BOOST_AUTO_TEST_SUITE(Test_ClassUnderTest);

#define SETTER_A_B(fieldname, valueA, valueB)\
        a.set##fieldname(valueA);\
        b.set##fieldname(valueB);

struct TestContext
{
    PoorLegacyClass a, b;
};

BOOST_FIXTURE_TEST_CASE(ClassUnderTest_meaningful_description1, TestContext)
{
    SETTER_A_B(ValueX, 20, 30);
    auto result = ClassUnderTest().merge(a, b);

    BOOST_TEST(20 == result.getValueX());
}

BOOST_FIXTURE_TEST_CASE(ClassUnderTest_meaningful_description2, TestContext)
{
    SETTER_A_B(ValueY, 21, 37);
    auto result = ClassUnderTest().merge(a, b);

    BOOST_TEST(21 + 37 == result.getValueY());
}

BOOST_FIXTURE_TEST_CASE(ClassUnderTest_meaningful_description3, TestContext)
{
    SETTER_A_B(ValueZ, 12, 83);
    auto result = ClassUnderTest().merge(a, b);

    BOOST_TEST(12 + 83 == result.getValueZ());
}

BOOST_FIXTURE_TEST_CASE(ClassUnderTest_meaningful_description4, TestContext)
{
    SETTER_A_B(ValueY, 212, 37);
    SETTER_A_B(ValueX, 20, 30);
    auto result = ClassUnderTest().merge(a, b);

    BOOST_TEST(a.getValueY() == result.getValueY());
}

// more test cases that are similar to those above

BOOST_AUTO_TEST_SUITE_END();

While I will refactor PoorLegacyClass in the future that is not the subject of this question. What I would like to know, though, is how to avoid using the #define macro.

Body:
Since you're willing to accept the syntax set(a, b, &PoorLegacyClass::setValueX, 20, 30);, implementing such a set should be easy:

template <class T>
void set(PoorLegacyClass &a, PoorLegacyClass &b, void (PoorLegacyClass::*setter)(T), T valForA, T valForB)
{
  (a.*setter)(valForA);
  (b.*setter)(valForB);
}

You could also make it so that the valFor parameters use T in a non-deduced context, so that T can only be deduced from the setter and implicit conversions happen on the values:

template <class T>
struct NonDeduced { using type = T; }

template <class T>
void set(PoorLegacyClass &a, PoorLegacyClass &b, void (PoorLegacyClass::*setter)(T), typename NonDeduced<T>::type valForA, typename NonDeduced<T>::type valForB)


问:
Javascript (Jquery or MooTools or pure Javascript) hide Element by content or href
I have a HTML that looks like this:

```<code><tr>
<td nowrap="nowrap">
<a href="/home" class="mainlevel_jos_mainmenu_menu" >Home</a>
<a href="/somethingelse" class="mainlevel_jos_mainmenu_menu" >Something Else</a>
<a href="/somethingelse2" class="mainlevel_jos_mainmenu_menu" id="active_menu_jos_mainmenu_menu">Something Else 2</a>
<a href="/somethingelse3" class="mainlevel_jos_mainmenu_menu" >Something Else 3</a>
<a href="/somethingelse4" class="mainlevel_jos_mainmenu_menu">Something Else 4</a>
</td>
</tr>
</code>```

and i need to hide the Element a with content Home, either by href (because its the only element with this href on page) or by content (which is always "Home").

But the problem is, i can not add ID to Home.

答:
Using jQuery:</p>

```<code>$('a[href="/home"]').hide();
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a HTML that looks like this:

Home
Something Else
Something Else 2
Something Else 3
Something Else 4

and i need to hide the Element a with content Home, either by href (because its the only element with this href on page) or by content (which is always "Home").

But the problem is, i can not add ID to Home.

Body:
Using jQuery:

$('a[href="/home"]').hide();


问:
Pic16f818 - set trisa regiter as digital inputs for those bits: RB5 RB6 RB7
I am trying to set RB0 - 7 as digital inputs on my PIC16F818 microcontroller. In order to do that I used the following config:

```<code>void config() {
    //cmcon = 0x07;     // Sets all IO pins to digital
    trisa = 0xFF;       // Set porta as inputs
    trisb = 0x00;       // Set portb as outputs
    adcon1 = 0x07;  // For PIC16F84A comment the line above and uncomment this statement
    portb = 0x00;       // Reset value of portb (portb = 0)
    _CONFIG  & _CP_OFF & _LVP_OFF & _CPD_OFF & _DEBUG_OFF & _MCLR_OFF & _INTRC_IO & _WRT_ENABLE_OFF  & _PWRTE_OFF;

}
</code>```

I test this setting by mapping my porta (8 switch block) to portb (8 bit led block), switches 0 - 4 are working correctly, but switches 5-7 are not responding, however bits are set internally by some other PIC functions and output: (b5)0 (b6)0 (b7)1.

答:
I'd recommend to use Latch for outputting data to a port.

So use "latb" instead of "portb" in your case.

Note that "latb" could be defined differently, depending on the compiler you are using.

Please let me know if it solved the problem.

Also,
For more information about the difference between LATCH and PORT use, refer to this link

Difference between PORT and LATCH on PIC

In this case he asked about PIC18F family, but the answer that is given there is very good for general pic programming (no matter what family it is), so you would benefit from it as well.

Body:
I am trying to set RB0 - 7 as digital inputs on my PIC16F818 microcontroller. In order to do that I used the following config:

void config() {
    //cmcon = 0x07;     // Sets all IO pins to digital
    trisa = 0xFF;       // Set porta as inputs
    trisb = 0x00;       // Set portb as outputs
    adcon1 = 0x07;  // For PIC16F84A comment the line above and uncomment this statement
    portb = 0x00;       // Reset value of portb (portb = 0)
    _CONFIG  & _CP_OFF & _LVP_OFF & _CPD_OFF & _DEBUG_OFF & _MCLR_OFF & _INTRC_IO & _WRT_ENABLE_OFF  & _PWRTE_OFF;

}

I test this setting by mapping my porta (8 switch block) to portb (8 bit led block), switches 0 - 4 are working correctly, but switches 5-7 are not responding, however bits are set internally by some other PIC functions and output: (b5)0 (b6)0 (b7)1.


问:
Who is faster: PEG or GLR?
I'm trying to create some kind of lint tool for the C/AL programming language. So basically I need to perform syntax and lexical analysis against the source code. I've planned to write parser from the scratch, but then discovered that there are a lots of tools helping generate these parsers automatically.

I need performance, since checking 20 megabytes of code in one piece is the normal scenario, and I need that tool to be extendable by custom rules. So I decided to go with JavaScript.

As far I have found two generators I can use Jison and PEG.js.

Which of them give me more parsing performance? Maybe not comparing libraries, but algorithms?

Which one is better for my needs (parsing general purpose programming language)?

UPDATE:
I have found similar Q&As:

Packrat parsing vs. LALR parsing

Performance of parsers: PEG vs LALR(1) or LL(k)

答:
As far I have found two generators I can use Jison and PEG.js.
  Which of them give me more parsing performance?

According to the JavaScript Parser Libraries benchmark I have created
It seems that PEG.js is faster (at least on Chrome/V8).

You can run it online here:
http://sap.github.io/chevrotain/performance/

Note that this benchmark uses the very simple JSON grammar to compare
the performance of the parsing libraries not a larger and more complex programing language grammar.

Title: Who is faster: PEG or GLR?


答:
if you want returning key:value style object.
you must return map or pojo.

for example

```<code>Map resultMap = new HashMap<>();
resultMap.put("success", true);
return resultMap;
</code>```

then you can see return message : {"success":true}

Title: Not receiving json object after returning boolean value in Spring

Body:
I don't know whether I do it right or not but it works so far.

The GetMapping should produce a json, but how exactly is it supposed to produce one if I'm giving it only one boolean and no Map type ? what is it exactly returning then ?

@GetMapping(value = "/getIsTrackedHistory/{name}" , produces = "application/json")
public @ResponseBody boolean getIsTrackedHistory(@PathVariable("name") String name) {
    boolean isTracked = template.getIsTrackedHistory(name);
    return isTracked;
}

My request :

$http.get(localhostUrl + 'getIsTrackedHistory/' + $scope.name
.success(function (data) {
      console.log(JSON.stringify(data)); //prints just true or false, which doesn't look at all like a json object.

Body:
if you want returning key:value style object.
you must return map or pojo.

for example

Map resultMap = new HashMap<>();
resultMap.put("success", true);
return resultMap;

then you can see return message : {"success":true}


问:
Designing GMail like recipient text box
Is there a way to design a Recipient text box like the gmail interface, when clicked it shows cc, bcc fields and on click of bcc or cc they further expand. I used jquery autocomplete multiple for emails. but how to go ahead?

         <input class="" type="text" id="recipients" placeholder="Recipients"/>

         <input type="text" id="subject" placeholder="Subject"/>

         <textarea rows="4" id="body" placeholder="Compose" ></textarea>

```

答:
```<code><html>
<head>
<style>
    .hidden{
        display:none;
    }
    .mailBox {
        border: 1px solid #ccc;
        margin: 0px;
        padding: 0px;
        height: auto;
        width: 400px;
    }
    .mailBox a {
        cursor: pointer;
    }
    .mailRecipients {
        height: auto;
    }
    .mailElem a {
        color: #ccc;
        text-decoration: none;
        margin-left: 10px;
        font-size: 16px;
        font-family: monospace;
    }
    .mailElem {
        border-bottom: 1px solid #ccc;
    }
    .mailElemCnt {
        display: inline-block;
    }
    .mailElemContExpand {
        float: right;
        margin-right: 10px;
        margin-top: 7px;
    }
    .mailElemCntA, .mailElemCntLbl{
        width: 75px;
    }
    .mailElemCnt input {
        width: 240px;
        padding: 10px 0px;
        border: none;
    }
    .mailElemCnt label{
        color: #ccc;
        text-decoration: none;
        margin-left: 10px;
        font-size: 16px;
        font-family: monospace;
    }
    .mailBody {
        width: 400px;
        height: 250px;
        border: none;
        border-bottom: 1px solid #ccc;
    }
    .mailboxBottom input[type=button] {
        padding: 10px 25px;
        background-color: #2196F3;
        color: white;
        border: none;
    }
</style>
</head>
<body>
    <script src="https://code.jquery.com/jquery-3.2.1.min.js" ></script>
    <div class="mailBox">
        <div class="mailRecipients">
            <div class="mailElem">
                <div class="mailElemCnt mailElemCntA">
                    <a onClick="alert('Add Dialog for Contact List');">To</a>
                </div>
                <div class="mailElemCnt">
                    <input type="text" id="mailTo" placeholder="abcTo@xyz.com"/>
                </div>
                <div class="mailElemCnt mailElemContExpand">
                    <a onClick="openCC()">CC</a>
                    <a onClick="openBCC()">BCC</a>
                </div>
            </div>
            <div id="mailIDCc" class="mailElem hidden">
                <div class="mailElemCnt mailElemCntA">
                    <a onClick="alert('Add Dialog for Contact List');">CC</a>
                </div>
                <div class="mailElemCnt">
                    <input type="text" id="mailCC" placeholder="abcCC@xyz.com"/>
                </div>
            </div>
            <div id="mailIDBcc" class="mailElem hidden">
                <div class="mailElemCnt mailElemCntA">
                    <a onClick="alert('Add Dialog for Contact List');">BCC</a>
                </div>
                <div class="mailElemCnt">
                    <input type="text" id="mailBCC" placeholder="abcBCC@xyz.com"/>
                </div>
            </div>
            <div id="mailIDSubject" class="mailElem">
                <div class="mailElemCnt mailElemCntLbl">
                    <label>Subject</label>
                </div>
                <div class="mailElemCnt">
                    <input type="text" id="mailSubject" placeholder="My Subject"/>
                </div>
            </div>
        </div>
        <div class="mailBodyBox">
            <textarea rows="4" id="mailIDBody" placeholder="Compose" class="mailBody"></textarea>
        </div>
        <div  class="mailboxBottom mailSend">
            <input type="button" value="Send" onClick="alert('Change Related to Mail Submit');"/>
        </div>
    </div>
    <script>
        function openCC(){
            $('#mailIDCc').toggle(500);
        }
        function openBCC(){
            $('#mailIDBcc').toggle(500);
        }
    </script>
</body>enter image description here
</html>
</code>```

Title: Designing GMail like recipient text box


答:
You should be able to compare each realTime with the last one in your setInterval. If the difference is far from the 1000ms that it is supposed to be, do an ajax call to query the server time again and renew the timeDiff.

Also you can try to use performance.now instead of Date.now. The higher resolution is unnecessary and possibly expensive, but MDN states that

unlike Date.now(), the values returned by Performance.now() always increase at a constant rate, independent of the system clock (which might be adjusted manually or skewed by software like NTP)

Title: Javascript clock - server time

Body:
I need to show the server time on a clock. Below is the code i currently have. I get the server time with Ajax call. The problem is that if the user changes it's local/computer clock it will also update the script's clock which is not ok - it should continue without changing and i'm stuck. I've tried passing the serverTime within the setTimeout so it get's used every time as a reference but no luck with that.

var serverTime  = 1490856278000;
var localTime   = +Date.now();
var timeDiff    = serverTime - localTime;
var realTime;
var date;
var hours;
var minutes;
var seconds;
setInterval(function () {
  realTime = +Date.now() + timeDiff;
  date     = new Date(realTime);
  hours    = date.getHours();
  minutes  = date.getMinutes();
  seconds  = date.getSeconds();
  document.getElementById('clock').innerHTML = hours + ':' + minutes + ':' + seconds;
}, 1000);


问:
Best way to read/parse a untyped binary file in Delphi
I would like to know what is the best way to parse an untyped binary file. For example, a EBML file. (http://ebml.sourceforge.net/). EBML is basically a binary xml file. It can store basically anything, but its predominate use right now are MKV video files (matroska).

To read a EBML file at the byte level, reading the header making sure it is a EBML file and retrieving information on the file. MKV files can be huge, 1-30gb in size.

The binary file could be anything, jpeg, bmp, avi etc ...
I just want to learn how to read them.

答: You could memory map the file. Then you can access it as if you were accessing memory. See http://msdn.microsoft.com/en-us/library/aa366556(VS.85).aspx</p>


问:
Selected Spinner data not appear
i have implemented Spinner, getting data of spinner from Server when selecting value from drop down list it does not Selected

```<code>    timeSpinner=(Spinner)findViewById(R.id.snipper2);
        timeSpinner.setAdapter(new ArrayAdapter<String>(singleDay.this,android.R.layout.simple_spinner_dropdown_item,dateArrayList));
        timeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                Toast.makeText(singleDay.this, "i am working...", Toast.LENGTH_SHORT).show();
                Toast.makeText(singleDay.this, ""+adapterView.getSelectedItem(), Toast.LENGTH_SHORT).show();
String s=timeSpinner.getSelectedItem().toString();
                textView.setText(s);

            }

    @Override
    public void onNothingSelected(AdapterView<?> adapterView) {
        Toast.makeText(singleDay.this, "i am working...", Toast.LENGTH_SHORT).show();
    }
</code>```

Xml code here:

```<code><Spinner
                android:id="@+id/snipper2"
                android:layout_row="1"
                android:background="@drawable/layout_bg"
                android:layout_column="1"
                android:layout_columnSpan="2"
                android:textColorHint="#05ab9a"
                android:prompt="@string/spinnertitle"
                android:layout_width="129dp"
                android:layout_height="39dp"

                />
</code>```

screenshots attached below:

答:
Change spinner height and width. It appears to be too small to display data.

Change your code to this

```<code>ArrayAdapter<String> dataAdapter  = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,dateArrayList);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

timeSpinner.setAdapter(dataAdapter);
</code>```

You can use getItemAtPosition() method to get the selected item:

```<code>@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
final String itemSelected = parent.getItemAtPosition(position).toString();
Log.i("Item Selected: ", itemSelected);
}
</code>```

Title: Selected Spinner data not appear

Body:
i have implemented Spinner, getting data of spinner from Server when selecting value from drop down list it does not Selected

    timeSpinner=(Spinner)findViewById(R.id.snipper2);
        timeSpinner.setAdapter(new ArrayAdapter<String>(singleDay.this,android.R.layout.simple_spinner_dropdown_item,dateArrayList));
        timeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                Toast.makeText(singleDay.this, "i am working...", Toast.LENGTH_SHORT).show();
                Toast.makeText(singleDay.this, ""+adapterView.getSelectedItem(), Toast.LENGTH_SHORT).show();
String s=timeSpinner.getSelectedItem().toString();
                textView.setText(s);

            }

    @Override
    public void onNothingSelected(AdapterView<?> adapterView) {
        Toast.makeText(singleDay.this, "i am working...", Toast.LENGTH_SHORT).show();
    }

Xml code here:

<Spinner
                android:id="@+id/snipper2"
                android:layout_row="1"
                android:background="@drawable/layout_bg"
                android:layout_column="1"
                android:layout_columnSpan="2"
                android:textColorHint="#05ab9a"
                android:prompt="@string/spinnertitle"
                android:layout_width="129dp"
                android:layout_height="39dp"

                />

screenshots attached below:

Body:
Change spinner height and width. It appears to be too small to display data.

Change your code to this

ArrayAdapter<String> dataAdapter  = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,dateArrayList);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

timeSpinner.setAdapter(dataAdapter);

You can use getItemAtPosition() method to get the selected item:

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
final String itemSelected = parent.getItemAtPosition(position).toString();
Log.i("Item Selected: ", itemSelected);
}


问:
Common libraries in a large team
Assume you have five products, and all of them use one or more of the company's internal libraries, written by individual developers.

It sounds simple but in practice, I found it to be very difficult to maintain.

How do you deal with the following scenarios:

A developer unintentionally introduces a bug and breaks everything in production.

Every library has to mature, That means the API needs to evolve, so how do you deploy the updated version to production if every developer needs to update/test their code while they are extremely busy on other projects? Is this a resource and time issue?

Version control, deployment,and usage. Would you store this in one global location or force each project to use, say, svn:externals to "tie" a library?

I've found that it is extremely hard to come up with a good strategy. My own pet theory is this:

Each common library has to have a super-thorough set of tests or else it should never be common, even if it means someone else duplicates the effort. Duplicate untested code is better than common untested code (you break only one project).

Each common library has to have a dedicated maintainer (can be offset by a really good test suite in a smaller team).

Each project should check out the version of the library that is known to work with it. This means a developer does not have to get pulled away to update API usage, as the common code gets updated. Which it will be. Every non-trivial piece of code evolves over months and years.

Thank you for your thoughts on this!

答:
I agree - this is difficult. In our small team (consulting .. not a product company - which made it harder), we had one common component that stood out from the others. In this case the recipe for success was:

Make a good developer responsible for developing the component

Make a good developer the gatekeeper for maintaining the component

Make sure all upgrades (there were several) are backward compatible

Make sure there is some basic documentation (or a simple reference application) explaining how the component is to be used

Make sure all developers know that the component exists (!) and where they can find it (along with the code, if they wish to review it)

Give developers the ability to review the code and suggest better implementations or refectoring, but have the final mods go through an experienced gatekeeper. When the component were upgraded, older apps did not have to upgrade. If we did a new release, we evaluated if we wanted to upgrade, and if we did, all we needed to do was swap the libraries - no code needed to change, unless we wanted to use some new features available through the upgrade. Resistance is inevitable, but sometimes it is a good sort of resistance when it comes from good developers who have better ideas for a new generation or refactored component.

OwnerDisplayName: Andrei

Title: Common libraries in a large team

LastEditorDisplayName: Roger Lipscombe


问:
Boost ASIO connect failing
I want to do a simple C++ web get using boost asio

I started by using this as an example http://www.boost.org/doc/libs/1_49_0/doc/html/boost_asio/example/ssl/client.cpp

but I keep getting messages like this

Connect failed: No connection could be made because the target machine
  actively refused it

答:
This is embarrassing, the issue was a typo in the hostname. When referencing an invalid hostname you can get this error message:

No connection could be made because the target machine actively
  refused it

Putting this answer here in case someone else encounters the same bone headed mistake

Title: Boost ASIO connect failing


问:
Are EF6 migrations supported on SAP HANA database?
I need to know if it is possible to use the ef code first approach with migrations with a SAP HANA database.

This particular is very important because based on it we will decide to use this database or remain with the platform that we already used.

Thank you.

答:
Trying to EF in SAP HANA 2.0. There is documentation about Entity Framework:
link

But in version 2.0.62 of SAP client libraries implementation EF Provider is not full. It generates NEWID insted of SYSUIID for example.


答:
you can use jquery's hide by giving class name which you have

```<code>give one more class name to the home like test

<a href="/home" class="mainlevel_jos_mainmenu_menu test" >Home</a>

$(".test").hide();
</code>```

for more details see here

http://api.jquery.com/hide/

Title: Javascript (Jquery or MooTools or pure Javascript) hide Element by content or href

Body:
you can use jquery's hide by giving class name which you have

give one more class name to the home like test

<a href="/home" class="mainlevel_jos_mainmenu_menu test" >Home</a>

$(".test").hide();

for more details see here

http://api.jquery.com/hide/


问:
Two columns of a table referring to PK of another table in JPA
We have two tables

Table1(Name=Comment, PK is "ID"): (Lookup table)

```<code>ID Description Type
1  Desc1       Type1
2  Desc2       Type2
</code>```

Table2(Name=Steps, PK is "ID"):(Values has to be persisted and retrieved)

```<code>ID  Value    Comment1    Comment2
1   Value1    1           2
2   Value2    1           NULL
</code>```

Comment1 and Comment2 are individually referring to ID of table1.

For each step in table 2 there might be different combinations of comment1 and comment2 referring to table1 (Comment1-has values w.r.t table1 with type as Type1, similarly Comment2).

What is the relationship that has to be defined in JPA for the entity comment in entity Step? We tried with ManyToOne on comment1 and comment2 of Step and had the following issues when retrieving the data(Although there was no issue when saving the data),

When retrieving data from Step, the description of comment is not being fetched on certain case where the data was retrieved immediately after persisting. But the value was fetched after the server was restarted. Do we have to explicitly join the tables when fetching(tried left join using criteria query). Should we have to edit the fetch type(tried both eager and lazy). Or does it have to do anything with cache refresh hints?

Annotation currently used,

```<code>@ManyToOne(fetch =FetchType.Eager, optional = false, cascade = CascadeType.REFRESH)
</code>```

答:
Your design is not normalized. You should add an intermediate table between comment and steps table.

```<code>comment table
    ID Description Type
    1  Desc1       Type1
    2  Desc2       Type2

step_comment table
    step_id comment_id
    1           1
    1           2
    2           1

step table
    ID  Value
    1   Value1
    2   Value2
</code>```

You should consider using many to many association. Below is the example of many to many bidirectional association between 2 entity:

```<code>@Entity
public class Step {

  @Id
  @Column(name="ID")
  private long id;
  ...
  @ManyToMany
  @JoinTable(
      name="step_comment",
      joinColumns=@JoinColumn(name="step_id", referencedColumnName="ID"),
      inverseJoinColumns=@JoinColumn(name="comment_id", referencedColumnName="ID"))
  private List<Comment> comments;
  .....
}

@Entity
public class Comment {

  @Id
  @Column(name="ID")
  private long id;
  ...
  @ManyToMany(mappedBy="comments")
  private List<Step> steps;
  ...
}
</code>```

Please refer to the JPA Wiki for more information: https://en.wikibooks.org/wiki/Java_Persistence/ManyToMany

Body:
We have two tables

Table1(Name=Comment, PK is "ID"): (Lookup table)

ID Description Type
1  Desc1       Type1
2  Desc2       Type2

Table2(Name=Steps, PK is "ID"):(Values has to be persisted and retrieved)

ID  Value    Comment1    Comment2
1   Value1    1           2
2   Value2    1           NULL

Comment1 and Comment2 are individually referring to ID of table1.

For each step in table 2 there might be different combinations of comment1 and comment2 referring to table1 (Comment1-has values w.r.t table1 with type as Type1, similarly Comment2).

What is the relationship that has to be defined in JPA for the entity comment in entity Step? We tried with ManyToOne on comment1 and comment2 of Step and had the following issues when retrieving the data(Although there was no issue when saving the data),

When retrieving data from Step, the description of comment is not being fetched on certain case where the data was retrieved immediately after persisting. But the value was fetched after the server was restarted. Do we have to explicitly join the tables when fetching(tried left join using criteria query). Should we have to edit the fetch type(tried both eager and lazy). Or does it have to do anything with cache refresh hints?

Annotation currently used,

@ManyToOne(fetch =FetchType.Eager, optional = false, cascade = CascadeType.REFRESH)

Body:
Your design is not normalized. You should add an intermediate table between comment and steps table.

comment table
    ID Description Type
    1  Desc1       Type1
    2  Desc2       Type2

step_comment table
    step_id comment_id
    1           1
    1           2
    2           1

step table
    ID  Value
    1   Value1
    2   Value2

You should consider using many to many association. Below is the example of many to many bidirectional association between 2 entity:

@Entity
public class Step {

  @Id
  @Column(name="ID")
  private long id;
  ...
  @ManyToMany
  @JoinTable(
      name="step_comment",
      joinColumns=@JoinColumn(name="step_id", referencedColumnName="ID"),
      inverseJoinColumns=@JoinColumn(name="comment_id", referencedColumnName="ID"))
  private List<Comment> comments;
  .....
}

@Entity
public class Comment {

  @Id
  @Column(name="ID")
  private long id;
  ...
  @ManyToMany(mappedBy="comments")
  private List<Step> steps;
  ...
}

Please refer to the JPA Wiki for more information: https://en.wikibooks.org/wiki/Java_Persistence/ManyToMany


问:
Tesseract 3.05 mac and android giving different results
I am using tesseract in my android application. For some reason, the result returned from tesseract in my mac is different to the result returned from the android application, even with the same image. I am using tesseract 3.05 in my mac and tess-two library, which also uses tesseract 3.05 and the language is english, both are using the eng.traineddata. Is there any particular reason for this?</p>

答:
I cannot point to any sources, but I remember having read that Tesseract has a cutoff of how much time it will spend on a given portion of the image. This is to prevent it from taking too much time. So on devices with less CPU, the recognition might degrade instead of becoming slower.

Android has less CPU power, so this cut-off is reached sooner.


问:
neovim spits out weird character on terminal upon closing
I have install neovim and linked the .vimrc to the .config/nvim/init file. neovim splits out the following character [2 q% on the terminal screen upon closing. The weird characters even appears when I press : inside neovim.

答:
In Nvim 0.1.7, that happens because your terminal (1) doesn't support cursor shape control sequences, and (2) doesn't properly ignore unknown sequences. To avoid it, put this in your ~/.config/nvim/init.vim:

```<code>let $NVIM_TUI_ENABLE_CURSOR_SHAPE=0
</code>```

That's also mentioned in man nvim.

In Nvim 0.2, cursor styling is controlled by the guicursor option. If you see "weird characters" like [2 q%, it means your terminal (probably) doesn't support this feature, but guicursor was enabled somewhere in your configuration. Disable guicursor by setting it empty:

```<code>:set guicursor=
</code>```

(Nvim disables guicursor by default if it's not sure about your terminal. But if you set guicursor anyway, Nvim will send the cursor shape control sequences to the terminal.)

Body:
In Nvim 0.1.7, that happens because your terminal (1) doesn't support cursor shape control sequences, and (2) doesn't properly ignore unknown sequences. To avoid it, put this in your ~/.config/nvim/init.vim:

let $NVIM_TUI_ENABLE_CURSOR_SHAPE=0

That's also mentioned in man nvim.

In Nvim 0.2, cursor styling is controlled by the guicursor option. If you see "weird characters" like [2 q%, it means your terminal (probably) doesn't support this feature, but guicursor was enabled somewhere in your configuration. Disable guicursor by setting it empty:

:set guicursor=

(Nvim disables guicursor by default if it's not sure about your terminal. But if you set guicursor anyway, Nvim will send the cursor shape control sequences to the terminal.)


问:
How do you toggle an active state ng-class in an ng-repeat item using ng-click?
```<code><ul>
  <li data-ng-repeat="image in images" data-ng-click="toggle = !toggle" data-ng-init="toggle=false">
      <img data-ng-class="{'active' : toggle}" src="" />
  </li>
</ul>
</code>```

CSS for 'active' class is from bootstrap.

So toggling works, which is almost where I want it; I would like it similar to active states in navigation links, except in my example it's dealing with images so need to worry about url strings, etc.

I tried emulating this example found here to no avail (I tried the same logic for images): ng-class to highlight active menu item based on ng-repeat. AngularJS

If someone could point me in the right direction, I would greatly appreciate it. :D

答:
You can try it in following way:</p>

```<code><body>
<style>
.blue{
    background:blue;
}
</style>
<div ng-app='my'>
  <div ng-controller='maincontroller as mainctrl'>
    <div ng-repeat='item in mainctrl.arr'>
    <p ng-class='{"blue":mainctrl.bgcolor==item}'
    ng-click='mainctrl.addColor(item)'>
    item {{item}}
    </p>

    </div>
  </div>
</div>
<script>
var app = angular.module('my',[])
app.controller('maincontroller',maincontroller)
function maincontroller(){
var mainctrl = this;
mainctrl.arr = [1,2,3,4,5,6];

mainctrl.addColor = function(data){
mainctrl.bgcolor = data
}
}
</script>
</body>
</code>```

Body:
You can try it in following way:

<body>
<style>
.blue{
    background:blue;
}
</style>
<div ng-app='my'>
  <div ng-controller='maincontroller as mainctrl'>
    <div ng-repeat='item in mainctrl.arr'>
    <p ng-class='{"blue":mainctrl.bgcolor==item}'
    ng-click='mainctrl.addColor(item)'>
    item {{item}}
    </p>

    </div>
  </div>
</div>
<script>
var app = angular.module('my',[])
app.controller('maincontroller',maincontroller)
function maincontroller(){
var mainctrl = this;
mainctrl.arr = [1,2,3,4,5,6];

mainctrl.addColor = function(data){
mainctrl.bgcolor = data
}
}
</script>
</body>


问:
Update a List of objects by comparing with another list
I do have two different lists of same object , one is with sample data , one is with real data. Few fields in the real data are messed up, I need to update the few fields of real data list , by getting those values from sample data .

Both lists are of same object, both have same unique key .

```<code>List<pojo> real = [(code:60,active:Y,account:check),(code:61,active:Y,account:check),(code:62,active:Y,account:check)];

List<pojo> sample = [(code:60,active:Y,account:saving),(code:61,active:Y,account:check),(code:62,active:Y,account:saving)]
</code>```

I have around 60 objects in each list , In the above one I need to update real where code is 60 and 62 - account from check to saving.

I am  using  java 1.8  &  groovy

thanks

答:
Is this what you need?

```<code>class Pojo {
    def code
    def active
    def account

    String toString() {
        account
   }
}

List<Pojo> real = [new Pojo(code: 60, active: 'Y', account: 'check'), new Pojo(code: 61, active: 'Y', account: 'check'), new Pojo(code: 62, active: 'Y', account: 'check')]

List<Pojo> sample = [new Pojo(code: 60, active: 'Y', account: 'saving'), new Pojo(code: 61, active: 'Y', account: 'check'), new Pojo(code: 62, active: 'Y', account: 'saving')]

real.each { r ->
    def acc = sample.find{it.code == r.code}?.account

    if (acc != null) {
        r.account = acc
    }
}

println real // prints [saving, check, saving]
</code>```

The above sample iterates with each over each pojo in real and searches the corresponding object (that with the same code) in the sample list. If the corresponding object is found, the value of account in the object of the real list is overwritten, otherwise it will be left as it is.

Body:
I do have two different lists of same object , one is with sample data , one is with real data. Few fields in the real data are messed up, I need to update the few fields of real data list , by getting those values from sample data .

Both lists are of same object, both have same unique key .

List<pojo> real = [(code:60,active:Y,account:check),(code:61,active:Y,account:check),(code:62,active:Y,account:check)];

List<pojo> sample = [(code:60,active:Y,account:saving),(code:61,active:Y,account:check),(code:62,active:Y,account:saving)]

I have around 60 objects in each list , In the above one I need to update real where code is 60 and 62 - account from check to saving.

I am  using  java 1.8  &  groovy

thanks

Body:
Is this what you need?

class Pojo {
    def code
    def active
    def account

    String toString() {
        account
   }
}

List<Pojo> real = [new Pojo(code: 60, active: 'Y', account: 'check'), new Pojo(code: 61, active: 'Y', account: 'check'), new Pojo(code: 62, active: 'Y', account: 'check')]

List<Pojo> sample = [new Pojo(code: 60, active: 'Y', account: 'saving'), new Pojo(code: 61, active: 'Y', account: 'check'), new Pojo(code: 62, active: 'Y', account: 'saving')]

real.each { r ->
    def acc = sample.find{it.code == r.code}?.account

    if (acc != null) {
        r.account = acc
    }
}

println real // prints [saving, check, saving]

The above sample iterates with each over each pojo in real and searches the corresponding object (that with the same code) in the sample list. If the corresponding object is found, the value of account in the object of the real list is overwritten, otherwise it will be left as it is.