问:
How to make username case insensitive in zf2
I used zf2 authentication for authenticate user in my project.I saved Harib in my user table as user name but if i use my user name Harib then its accept or if i use harib then its not accept,i want to remove case sensitivity of user name so both Harib or harib access how i fix this?

Here is my code:

```<code>public function loginAction()
{
    $this->layout('layout/login-layout.phtml');
    $login_error = false;
    $loginForm = new LoginForm();
    $form_elements = json_encode($loginForm->form_elements);
    if ($this->request->isPost()) {
        $post = $this->request->getPost();
        $loginForm->setData($post);
        if ($loginForm->isValid()) {
            $hashed_string = '';
            if(
                array_key_exists('hashed_input' , $post) &&
                $post['hashed_input'] != '' &&
                strpos(urldecode($this->params('redirect')) , 'programdetailrequest') !== false
            ) {
                $hashed_string = $post['hashed_input'];
            }
            $data = $loginForm->getData();
            $authService = $this->getServiceLocator()->get('doctrine.authenticationservice.odm_default');
            $adapter = $authService->getAdapter();
            $adapter->setIdentityValue($data['username']);
            $adapter->setCredentialValue(md5($data['password']));
            $authResult = $authService->authenticate();
            if($authResult->isValid()){
                $identity = $authResult->getIdentity();
                if( is_object($identity) && method_exists($identity, 'getData') ){
                    $user_data = $identity->getData();
                    $authService->getStorage()->write($identity);
                    // for remeber checkbox
                    if ($post['rememberme']) {
                        $token = new UserToken();
                        $dm = $this->getServiceLocator()->get('doctrine.documentmanager.odm_default');
                        //if same user already running from other browser then remove previous token.
                        $check_token = $dm->getRepository('Admin\Document\UserToken')->findOneBy(array( "user_id.id" => $user_data['id'] ));
                        if (is_object($check_token) && !is_null($check_token)) {
                            $remove_token = $dm->createQueryBuilder('Admin\Document\UserToken')
                                ->remove()
                                ->field('id')->equals($check_token->id)
                                ->getQuery()->execute();
                        }
                        //create token
                        $user = $dm->getRepository('Admin\Document\User')->findOneBy(array( "id" => $user_data['id'] ));
                        $token->setProperty('user_id', $user);
                        $token->setProperty('dataentered', new \MongoDate());
                        $dm->persist($token);
                        $dm->flush($token);
                        //create cookie
                        if(is_object($token) && property_exists($token, 'id')){
                            $time = time() + (60 * 60 * 24 * 30); // 1 month
                            setcookie('token', $token->getProperty('id'), $time, '/');
                        }
                    }
                    if ($user_data['user_type'] == 'onlinemarketer') {
                        $this->redirect()->toRoute('admin_program_meta');
                    } elseif ($user_data['user_type'] == 'bucharestofficemanager') {
                        $this->redirect()->toRoute('admin_program_detail_request');
                    } else {
                        if ($this->params('redirect') && urldecode($this->params('redirect')) !== '/logout/') {
                            $server_url = $this->getRequest()->getUri()->getScheme() . '://' . $this->getRequest()->getUri()->getHost().urldecode($this->params('redirect') . $hashed_string);
                            return $this->redirect()->toUrl($server_url);
                        }
                        return $this->redirect()->toRoute('admin_index');
                    }
                }
            } else {
                $identity = false;
                $login_error = true;
            }
        }
    }
    return new ViewModel(array(
            'loginForm' => $loginForm,
            'form_elements' =>$form_elements,
            'login_error' => $login_error,
    ));
}
</code>```

and here is my login form code:

```<code><?php
namespace Admin\Form;

use Zend\Form\Form;
use Zend\Form\Element;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\Factory as InputFactory;

class LoginForm extends Form implements InputFilterAwareInterface
{
protected $inputFilter;
public $form_elements = array(
    array(
        'name' => 'username',
        'attributes' => array(
            'id' => 'username',
            'type'  => 'text',
            'error_msg' => 'Enter Valid Username',
            'data-parsley-required' => 'true',
            'data-parsley-pattern' => '^[a-zA-Z0-9_\.\-]{1,50}$',
            'data-parsley-trigger' => 'change'
        ),
        'options' => array(
            'label' => 'User Name'
        ),
        'validation' => array(
            'required'=>true,
            'filters'=> array(
                array('name'=>'StripTags'),
                array('name'=>'StringTrim')
            ),
            'validators'=>array(
                array('name'=>'Regex',
                    'options'=> array(
                        'pattern' => '/^[a-z0-9_.-]{1,50}+$/', // contain only a to z 0 to 9 underscore, hypen and space, min 1 max 50
                        'pattern_js' => '^[a-zA-Z0-9_\.\-]{1,50}$'
                    )
                )
            )
        )
    ),
    array(
        'name' => 'password',
        'attributes' => array(
            'id' => 'password',
            'type'  => 'password',
            'error_msg' => 'Enter Valid Password',
            'data-parsley-required' => 'true',
            'data-parsley-pattern' => '^[a-zA-Z0-9_\.\-]{6,25}$',
            'data-parsley-trigger' => 'change'
        ),
        'options' => array(
            'label' => 'Password'
        ),
        'validation' => array(
            'required' => true,
            'filters'=> array(
                array('name'=>'StripTags'),
                array('name'=>'StringTrim')
            ),
            'validators'=>array(
                array('name'=>'Regex',
                    'options'=> array(
                        'pattern' => '/^[a-z0-9_.-]{6,25}+$/', // contain only a to z 0 to 9 underscore, hypen and space, min 1 max 50
                        'pattern_js' => '^[a-zA-Z0-9_\.\-]{6,25}$'
                    )
                )
            )
        )
    ),
    array(
        'name' => 'hashed_input',
        'attributes' => array(
            'type'  => 'hidden',
            'id' => 'hashed_input',
            'value' => ''
        )
    ),
    array(
        'name' => 'rememberme',
        'attributes' => array(
            'value' => 1,
            'id' => 'rememberme',
            'type' => 'Checkbox'
        ),
        'options' => array(
            'label' => 'Remember Me',
            'use_hidden_element' => false,
        )
    ),
    array(
        'name' => 'submit',
        'attributes' => array(
            'type'  => 'submit',
            'value' => 'Log in',
            'id' => 'submitbutton'
        )
    )
);
public function __construct()
{
    parent::__construct('user');
    $this->setAttribute('method', 'post');
    $this->setAttribute('data-parsley-validate', '');
    $this->setAttribute('data-elements', json_encode($this->form_elements));
    $this->setAttribute('autocomplete', 'off');
    for($i=0;$i<count($this->form_elements);$i++){
        $elements=$this->form_elements[$i];
        $this->add($elements);
    }
}
public function getInputFilter($action=false)
{
    if(!$this->inputFilter){
        $inputFilter = new InputFilter();
        $factory = new InputFactory();
        for($i=0;$i<count($this->form_elements);$i++){
            if(array_key_exists('validation',$this->form_elements[$i])){
                $this->form_elements[$i]['validation']['name']=$this->form_elements[$i]['name'];
                $inputFilter->add($factory->createInput( $this->form_elements[$i]['validation'] ));
            }
        }
        $this->inputFilter = $inputFilter;
    }
    return $this->inputFilter;
}
}
</code>```

how we remove case sensitivity of user name so both Harib or harib accepted?

答:
Add a filter StringToLower in your loginform on the element user_id.

For this, the class that defines your loginform must implement InputFilterProviderInterface and you must add in the getInputFilterSpecification method as follows :

```<code>public function getInputFilterSpecification()
{
    return [
        'username' => [
            'name' => 'username',
            'required' => true,
            'filters' => [
                'name' => 'StringToLower',
                'name'=>'StripTags',
                'name'=>'StringTrim'
            ],
            validators => [
                [
                    'name'=>'Regex',
                    'options'=> [
                        'pattern' => '/^[a-z0-9_.-]{1,50}+$/',
                        'pattern_js' => '^[a-zA-Z0-9_\.\-]{1,50}$'
                    ]
                ]
            ]
        ],
        'password' => [
            'name' => 'password',
            'required' => true,
            'filters' => [
                array('name'=>'StripTags'),
                array('name'=>'StringTrim')
            ],
            'validators' => [
                [
                    'name'=>'Regex',
                    'options'=> [
                    'pattern' => '/^[a-z0-9_.-]{6,25}+$/',
                    'pattern_js' => '^[a-zA-Z0-9_\.\-]{6,25}$'
                    ]
                ]
            ]
        ]
    ];
}
</code>```

So you are assured that the value returned in the post is in lowercase.

Body:
I used zf2 authentication for authenticate user in my project.I saved Harib in my user table as user name but if i use my user name Harib then its accept or if i use harib then its not accept,i want to remove case sensitivity of user name so both Harib or harib access how i fix this?

Here is my code:

public function loginAction()
{
    $this->layout('layout/login-layout.phtml');
    $login_error = false;
    $loginForm = new LoginForm();
    $form_elements = json_encode($loginForm->form_elements);
    if ($this->request->isPost()) {
        $post = $this->request->getPost();
        $loginForm->setData($post);
        if ($loginForm->isValid()) {
            $hashed_string = '';
            if(
                array_key_exists('hashed_input' , $post) &&
                $post['hashed_input'] != '' &&
                strpos(urldecode($this->params('redirect')) , 'programdetailrequest') !== false
            ) {
                $hashed_string = $post['hashed_input'];
            }
            $data = $loginForm->getData();
            $authService = $this->getServiceLocator()->get('doctrine.authenticationservice.odm_default');
            $adapter = $authService->getAdapter();
            $adapter->setIdentityValue($data['username']);
            $adapter->setCredentialValue(md5($data['password']));
            $authResult = $authService->authenticate();
            if($authResult->isValid()){
                $identity = $authResult->getIdentity();
                if( is_object($identity) && method_exists($identity, 'getData') ){
                    $user_data = $identity->getData();
                    $authService->getStorage()->write($identity);
                    // for remeber checkbox
                    if ($post['rememberme']) {
                        $token = new UserToken();
                        $dm = $this->getServiceLocator()->get('doctrine.documentmanager.odm_default');
                        //if same user already running from other browser then remove previous token.
                        $check_token = $dm->getRepository('Admin\Document\UserToken')->findOneBy(array( "user_id.id" => $user_data['id'] ));
                        if (is_object($check_token) && !is_null($check_token)) {
                            $remove_token = $dm->createQueryBuilder('Admin\Document\UserToken')
                                ->remove()
                                ->field('id')->equals($check_token->id)
                                ->getQuery()->execute();
                        }
                        //create token
                        $user = $dm->getRepository('Admin\Document\User')->findOneBy(array( "id" => $user_data['id'] ));
                        $token->setProperty('user_id', $user);
                        $token->setProperty('dataentered', new \MongoDate());
                        $dm->persist($token);
                        $dm->flush($token);
                        //create cookie
                        if(is_object($token) && property_exists($token, 'id')){
                            $time = time() + (60 * 60 * 24 * 30); // 1 month
                            setcookie('token', $token->getProperty('id'), $time, '/');
                        }
                    }
                    if ($user_data['user_type'] == 'onlinemarketer') {
                        $this->redirect()->toRoute('admin_program_meta');
                    } elseif ($user_data['user_type'] == 'bucharestofficemanager') {
                        $this->redirect()->toRoute('admin_program_detail_request');
                    } else {
                        if ($this->params('redirect') && urldecode($this->params('redirect')) !== '/logout/') {
                            $server_url = $this->getRequest()->getUri()->getScheme() . '://' . $this->getRequest()->getUri()->getHost().urldecode($this->params('redirect') . $hashed_string);
                            return $this->redirect()->toUrl($server_url);
                        }
                        return $this->redirect()->toRoute('admin_index');
                    }
                }
            } else {
                $identity = false;
                $login_error = true;
            }
        }
    }
    return new ViewModel(array(
            'loginForm' => $loginForm,
            'form_elements' =>$form_elements,
            'login_error' => $login_error,
    ));
}

and here is my login form code:

<?php
namespace Admin\Form;

use Zend\Form\Form;
use Zend\Form\Element;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\Factory as InputFactory;

class LoginForm extends Form implements InputFilterAwareInterface
{
protected $inputFilter;
public $form_elements = array(
    array(
        'name' => 'username',
        'attributes' => array(
            'id' => 'username',
            'type'  => 'text',
            'error_msg' => 'Enter Valid Username',
            'data-parsley-required' => 'true',
            'data-parsley-pattern' => '^[a-zA-Z0-9_\.\-]{1,50}$',
            'data-parsley-trigger' => 'change'
        ),
        'options' => array(
            'label' => 'User Name'
        ),
        'validation' => array(
            'required'=>true,
            'filters'=> array(
                array('name'=>'StripTags'),
                array('name'=>'StringTrim')
            ),
            'validators'=>array(
                array('name'=>'Regex',
                    'options'=> array(
                        'pattern' => '/^[a-z0-9_.-]{1,50}+$/', // contain only a to z 0 to 9 underscore, hypen and space, min 1 max 50
                        'pattern_js' => '^[a-zA-Z0-9_\.\-]{1,50}$'
                    )
                )
            )
        )
    ),
    array(
        'name' => 'password',
        'attributes' => array(
            'id' => 'password',
            'type'  => 'password',
            'error_msg' => 'Enter Valid Password',
            'data-parsley-required' => 'true',
            'data-parsley-pattern' => '^[a-zA-Z0-9_\.\-]{6,25}$',
            'data-parsley-trigger' => 'change'
        ),
        'options' => array(
            'label' => 'Password'
        ),
        'validation' => array(
            'required' => true,
            'filters'=> array(
                array('name'=>'StripTags'),
                array('name'=>'StringTrim')
            ),
            'validators'=>array(
                array('name'=>'Regex',
                    'options'=> array(
                        'pattern' => '/^[a-z0-9_.-]{6,25}+$/', // contain only a to z 0 to 9 underscore, hypen and space, min 1 max 50
                        'pattern_js' => '^[a-zA-Z0-9_\.\-]{6,25}$'
                    )
                )
            )
        )
    ),
    array(
        'name' => 'hashed_input',
        'attributes' => array(
            'type'  => 'hidden',
            'id' => 'hashed_input',
            'value' => ''
        )
    ),
    array(
        'name' => 'rememberme',
        'attributes' => array(
            'value' => 1,
            'id' => 'rememberme',
            'type' => 'Checkbox'
        ),
        'options' => array(
            'label' => 'Remember Me',
            'use_hidden_element' => false,
        )
    ),
    array(
        'name' => 'submit',
        'attributes' => array(
            'type'  => 'submit',
            'value' => 'Log in',
            'id' => 'submitbutton'
        )
    )
);
public function __construct()
{
    parent::__construct('user');
    $this->setAttribute('method', 'post');
    $this->setAttribute('data-parsley-validate', '');
    $this->setAttribute('data-elements', json_encode($this->form_elements));
    $this->setAttribute('autocomplete', 'off');
    for($i=0;$i<count($this->form_elements);$i++){
        $elements=$this->form_elements[$i];
        $this->add($elements);
    }
}
public function getInputFilter($action=false)
{
    if(!$this->inputFilter){
        $inputFilter = new InputFilter();
        $factory = new InputFactory();
        for($i=0;$i<count($this->form_elements);$i++){
            if(array_key_exists('validation',$this->form_elements[$i])){
                $this->form_elements[$i]['validation']['name']=$this->form_elements[$i]['name'];
                $inputFilter->add($factory->createInput( $this->form_elements[$i]['validation'] ));
            }
        }
        $this->inputFilter = $inputFilter;
    }
    return $this->inputFilter;
}
}

how we remove case sensitivity of user name so both Harib or harib accepted?

Body:
Add a filter StringToLower in your loginform on the element user_id.

For this, the class that defines your loginform must implement InputFilterProviderInterface and you must add in the getInputFilterSpecification method as follows :

public function getInputFilterSpecification()
{
    return [
        'username' => [
            'name' => 'username',
            'required' => true,
            'filters' => [
                'name' => 'StringToLower',
                'name'=>'StripTags',
                'name'=>'StringTrim'
            ],
            validators => [
                [
                    'name'=>'Regex',
                    'options'=> [
                        'pattern' => '/^[a-z0-9_.-]{1,50}+$/',
                        'pattern_js' => '^[a-zA-Z0-9_\.\-]{1,50}$'
                    ]
                ]
            ]
        ],
        'password' => [
            'name' => 'password',
            'required' => true,
            'filters' => [
                array('name'=>'StripTags'),
                array('name'=>'StringTrim')
            ],
            'validators' => [
                [
                    'name'=>'Regex',
                    'options'=> [
                    'pattern' => '/^[a-z0-9_.-]{6,25}+$/',
                    'pattern_js' => '^[a-zA-Z0-9_\.\-]{6,25}$'
                    ]
                ]
            ]
        ]
    ];
}

So you are assured that the value returned in the post is in lowercase.


来源: stackexchange

问:
How to export _all_ nodes and all relations from Neo4j into Gephi?
I intend to export my entire graph (both nodes with relations and "independent" nodes) into Gephi. In order to achieve it, I currenly execute two queries:

```<code>// export relationships
match path = (n)--()
with collect(path) as paths
call apoc.gephi.add(null, 'workspace1', paths, '', ['attr1', 'attr2']) yield nodes, relationships, time
return nodes, relationships, time

// export independent nodes
match path = (p)
where not (p)--()
with collect(path) as paths
call apoc.gephi.add(null, 'workspace1', paths, '', ['attr1', 'attr2']) yield nodes, relationships, time
return nodes, relationships, time
</code>```

I have tried to replace them with a single query like:

```<code>match path = (n)-[*0..]-()
with collect(path) as paths
call apoc.gephi.add(null, 'workspace1', paths, '', ['attr1', 'attr2']) yield nodes, relationships, time
return nodes, relationships, time
</code>```

Unfortunately the query never finishes and effectively DoS-es Neo4j (results in high CPU and RAM consumption on Neo4j side and makes it unresponsive).
I have also tried to limit the relations depth with [*0..10] but it didn't help.

What would be a correct way to export my data with a single query?

答:
I would try in your case the following...

```<code>match path = (n)-[*0..1]->()
with collect(path) as paths
call apoc.gephi.add(null, 'workspace1', paths, '', ['attr1', 'attr2']) yield nodes, relationships, time
return nodes, relationships, time
</code>```

So we have added the direction of relationships and limit to only 1 hop. This way we remove exporting duplicates and speed up export.

ContentLicense: CC BY-SA 3.0

Body:
I intend to export my entire graph (both nodes with relations and "independent" nodes) into Gephi. In order to achieve it, I currenly execute two queries:

// export relationships
match path = (n)--()
with collect(path) as paths
call apoc.gephi.add(null, 'workspace1', paths, '', ['attr1', 'attr2']) yield nodes, relationships, time
return nodes, relationships, time

// export independent nodes
match path = (p)
where not (p)--()
with collect(path) as paths
call apoc.gephi.add(null, 'workspace1', paths, '', ['attr1', 'attr2']) yield nodes, relationships, time
return nodes, relationships, time

I have tried to replace them with a single query like:

match path = (n)-[*0..]-()
with collect(path) as paths
call apoc.gephi.add(null, 'workspace1', paths, '', ['attr1', 'attr2']) yield nodes, relationships, time
return nodes, relationships, time

Unfortunately the query never finishes and effectively DoS-es Neo4j (results in high CPU and RAM consumption on Neo4j side and makes it unresponsive).
I have also tried to limit the relations depth with [*0..10] but it didn't help.

What would be a correct way to export my data with a single query?

Body:
I would try in your case the following...

match path = (n)-[*0..1]->()
with collect(path) as paths
call apoc.gephi.add(null, 'workspace1', paths, '', ['attr1', 'attr2']) yield nodes, relationships, time
return nodes, relationships, time

So we have added the direction of relationships and limit to only 1 hop. This way we remove exporting duplicates and speed up export.


问:
"Unwrapping" SklearnClassifier Object - NLTK Python
I have used the SklearnClassifier() wrapper from the NLTK python package to train a couple of sklearn classifiers (LogisticRegression() and RandomForest()) for a binary classification problem where text are features. Is there any functionality that allows one to "unwrap" this object so that one can access things such as parameter estimates (for logistic regression) or the variable importance list from the random forest (or any of the items available from the original sklearn object)? The nltk classifier object can score new instances so the underlying information must be contained in that object somewhere? Thank you for you thoughts.</p>

答:
Your classifier is hidden under _clf variable.

```<code>classifier = SKLearnClassifier(MLPClassifier())
mlp = classifier._clf
</code>```

Documentation found at http://www.nltk.org/_modules/nltk/classify/scikitlearn.html :

```<code>def __init__(self, estimator, dtype=float, sparse=True):
    """
    :param estimator: scikit-learn classifier object.

    :param dtype: data type used when building feature array.
        scikit-learn estimators work exclusively on numeric data. The
        default value should be fine for almost all situations.

    :param sparse: Whether to use sparse matrices internally.
        The estimator must support these; not all scikit-learn classifiers
        do (see their respective documentation and look for "sparse
        matrix"). The default value is True, since most NLP problems
        involve sparse feature sets. Setting this to False may take a
        great amount of memory.
    :type sparse: boolean.
    """
    self._clf = estimator
    self._encoder = LabelEncoder()
    self._vectorizer = DictVectorizer(dtype=dtype, sparse=sparse)
</code>```

Body:
Your classifier is hidden under _clf variable.

classifier = SKLearnClassifier(MLPClassifier())
mlp = classifier._clf

Documentation found at http://www.nltk.org/_modules/nltk/classify/scikitlearn.html :

def __init__(self, estimator, dtype=float, sparse=True):
    """
    :param estimator: scikit-learn classifier object.

    :param dtype: data type used when building feature array.
        scikit-learn estimators work exclusively on numeric data. The
        default value should be fine for almost all situations.

    :param sparse: Whether to use sparse matrices internally.
        The estimator must support these; not all scikit-learn classifiers
        do (see their respective documentation and look for "sparse
        matrix"). The default value is True, since most NLP problems
        involve sparse feature sets. Setting this to False may take a
        great amount of memory.
    :type sparse: boolean.
    """
    self._clf = estimator
    self._encoder = LabelEncoder()
    self._vectorizer = DictVectorizer(dtype=dtype, sparse=sparse)


问:
Undefined reference to `vtable
I am creating a GUI application using Qt; I try to do hello world using Qt and it works perfectly, but when I create custom list widget I get undefined reference to vtable error when I compile it:

I am using eclipse and c++

```<code>#ifndef QMENUFILTER_H_
#define QMENUFILTER_H_
#include <qmenu.h>
class CustomMenuFilter : QMenu
{
    Q_OBJECT
public:
    CustomMenuFilter () ;
    ~CustomMenuFilter() ;
private:
    QMenu FilterMenu;
    QAction *AddFilterAct ;
    QAction *DeleteFilterAct ;

     Q_SLOT
      void contextMenuEvent(QContextMenuEvent *event);
};
#endif /* QMENUFILTER_H_ */

#include "QMenuFilter.h"
CustomMenuFilter::CustomMenuFilter():QMenu()
{
    DeleteFilterAct = new QAction("DeleteFilter" , this);
    AddFilterAct = new QAction("AddFilter" , this);
    AddFilterAct->setText("AddFilter");
    DeleteFilterAct->setText("DeleteFilter");
}
</code>```

LOG file :
http://pastebin.com/raw.php?i=qZes6bkm

答:
Set CMAKE_AUTOMOC to ON, this fixed my problem.</p>

```<code>#Find includes in corresponding build directories
set(CMAKE_INCLUDE_CURRENT_DIR ON)

# Instruct CMake to run moc automatically when needed.
set(CMAKE_AUTOMOC ON)
</code>```

Title: Undefined reference to `vtable

Body:
I am creating a GUI application using Qt; I try to do hello world using Qt and it works perfectly, but when I create custom list widget I get undefined reference to vtable error when I compile it:

I am using eclipse and c++

#ifndef QMENUFILTER_H_
#define QMENUFILTER_H_
#include <qmenu.h>
class CustomMenuFilter : QMenu
{
    Q_OBJECT
public:
    CustomMenuFilter () ;
    ~CustomMenuFilter() ;
private:
    QMenu FilterMenu;
    QAction *AddFilterAct ;
    QAction *DeleteFilterAct ;

     Q_SLOT
      void contextMenuEvent(QContextMenuEvent *event);
};
#endif /* QMENUFILTER_H_ */

#include "QMenuFilter.h"
CustomMenuFilter::CustomMenuFilter():QMenu()
{
    DeleteFilterAct = new QAction("DeleteFilter" , this);
    AddFilterAct = new QAction("AddFilter" , this);
    AddFilterAct->setText("AddFilter");
    DeleteFilterAct->setText("DeleteFilter");
}

LOG file :
http://pastebin.com/raw.php?i=qZes6bkm

Body:
Set CMAKE_AUTOMOC to ON, this fixed my problem.

#Find includes in corresponding build directories
set(CMAKE_INCLUDE_CURRENT_DIR ON)

# Instruct CMake to run moc automatically when needed.
set(CMAKE_AUTOMOC ON)


问:
How to add number before a word inside a text file?
I have this menu inside a text file:

#Menu 1 file
Jelly Fish Yee Sang with Pear
Dried Seafood with Fish Soup
Steamed Sea Water Grouper
```

<p>and I have this code:</p>

```menuList = input('enter number:')
def printPackage(menuList):
    if menuList == '1':
        with open('menu/Menu1.txt')as f:
            data = f.read()
            print(data)
printPackage(menuList)
```

<p>What should I add to my code so that I have my text file to print like this?</p>

<pre class="lang-none prettyprint-override"><code>---------
Menu List
---------
1. Jelly Fish Yee Sang with Pear
2. Dried Seafood with Fish Soup
3. Steamed Sea Water Grouper
</code>```

Help please.

答:
```<code>menuList = input('enter number:')
def printPackage(menuList):
    if menuList == '1':
        with open('menu/Menu1.txt')as f:
            lines = []
            for l_i, line in enumerate(f.read().split('\n'), 1):  # Read the file and split it on newline. Enumerate the results returning index (l_i) and the line. Start l_i at 1
                formatted_line = '%s. %s' % (l_i, line)  # Format it with the line number.
                print(formatted_line)
                lines.append(formatted_line)

            # If you want to save it.
            with open('menu/Menu1_with_numbers.txt', 'w') as o_f:
                o_f.write('\n'.join(lines))  # Join back the lines on newline and write it out to Menu1_with_numbers.txt
</code>```

Body:
I have this menu inside a text file:

#Menu 1 file
Jelly Fish Yee Sang with Pear
Dried Seafood with Fish Soup
Steamed Sea Water Grouper

and I have this code:

menuList = input('enter number:')
def printPackage(menuList):
    if menuList == '1':
        with open('menu/Menu1.txt')as f:
            data = f.read()
            print(data)
printPackage(menuList)

What should I add to my code so that I have my text file to print like this?

---------
Menu List
---------
1. Jelly Fish Yee Sang with Pear
2. Dried Seafood with Fish Soup
3. Steamed Sea Water Grouper

Help please.


问:
Simple: what's the CSS selector for this item?
sorry for this trivial question, but i just don't get it. I would like to set the witdh of this image:

```<code><img class='icon weather/mostlycloudy'
src="/fhem/images/default/weather/mostlycloudy.png" alt="mostlycloudy"
title="mostlycloudy">
</code>```

I've tried things like

```<code>[class~="weather"] {
    witdh:50px;
}

.img.icon {
    witdh:50px;
}
</code>```

and everything I could imagine, but the width attribute never appears if I check it with chromes inspect tool. I'm sure that I edit the correct .css file, because I can see the influence for other elements of that page. I surely am no html or css expert and maybe a bit dumb... Could you please help me?

答:
There are 2 errors in your code.

First, the selector. img is an HTML element and therefore should not be prefixed with a . as it was a class name. (unless you're having a class named img).

```<code>.img.icon {
</code>```

Should be:

```<code>img.icon {
</code>```

Second, you wrote witdh instead of width. You've should notice that in the inspector this property has been marked with a ! as there's a mistake.

```<code>img.icon {
    width:50px; //not wi**td**h
}
</code>```

https://jsfiddle.net/zmztezc2/

Body:
sorry for this trivial question, but i just don't get it. I would like to set the witdh of this image:

I've tried things like

[class~="weather"] {
    witdh:50px;
}

.img.icon {
    witdh:50px;
}

and everything I could imagine, but the width attribute never appears if I check it with chromes inspect tool. I'm sure that I edit the correct .css file, because I can see the influence for other elements of that page. I surely am no html or css expert and maybe a bit dumb... Could you please help me?

Body:
There are 2 errors in your code.

First, the selector. img is an HTML element and therefore should not be prefixed with a . as it was a class name. (unless you're having a class named img).

.img.icon {

Should be:

img.icon {

Second, you wrote witdh instead of width. You've should notice that in the inspector this property has been marked with a ! as there's a mistake.

img.icon {
    width:50px; //not wi**td**h
}

https://jsfiddle.net/zmztezc2/


问:
How to add UICollectionView inside UIAlertViewController?
There are similar question on stackoverflow How to add UITableView in a UIAlertView in swift and How to add a UITableView inside the UIAlertView in iPhone? but I am adding UICollectionView inside UIAlertViewController and I am getting crash

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UICollectionView view]: unrecognized selector sent to instance 0x103808200'

I am using below Code

```<code>class NewProjectViewController: UIViewController {
    var iconCollectionView:UICollectionView!
    @IBAction func projectIconAction(_ sender: UIButton) {
        selectIcon()
    }
}

extension NewProjectViewController:UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout
{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return Constant.iconArray.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell:UICollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath as IndexPath)

        cell.backgroundColor = UIColor.blue
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
    {
        return CGSize(width: 50, height: 50)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets
    {
        return UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
    }

    func selectIcon() {

        let flowLayout = UICollectionViewFlowLayout()
        iconCollectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: flowLayout)
        iconCollectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "Cell")
        iconCollectionView.delegate = self
        iconCollectionView.dataSource = self

        let alertController:UIAlertController = UIAlertController(title: "ICON", message: "", preferredStyle: UIAlertControllerStyle.alert)
        alertController.addAction(UIAlertAction(title: "Select", style: UIAlertActionStyle.default, handler: { (action) in
            print("Icon Selected")
        }))
        alertController.setValue(iconCollectionView, forKey: "contentViewController")
        alertController.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.destructive, handler: nil))
        self.present(alertController, animated: true, completion: nil)
    }

}
</code>```

Please let me know what I am doing wrong here

Edit 1:
If I am using bellow code to add UICollectionViewController as subview to UIAlertController then I got out as in screenshot

```<code>func selectIcon() {

        let flowLayout = UICollectionViewFlowLayout()
        iconCollectionView = UICollectionView(frame: CGRect(x: 0, y: 80, width: 300, height: 300), collectionViewLayout: flowLayout)
        iconCollectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "Cell")
        iconCollectionView.delegate = self
        iconCollectionView.dataSource = self

        let alertController:UIAlertController = UIAlertController(title: "ICON", message: "", preferredStyle: UIAlertControllerStyle.alert)
        alertController.addAction(UIAlertAction(title: "Select", style: UIAlertActionStyle.default, handler: { (action) in
            print("Icon Selected")
        }))
//        alertController.setValue(iconCollectionView, forKey: "contentViewController")
        alertController.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.destructive, handler: nil))
        alertController.view.addSubview(iconCollectionView)
        self.present(alertController, animated: true, completion: nil)
    }
</code>```

答:
Unfortunately such a thing is not possible with the Apple UIAlertController. As the answers to the question you linked suggest, you need to create a custom view to do this.

You can do this yourself, (refer to the other answer), or alternatively, many libraries exist that you can use.

I have personally used this one before and had great success with it.

Good luck!

Body:
There are similar question on stackoverflow How to add UITableView in a UIAlertView in swift and How to add a UITableView inside the UIAlertView in iPhone? but I am adding UICollectionView inside UIAlertViewController and I am getting crash

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UICollectionView view]: unrecognized selector sent to instance 0x103808200'

I am using below Code

class NewProjectViewController: UIViewController {
    var iconCollectionView:UICollectionView!
    @IBAction func projectIconAction(_ sender: UIButton) {
        selectIcon()
    }
}

extension NewProjectViewController:UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout
{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return Constant.iconArray.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell:UICollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath as IndexPath)

        cell.backgroundColor = UIColor.blue
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
    {
        return CGSize(width: 50, height: 50)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets
    {
        return UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
    }

    func selectIcon() {

        let flowLayout = UICollectionViewFlowLayout()
        iconCollectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: flowLayout)
        iconCollectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "Cell")
        iconCollectionView.delegate = self
        iconCollectionView.dataSource = self

        let alertController:UIAlertController = UIAlertController(title: "ICON", message: "", preferredStyle: UIAlertControllerStyle.alert)
        alertController.addAction(UIAlertAction(title: "Select", style: UIAlertActionStyle.default, handler: { (action) in
            print("Icon Selected")
        }))
        alertController.setValue(iconCollectionView, forKey: "contentViewController")
        alertController.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.destructive, handler: nil))
        self.present(alertController, animated: true, completion: nil)
    }

}

Please let me know what I am doing wrong here

Edit 1:
If I am using bellow code to add UICollectionViewController as subview to UIAlertController then I got out as in screenshot

func selectIcon() {

        let flowLayout = UICollectionViewFlowLayout()
        iconCollectionView = UICollectionView(frame: CGRect(x: 0, y: 80, width: 300, height: 300), collectionViewLayout: flowLayout)
        iconCollectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "Cell")
        iconCollectionView.delegate = self
        iconCollectionView.dataSource = self

        let alertController:UIAlertController = UIAlertController(title: "ICON", message: "", preferredStyle: UIAlertControllerStyle.alert)
        alertController.addAction(UIAlertAction(title: "Select", style: UIAlertActionStyle.default, handler: { (action) in
            print("Icon Selected")
        }))
//        alertController.setValue(iconCollectionView, forKey: "contentViewController")
        alertController.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.destructive, handler: nil))
        alertController.view.addSubview(iconCollectionView)
        self.present(alertController, animated: true, completion: nil)
    }


问:
Styling not applying to child component
I'm trying to apply styling to a child component tag, but I can't do that.

I have child component with anchor tag.

Even though i have styling for anchor tag in the parent component, it's not applying. What's the solution for it?

Working code: http://plnkr.co/edit/CJCpV4ZbG7hdxT2AeSmt?p=preview

```<code> <a href="https://www.google.com">Google</a>
</code>```

In the parent component i'm using the child component and applying styling for this child component.

Html code:

```<code><div class="container">
  <div class="test">
    <testapp></testapp>
  </div>
</div>
</code>```

Css code:

```<code>.container{
  font-family:sans-serif;
  font-size:18px;
  border: 1px solid black;
}
.test{
  width:50%;
  background-color:#f0f5f5;
}

.container:hover .test{
  background-color:#e6ffe6;
}
.container:hover .test:hover{
  background-color:#ffffe6;
}
.container .test a {
    color:   red ;
}
.container .test a:hover {
    color:green;
}
</code>```

答:
EDITED: This should solve:

In the css of child class write below code

```<code>:host.parentclass childclass{

}
</code>```

The parentclass is immediate parent of child. childclass is the class applied to child component.

ContentLicense: CC BY-SA 4.0

Title: Styling not applying to child component

Body:
I'm trying to apply styling to a child component tag, but I can't do that.

I have child component with anchor tag.

Even though i have styling for anchor tag in the parent component, it's not applying. What's the solution for it?

Working code: http://plnkr.co/edit/CJCpV4ZbG7hdxT2AeSmt?p=preview

 Google

In the parent component i'm using the child component and applying styling for this child component.

Html code:

    <testapp></testapp>

Css code:

.container{
  font-family:sans-serif;
  font-size:18px;
  border: 1px solid black;
}
.test{
  width:50%;
  background-color:#f0f5f5;
}

.container:hover .test{
  background-color:#e6ffe6;
}
.container:hover .test:hover{
  background-color:#ffffe6;
}
.container .test a {
    color:   red ;
}
.container .test a:hover {
    color:green;
}

Body:
EDITED: This should solve:

In the css of child class write below code

:host.parentclass childclass{

}

The parentclass is immediate parent of child. childclass is the class applied to child component.


问:
How to use tilde in css correctly in structure?
I have the following issue.

In a demo part I have the code below:

Standard size

Big size

Very big size

```

When you move the mouse cursor over one of the text paragraphs an image should appear. That will work if I replace the paragraphs above the code with the images.

But when I put in the structure like I showed above it doesn't work.

I tried to find answer online why it doesn't work... I post my question here because I didn't fine a clear answer.

答:
The tilde ~ targets siblings which follow in the HTML markup order...

A ~ B = target B if and only if it follows A

To employ this feature of CSS in your example use something like this in your stylesheet...

```<code>/* hide all divs with a class
   which begins with 'manImg' */
div[class^=manImg] {
    display:none;
}

/* show div when p.prijs* element hovered */
p.prijsa:hover ~ div.manImgA,
p.prijsb:hover ~ div.manImgB,
p.prijsc:hover ~ div.manImgC {
    display:block;
}
</code>```

Hope that helped. :)

Body:
I have the following issue.

In a demo part I have the code below:

Standard size

Big size

Very big size

When you move the mouse cursor over one of the text paragraphs an image should appear. That will work if I replace the paragraphs above the code with the images.

But when I put in the structure like I showed above it doesn't work.

I tried to find answer online why it doesn't work... I post my question here because I didn't fine a clear answer.

Body:
The tilde ~ targets siblings which follow in the HTML markup order...

A ~ B = target B if and only if it follows A

To employ this feature of CSS in your example use something like this in your stylesheet...

/* hide all divs with a class
   which begins with 'manImg' */
div[class^=manImg] {
    display:none;
}

/* show div when p.prijs* element hovered */
p.prijsa:hover ~ div.manImgA,
p.prijsb:hover ~ div.manImgB,
p.prijsc:hover ~ div.manImgC {
    display:block;
}

Hope that helped. :)


问:
NumericUpDown backcolor not working as expected
I recently had the need to write a version of the Windows NumericUpDown control which could highlight whether a value was mandatory. It needed to do this by changing the back colour of the control. I thought this would be simple enough, but in trying to do so, I find that it has a wierd side-effect of not quite drawing all the control.

Using the code below, I am seeing this:

When I drop a control on a Windows form, and change the BackColor property (ie. to Blue), the whole of the control's number part changes colour. If, alternatively, I change my "IsMandatory" property, not quite all of the back colour changes (it leaves a border). So, if I change the BackColor to Blue, and then set IsMandatory to True, I get a LightBlue control (the mandatory colour) with a Blue border.

I cannot see why that should be, given that they both use the same code.

Ideas or explanations greatfully received.

```<code>   public partial class MyNumericUpDown : NumericUpDown
   {
      private Boolean _isMandatory = false;
      private Color _mandatoryBackColor = Color.LightBlue;
      private Color _backColor = Color.FromKnownColor(KnownColor.Window);

      [DefaultValue(typeof(Color), "Window"), Description("Overridden property")]
      override public Color BackColor
      {
         get { return _backColor; }
         set
         {
            _backColor = value;
            MyResetColors();
         }
      }

      [DefaultValue(typeof(Color), "LightBlue"), Category("Appearance")]
      public Color MandatoryBackColor
      {
         get {return _mandatoryBackColor;}
         set
         {
            _mandatoryBackColor = value;
            MyResetColors();
         }
      }

      [DefaultValue(false), Category("Behavior")]
      public Boolean IsMandatory
      {
         get { return _isMandatory; }
         set
         {
            _isMandatory = value;
            MyResetColors();
         }
      }

      private void MyResetColors()
      {
         base.BackColor = (this.IsMandatory ? this.MandatoryBackColor : this.BackColor);
      }
   }
</code>```

答:
Windows does not properly/completely repaint the NumericUpDown control when it is disabled.

See this post:  NumericUpDown background colour change for disabled element

Enabling / disabling the control after it is displayed is a work-around.

Body:
I recently had the need to write a version of the Windows NumericUpDown control which could highlight whether a value was mandatory. It needed to do this by changing the back colour of the control. I thought this would be simple enough, but in trying to do so, I find that it has a wierd side-effect of not quite drawing all the control.

Using the code below, I am seeing this:

When I drop a control on a Windows form, and change the BackColor property (ie. to Blue), the whole of the control's number part changes colour. If, alternatively, I change my "IsMandatory" property, not quite all of the back colour changes (it leaves a border). So, if I change the BackColor to Blue, and then set IsMandatory to True, I get a LightBlue control (the mandatory colour) with a Blue border.

I cannot see why that should be, given that they both use the same code.

Ideas or explanations greatfully received.

   public partial class MyNumericUpDown : NumericUpDown
   {
      private Boolean _isMandatory = false;
      private Color _mandatoryBackColor = Color.LightBlue;
      private Color _backColor = Color.FromKnownColor(KnownColor.Window);

      [DefaultValue(typeof(Color), "Window"), Description("Overridden property")]
      override public Color BackColor
      {
         get { return _backColor; }
         set
         {
            _backColor = value;
            MyResetColors();
         }
      }

      [DefaultValue(typeof(Color), "LightBlue"), Category("Appearance")]
      public Color MandatoryBackColor
      {
         get {return _mandatoryBackColor;}
         set
         {
            _mandatoryBackColor = value;
            MyResetColors();
         }
      }

      [DefaultValue(false), Category("Behavior")]
      public Boolean IsMandatory
      {
         get { return _isMandatory; }
         set
         {
            _isMandatory = value;
            MyResetColors();
         }
      }

      private void MyResetColors()
      {
         base.BackColor = (this.IsMandatory ? this.MandatoryBackColor : this.BackColor);
      }
   }


问:
select department(s) with maximum number of employees
I have two tables EMP(id,name,DEPT_id) and DEPT(id ,name). I need to find the department(s) in which the maximum number of employees work. Please help.

答:
```<code>SELECT department_id, count(employee_id) as 'No_of_Emp'
    FROM employees
    GROUP BY department_id
    ORDER BY No_of_Emp DESC
</code>```


问:
Should pdb and ipdb be installed by Anaconda on Windows?
I installed Anaconda (python 3) on a Windows 10 machine. Whilst import pdb works inside a script I cant use pdb

Body:
Problem

pdb package comes with Anaconda 3's Python installation, so when you run import pdb in the command line it successfully loads it.

Running pdb <script> from command line makes Windows look for a pdb.exe executable in any of the paths listed in your PATH environment variable.

As far as I know, pdb does not come with a script executable. ipdb does.

Solution

PDB:

Run python -m pdb myscript.py from an Anaconda terminal.

IPDB:

Install the ipdb package in your Anaconda Python environment.

Try running your script in the command line with ipdb <script>.

If the second step does not work for you, this is probably because the anaconda script folder does not appear in your PATH environment variable.

Press winkey

Search for Edit the system environment variables

Click on environment variables....

Look for a PATH variable in either your user or system variables. (If it doesn't exist, create a new variable).

Double click it and add a new path pointing to your anaconda Scripts folder (for me it's in %localappdata%\Continuum\anaconda3\Scripts).

And you're done.


问:
Angular 4 typed.js is not a constructor issue
I am trying to build my new portfolio with Angular 4 but came across few issues.
I first built it with normal html,css and js and worked fine.

I am using typed.js to create an animation at the beginning.
This are the steps that I followed:

1 - in node_modules created folder typed within typed.min.js

2 - angular-cli.json under scripts section "../node_modules/typed/typed.min.js"

3 - in typed component i imported as: import * as typed from
'../../../../node_modules/typed/typed.min.js'; (apparently not working today and the terminal is saying this ERROR in src/app/components/loading-section/loading-section.component.ts(2,24): error TS6143: Module '../../../../node_modules/typed/typed.min.js' was resolved to '/Users/matteosoresini/Development/Portfolio2017/node_modules/typed/typed.min.js', but '--allowJs' is not set. so if i change the path as the terminal says is working but doesn't really make sense but this is not the main issue.

4 - in ngInit i tried to implement the JS function and when run the project the terminal says typed is not a constructor, even if i move the function inside a script within the typed.component.html

can you please help me with this and clarify where to import external plugin?
Thanks

答:
Types.js has no defined typescript types in DefinitelyTyped repo.
I not sure how it would behave with Angular since it does DOM changes outside angular. You can see and try https://github.com/kuflink/angular-typed but it is not production ready.</p>


答:
If you want only with pure css,you must change pure css:

.manImgA { display: none; }
.manImgB { display: none; }
.manImgC { display: none; }
.text:hover + div { display: block; }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p class="text prijsa">Standard size</p>
<div class="manImgA">
  <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQEnn9dYYZlciBKfaHCw17-dUgRPX3nq5_6-kV1ua-LIsId5g43uA">
</div>

<p class="text prijsb">Big size</p>
<div class="manImgB">
  <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRDAYrQr9qgT2W00EV_CoCahFki3Vw4lSMNt81k9FCSTXoKT8TY2w">
</div>

<p class="text prijsc">Very big size</p>
<div class="manImgC">
  <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSeY54SaYkaOxxyXlu_ng21EMIBZvJjnZBNQAOsIh_0_6Tvu9et">
</div></code>```

Title: How to use tilde in css correctly in structure?

Body:
If you want only with pure css,you must change pure css:

.manImgA { display: none; }
.manImgB { display: none; }
.manImgC { display: none; }
.text:hover + div { display: block; }

<p class="text prijsa">Standard size</p>
<div class="manImgA">
  <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQEnn9dYYZlciBKfaHCw17-dUgRPX3nq5_6-kV1ua-LIsId5g43uA">
</div>

<p class="text prijsb">Big size</p>
<div class="manImgB">
  <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRDAYrQr9qgT2W00EV_CoCahFki3Vw4lSMNt81k9FCSTXoKT8TY2w">
</div>

<p class="text prijsc">Very big size</p>
<div class="manImgC">
  <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSeY54SaYkaOxxyXlu_ng21EMIBZvJjnZBNQAOsIh_0_6Tvu9et">
</div>


问:
Displaying a value in a populated combo box
Here is the situation:
I have populated a combo box with the names of divisions in my company and it is working fine. I go into edit mode and pull one record out of the data table so I bind all controls on the form with one record. I also populate this combo box with all divisions but want it to display the selected division. While I know how to display correct date in textbox controls, I do not know how to make combo box display only selected data. It displays the first record from the query which populates it. Any suggestions?

Thanks

答:
Not clear if you are using ASP.NET or Windows Form.  I am assuming Windows Form at the moment since it has an actual ComboBox control, while ASP.NET only has DropDownList (not counting the AJAX Control Toolkit).

ComboBox has a bunch of Selected... properties, i.e. SelectedIndex, SelectedItem, SelectedValue, SelectedText that you can manipulate (set) to show a certain item on the screen.  So you can just do cbDivision.SelectedText = myRecord.Division (assuming Division in myRecord contains the same name as the one bound in the ComboBox.

for reference, see: this

ContentLicense: CC BY-SA 2.5


问:
Is there a fast parallel "for" loop in Perl 6?
Given some code which does a bit of math/casting for each number from 1 to 500000, we have options:

Simple for loop: for ^500000 -> $i { my $result = ($i ** 2).Str; }. In my unscientific benchmark, this takes 2.8 seconds.

The most canonical parallel version does each bit of work in a Promise, then waits for the result. await do for ^500000 -> $i { start { my $result = ($i ** 2).Str; } } takes 19 seconds. This is slow! Creating a new promise must have too much overhead to be worthwhile for such a simple computation.

Using a parallel map operation is fairly fast. At 2.0 seconds, the operation seems barely slow enough to take advantage of parallelization: (^500000).race.map: -> $i { my $result = ($i ** 2).Str; }

The third option seems best. Unfortunately, it reads like a hack. We should not be writing map code for iteration in sink context, because others that read "map" in the source may assume the purpose is to build a list, which isn't our intent at all. It's poor communication to use map this way.

Is there any canonical fast way to use Perl 6's built in concurrency? A hyper operator would be perfect if it could accept a block instead of only functions:

```<code>(^500000)».(-> $i { my $result = ($i ** 2).Str; }) # No such method 'CALL-ME' for invocant of type 'Int'
</code>```

答:
If you want to use for with a hyper or race operation, you have to spell it hyper for @blah.hyper(:batch(10_000)) or race for @blah.race(:batch(10_000)). Or without parameters: hyper for @blah, race for @blah.

This was decided because you might have code like for some-operation() { some-non-threadsafe-code } where some-operation is part of a library or something. Now you cannot tell any more if the for loop can have thread-unsafe code in it or not, and even if you know the library doesn't return a HyperSeq at that point in time, what if the library author comes up with this great idea to make some-operation faster by hypering it?

That's why a signifier for "it's safe to run this for loop in parallel" is required right where the code is, not only where the sequence gets created.

Body:
Given some code which does a bit of math/casting for each number from 1 to 500000, we have options:

Simple for loop: for ^500000 -> $i { my $result = ($i ** 2).Str; }. In my unscientific benchmark, this takes 2.8 seconds.

The most canonical parallel version does each bit of work in a Promise, then waits for the result. await do for ^500000 -> $i { start { my $result = ($i ** 2).Str; } } takes 19 seconds. This is slow! Creating a new promise must have too much overhead to be worthwhile for such a simple computation.

Using a parallel map operation is fairly fast. At 2.0 seconds, the operation seems barely slow enough to take advantage of parallelization: (^500000).race.map: -> $i { my $result = ($i ** 2).Str; }

The third option seems best. Unfortunately, it reads like a hack. We should not be writing map code for iteration in sink context, because others that read "map" in the source may assume the purpose is to build a list, which isn't our intent at all. It's poor communication to use map this way.

Is there any canonical fast way to use Perl 6's built in concurrency? A hyper operator would be perfect if it could accept a block instead of only functions:

(^500000)».(-> $i { my $result = ($i ** 2).Str; }) # No such method 'CALL-ME' for invocant of type 'Int'


问:
C# - How to Italicise a words within a string resource
I'm writing a WPF application and I need to italicise words within descriptions on my view while still having them within resources to provide multi-lingual support later on. These descriptions are resourced and pass through a director that matches the descriptions in the view model by their code to their appropriate placement.

What I have tried:

I've begun resourcing the words of importance separately and added placeholder codes within the description resources. I then wanted to insert the words of importance into the description strings as they pass through the director but I can't italicise them at this stage either as they're just strings! How can i do achieve this?

答:
This is typically a case where you are intertwining your data with the view of your data. You should keep them separated, as Model-View-Controller (MVC) advises.

You have some data that consists of two parts:

your description

the texts within your description that needs to be emphasized

This data can be displayed on several ways. One way - the method you want - is to display the complete description while the texts that need to be emphasized must be shown in italics.

But one could also think of a viewing method where the emphasized words are shown in bold fond, or a different font, or in red, or upside down.

By separating your data from the way you view your data, it is possible to change this view without having to change the data itself

Now back to your question. So you have some text, and some subtext that need to be emphasized. How you know which text needs to be emphasized is out of scope of your question. How you put this information inside this class is also out-of-scope of this question. All you need is some translate function that will translate your text into a format that allows interpreters of the translated text to know the complete text, and which phrases must be emphasized.

How to mark where the emphasize starts and where it stops is not really important, just use some well-defined method.

For instance, you could use the HTML method for emphasis:

```<code>Some normal text <em>is emphasized</em> and normal again
</code>```

If you want, you could use any other method, like adding double forward slashes to switch emphasizing on or off, or anything else. It doesn't matter, as long as it is well defined.

So the class that holds your text and your emphasized needs a procedure to extract the translated text

```<code>public string ExtractTranslatedText()
{
    // TODO: take your original text and add <em> and </em>
    // to mark begin and end of emphasis
}
</code>```

It seems that you almost succeeded creating this function.

Now once you've got a string that holds this emphases, you need to display it. It depends on your display class how this can be done.

Suppose you want to display it italicized in a RichTextBox. You could derive your class from RichTextBox, or you could create an extension function for RichTextBox.

See Extension Methods Demystified

```<code>public static class RichTestBoxExtensions
{
    // TODO: add the required functions
}
</code>```

We need a function that will append some text to the already existing text in the text box in a given System.Drawing.FontStyle:

```<code>public static void AppendText(this RichTextBox box, string text, FontStyle fontStyle)
{
    box.SelectionStart = box.TextLength;
    box.SelectionLength = 0;

    Font savedSelectionFont = box.SelectionFont;
    box.SelectionFont = new Font(box.SelectionFont, fontStyle);
    box.AppendText(text);
    box.SelectionFont = savedSelectionFont;
}
</code>```

If you want, you could also add methods to show the text in a different color.
The code will be very similar.

Now you need to put your translated string with emphasis markers in the rich text box

```<code>public static ShowEmphasis(this RichTextBox, string text, FontStyle emphasisStyle)
{
    const string emphasisOn = "<em>";
    const string emphasisOff = "</em>";

    while(!String.IsNullOrEmpty(text))
    {   // still some text to print
        // get the substring until first emphasisOn
        int indexStartEmphasis = text.Index(emphasisOn);

        if (indexStartEmphasis == -1)
        {   // no emphasisOn anymore: write all in emphasisStyle
            richTextBox.AppendText(text, emphasisStyle);
            text = String.Empty; // no text left
        }
        else
        {   // write until emphasisOn:
            string normalText = text.SubString(0, indexStartEmphasis);
            richTextBox.AppendText(normalText, FontStyle.Normal);

            // remove the normalText + <em> from text:
            text = text.Substring(indexStartEmphasis + emphasisOn.Length);

            // do the same until emphasisOff
            int indexStopEmphasis = text.Index(emphasisOff);
            if (indexStopEmphasis == -1)
            {   // no emphasisOff anymore: write all in emphasisStyle
                richTextBox.AppendText(text, FontStyle.Normal);
                text = String.Empty; // no text left
            }
            else
            {   // write until emphasisOff in emphasisStyle:
                string emphasizedText = text.SubString(0, indexStopEmphasis);
                richTextBox.AppendText(emphasizedText, emphasisStyle);

                // remove the emphasizedlText + </em> from text:
                text = text.Substring(indexStopEmphasis + emphasisOff.Length);
            }
        }
    }
}
</code>```

Body:
This is typically a case where you are intertwining your data with the view of your data. You should keep them separated, as Model-View-Controller (MVC) advises.

You have some data that consists of two parts:

your description

the texts within your description that needs to be emphasized

This data can be displayed on several ways. One way - the method you want - is to display the complete description while the texts that need to be emphasized must be shown in italics.

But one could also think of a viewing method where the emphasized words are shown in bold fond, or a different font, or in red, or upside down.

By separating your data from the way you view your data, it is possible to change this view without having to change the data itself

Now back to your question. So you have some text, and some subtext that need to be emphasized. How you know which text needs to be emphasized is out of scope of your question. How you put this information inside this class is also out-of-scope of this question. All you need is some translate function that will translate your text into a format that allows interpreters of the translated text to know the complete text, and which phrases must be emphasized.

How to mark where the emphasize starts and where it stops is not really important, just use some well-defined method.

For instance, you could use the HTML method for emphasis:

Some normal text <em>is emphasized</em> and normal again

If you want, you could use any other method, like adding double forward slashes to switch emphasizing on or off, or anything else. It doesn't matter, as long as it is well defined.

So the class that holds your text and your emphasized needs a procedure to extract the translated text

public string ExtractTranslatedText()
{
    // TODO: take your original text and add <em> and </em>
    // to mark begin and end of emphasis
}

It seems that you almost succeeded creating this function.

Now once you've got a string that holds this emphases, you need to display it. It depends on your display class how this can be done.

Suppose you want to display it italicized in a RichTextBox. You could derive your class from RichTextBox, or you could create an extension function for RichTextBox.

See Extension Methods Demystified

public static class RichTestBoxExtensions
{
    // TODO: add the required functions
}

We need a function that will append some text to the already existing text in the text box in a given System.Drawing.FontStyle:

public static void AppendText(this RichTextBox box, string text, FontStyle fontStyle)
{
    box.SelectionStart = box.TextLength;
    box.SelectionLength = 0;

    Font savedSelectionFont = box.SelectionFont;
    box.SelectionFont = new Font(box.SelectionFont, fontStyle);
    box.AppendText(text);
    box.SelectionFont = savedSelectionFont;
}

If you want, you could also add methods to show the text in a different color.
The code will be very similar.

Now you need to put your translated string with emphasis markers in the rich text box

public static ShowEmphasis(this RichTextBox, string text, FontStyle emphasisStyle)
{
    const string emphasisOn = "<em>";
    const string emphasisOff = "</em>";

    while(!String.IsNullOrEmpty(text))
    {   // still some text to print
        // get the substring until first emphasisOn
        int indexStartEmphasis = text.Index(emphasisOn);

        if (indexStartEmphasis == -1)
        {   // no emphasisOn anymore: write all in emphasisStyle
            richTextBox.AppendText(text, emphasisStyle);
            text = String.Empty; // no text left
        }
        else
        {   // write until emphasisOn:
            string normalText = text.SubString(0, indexStartEmphasis);
            richTextBox.AppendText(normalText, FontStyle.Normal);

            // remove the normalText + <em> from text:
            text = text.Substring(indexStartEmphasis + emphasisOn.Length);

            // do the same until emphasisOff
            int indexStopEmphasis = text.Index(emphasisOff);
            if (indexStopEmphasis == -1)
            {   // no emphasisOff anymore: write all in emphasisStyle
                richTextBox.AppendText(text, FontStyle.Normal);
                text = String.Empty; // no text left
            }
            else
            {   // write until emphasisOff in emphasisStyle:
                string emphasizedText = text.SubString(0, indexStopEmphasis);
                richTextBox.AppendText(emphasizedText, emphasisStyle);

                // remove the emphasizedlText + </em> from text:
                text = text.Substring(indexStopEmphasis + emphasisOff.Length);
            }
        }
    }
}


问:
Don’t mock value objects: too generic rule without explanation
Here is a quote from Mockito unit testing framework:

Don't mock value objects

Why one would even want to do that?

Because instantiating the object is too painful !? => not a valid
  reason. If it's too difficult to create new fixtures, it is a sign the
  code may need some serious refactoring. An alternative is to create
  builders for your value objects -- there are tools for that, including
  IDE plugins, Lombok, and others. One can also create meaningful
  factory methods in the test classpath.

And another quote from here:

There isn't much point in writing mocks for simple value objects
  (which should be immutable anyway), just create an instance and use
  it.  It's not worth creating an interface / implementation pair to control which time values are returned, just create instances with the appropriate values and use them. There are a couple of heuristics for when a class is not worth mocking. First, it has only accessors or simple methods that act on values it holds, it doesn't have any interesting behaviour. Second, you can't think of a meaningful name for the class other than VideoImpl or some such vague term.

This seems to be a valid reason for dumb value objects holding just the values and nothing more, but things getting more complicated when you have a ValueObject referencing the entities and other value objects.

Let's say I have Person and Pet objects which are entities and Relationship (owner, doctor, etc) which is a ValueObject between two persons and has a RelationshipType which is also a Value Object. So, relationship is basically:

```<code>class Relationship {
    private Person person;
    private Pet pet;
    private RelationshipType type;
}
</code>```

Now, let's say I have a class with the predicate like isOwnerRelationship, isDoctorRelationship, whatever. Basically predicate is as simple as

relationship -> relationship.isOwner(); //delegates to relationshipType.isOwner()

Now, I want to test the predicates and I have two options:

Mock Relationship

```<code>public void testIsOwner() {
   Relationship rel = mock(Relationship.class);
   when(rel.isOwner()).thenReturn(true);

   assertTrue(RelationshipPredicates.isOwner(rel));
}
</code>```

Don't mock Relationship

```<code>public void testIsOwner() {
   Person person = PersonBuilder.newPerson();
   Pet pet = PetBuilder.newDogPet();
   RelationshipType type = RelationshipTypes.ownerType();

   Relationship rel = new Relationship(person, pet, type);

   assertTrue(RelationshipPredicates.isOwner(rel));
}
</code>```

Of course the example is over simplified because for a person you may be required to provide address, for Pet you may have to provide BreedType, whatever, i.e. transitive graph of entities and value objects you may need to provide can be very huge. Of course you can mock Entities, but assume you have more ValueObjects of ValueObjects inside of Relationship. Even if you have fancy builders, you will have to provide each and every part of the original ValueObject even though unit test is going to test only single aspect of it.

In the predicates test, why should I care about full object construction if the predicate cares about calling one particular method of the object or combination of them?

Or is such value object can't be considered as a simple and rule doesn't apply?

答:
In the predicates test, why should I care about full object construction if the predicate cares about calling one particular method of the object or combination of them?

If the predicate only cares about calling one particular method, then why are you passing an entire value to it?

In test driven design, one of the key ideas is that writing the test is feedback about the API that you are creating; if you are finding that API to be clumsy to test, it's a hint that the API may also be clumsy to use.

In this specific case, the test is trying to tell you that your current design violates the interface segregation principle

No client should be forced to depend on methods it does not use.

All the predicate cares about is a description of ownership, so maybe that idea should be expressed explicitly in your solution

```<code>interface DescribesOwnership {
    boolean isOwner();
}

class Relationship implements DescribesOwnership {
    @Override
    boolean isOwner() {
        return this.type.isOwner();
    }
}
</code>```

That's one possible answer.  Another is that the code is trying to tell you that the API for constructing a Relationship needs some work.  You're heading that direction with your Builder proposal, but again... listen to the test.

It's trying to tell you that you want:

```<code>Relationship rel = Relationship.builder()
                   .using(RelationshipTypes.ownerType())
                   .build();
</code>```

In other words, this test doesn't care at all what values are used for Owner or Pet; it doesn't even care that those things exist.  Maybe that's going to be true elsewhere as well.

Notice that you still get the clean test that you have in your mock example

```<code>public void testIsOwner() {
    Relationship rel = Relationship.builder()
                   .using(RelationshipTypes.ownerType())
                   .build();

    assertTrue(RelationshipPredicates.isOwner(rel));
}
</code>```

Don't like the Builder idiom?  that's fine; just notice that all we are really doing is creating a mapping between an instance of RelationshipTypes and an instance of Relationship.  In other words, you are just looking for a function.

```<code>public void testIsOwner() {
    // foo: RelationshipTypes -> Relationship
    Relationship rel = foo(RelationshipTypes.ownerType());

    assertTrue(RelationshipPredicates.isOwner(rel));
}
</code>```

And you can use whichever spelling of foo is consistent with your local coding style.

In summary

Don't mock value objects

seems like really good advice -- it's a heuristic to remind you that creating a mock for a value object is solving the wrong problem.

Body:
Here is a quote from Mockito unit testing framework:

Don't mock value objects

Why one would even want to do that?

Because instantiating the object is too painful !? => not a valid
  reason. If it's too difficult to create new fixtures, it is a sign the
  code may need some serious refactoring. An alternative is to create
  builders for your value objects -- there are tools for that, including
  IDE plugins, Lombok, and others. One can also create meaningful
  factory methods in the test classpath.

And another quote from here:

There isn't much point in writing mocks for simple value objects
  (which should be immutable anyway), just create an instance and use
  it.  It's not worth creating an interface / implementation pair to control which time values are returned, just create instances with the appropriate values and use them. There are a couple of heuristics for when a class is not worth mocking. First, it has only accessors or simple methods that act on values it holds, it doesn't have any interesting behaviour. Second, you can't think of a meaningful name for the class other than VideoImpl or some such vague term.

This seems to be a valid reason for dumb value objects holding just the values and nothing more, but things getting more complicated when you have a ValueObject referencing the entities and other value objects.

Let's say I have Person and Pet objects which are entities and Relationship (owner, doctor, etc) which is a ValueObject between two persons and has a RelationshipType which is also a Value Object. So, relationship is basically:

class Relationship {
    private Person person;
    private Pet pet;
    private RelationshipType type;
}

Now, let's say I have a class with the predicate like isOwnerRelationship, isDoctorRelationship, whatever. Basically predicate is as simple as

relationship -> relationship.isOwner(); //delegates to relationshipType.isOwner()

Now, I want to test the predicates and I have two options:

Mock Relationship

public void testIsOwner() {
   Relationship rel = mock(Relationship.class);
   when(rel.isOwner()).thenReturn(true);

   assertTrue(RelationshipPredicates.isOwner(rel));
}

Don't mock Relationship

public void testIsOwner() {
   Person person = PersonBuilder.newPerson();
   Pet pet = PetBuilder.newDogPet();
   RelationshipType type = RelationshipTypes.ownerType();

   Relationship rel = new Relationship(person, pet, type);

   assertTrue(RelationshipPredicates.isOwner(rel));
}

Of course the example is over simplified because for a person you may be required to provide address, for Pet you may have to provide BreedType, whatever, i.e. transitive graph of entities and value objects you may need to provide can be very huge. Of course you can mock Entities, but assume you have more ValueObjects of ValueObjects inside of Relationship. Even if you have fancy builders, you will have to provide each and every part of the original ValueObject even though unit test is going to test only single aspect of it.

In the predicates test, why should I care about full object construction if the predicate cares about calling one particular method of the object or combination of them?

Or is such value object can't be considered as a simple and rule doesn't apply?

Body:
In the predicates test, why should I care about full object construction if the predicate cares about calling one particular method of the object or combination of them?

If the predicate only cares about calling one particular method, then why are you passing an entire value to it?

In test driven design, one of the key ideas is that writing the test is feedback about the API that you are creating; if you are finding that API to be clumsy to test, it's a hint that the API may also be clumsy to use.

In this specific case, the test is trying to tell you that your current design violates the interface segregation principle

No client should be forced to depend on methods it does not use.

All the predicate cares about is a description of ownership, so maybe that idea should be expressed explicitly in your solution

interface DescribesOwnership {
    boolean isOwner();
}

class Relationship implements DescribesOwnership {
    @Override
    boolean isOwner() {
        return this.type.isOwner();
    }
}

That's one possible answer.  Another is that the code is trying to tell you that the API for constructing a Relationship needs some work.  You're heading that direction with your Builder proposal, but again... listen to the test.

It's trying to tell you that you want:

Relationship rel = Relationship.builder()
                   .using(RelationshipTypes.ownerType())
                   .build();

In other words, this test doesn't care at all what values are used for Owner or Pet; it doesn't even care that those things exist.  Maybe that's going to be true elsewhere as well.

Notice that you still get the clean test that you have in your mock example

public void testIsOwner() {
    Relationship rel = Relationship.builder()
                   .using(RelationshipTypes.ownerType())
                   .build();

    assertTrue(RelationshipPredicates.isOwner(rel));
}

Don't like the Builder idiom?  that's fine; just notice that all we are really doing is creating a mapping between an instance of RelationshipTypes and an instance of Relationship.  In other words, you are just looking for a function.

public void testIsOwner() {
    // foo: RelationshipTypes -> Relationship
    Relationship rel = foo(RelationshipTypes.ownerType());

    assertTrue(RelationshipPredicates.isOwner(rel));
}

And you can use whichever spelling of foo is consistent with your local coding style.

In summary

Don't mock value objects

seems like really good advice -- it's a heuristic to remind you that creating a mock for a value object is solving the wrong problem.


问:
Question about adding three variables C++
Hey so im making a program to figure out a energy cost my program so far is, but I want the watt-hours to be for all three appliances not just one how do i do that?:</p>

```<code>#include <iostream>
using namespace std;

int main ()
{
   double watts, hours_per_day, watt_hours, dollars_per_wh;

   dollars_per_wh= .00008;

   cout << " How many Watts for the Air conditioner? ";
   cin >> watts;
   cout << " How many hours/day do you run the Air Conditioner? ";
   cin >> hours_per_day;

   cout << "How many Watts for the Television? " ;
   cin >> watts;
   cout << "How many hours/day do you run the Television? " ;
   cin >> hours_per_day;

   cout << "How many Watts for the Washer? " ;
   cin >> watts;
   cout << "How many hours/day do you run the Washer? " ;
   cin >> hours_per_day;

   watt_hours = watts * hours_per_day * 30;
   cout << "You have used " << watt_hours << " Watts-Hours of electricity." << endl;
</code>```

答:
You will have to use a stand-alone watts variable and hours_per_day for each appliance.

Also consider using loops for doing such, it makes code more clearer and less sized;

```<code>#include <iostream>
#include <string>
#include <vector>

using std::cout;
using std::cin;
using std::endl;

static const double dollars_per_wh = 0.00008;

int main(int argc, char ** argv)
{
    int num_apps = 3;
    std::vector<std::string> v_apps;
    v_apps.push_back("Air conditioner");
    v_apps.push_back("Television");
    v_apps.push_back("Washer");

    double watt, hours, watt_hours = 0;
    for(register int i = 0; i < num_apps; ++i)
    {
        cout << "How many watts for the " << v_apps[i].c_str() << "? ";
        cin >> watt;
        cout << "How many hours/day do you run the " << v_apps[i].c_str() << "? ";
        cin >> hours;
        watt_hours = watt_hours + ((watt * hours) * 30);
    }
    cout << "You have used " << watt_hours << " Watt-Hours of electricity." << endl;
    return 0;
}
</code>```

Body:
Hey so im making a program to figure out a energy cost my program so far is, but I want the watt-hours to be for all three appliances not just one how do i do that?:

#include <iostream>
using namespace std;

int main ()
{
   double watts, hours_per_day, watt_hours, dollars_per_wh;

   dollars_per_wh= .00008;

   cout << " How many Watts for the Air conditioner? ";
   cin >> watts;
   cout << " How many hours/day do you run the Air Conditioner? ";
   cin >> hours_per_day;

   cout << "How many Watts for the Television? " ;
   cin >> watts;
   cout << "How many hours/day do you run the Television? " ;
   cin >> hours_per_day;

   cout << "How many Watts for the Washer? " ;
   cin >> watts;
   cout << "How many hours/day do you run the Washer? " ;
   cin >> hours_per_day;

   watt_hours = watts * hours_per_day * 30;
   cout << "You have used " << watt_hours << " Watts-Hours of electricity." << endl;

Body:
You will have to use a stand-alone watts variable and hours_per_day for each appliance.

Also consider using loops for doing such, it makes code more clearer and less sized;

#include <iostream>
#include <string>
#include <vector>

using std::cout;
using std::cin;
using std::endl;

static const double dollars_per_wh = 0.00008;

int main(int argc, char ** argv)
{
    int num_apps = 3;
    std::vector<std::string> v_apps;
    v_apps.push_back("Air conditioner");
    v_apps.push_back("Television");
    v_apps.push_back("Washer");

    double watt, hours, watt_hours = 0;
    for(register int i = 0; i < num_apps; ++i)
    {
        cout << "How many watts for the " << v_apps[i].c_str() << "? ";
        cin >> watt;
        cout << "How many hours/day do you run the " << v_apps[i].c_str() << "? ";
        cin >> hours;
        watt_hours = watt_hours + ((watt * hours) * 30);
    }
    cout << "You have used " << watt_hours << " Watt-Hours of electricity." << endl;
    return 0;
}


答:
img.icon (selecting the img element type) rather than .img.icon (which looks for a class containing img) should do the trick.

If you're looking to match any class starting with weather/, then I suggest [class*="weather/"].

Title: Simple: what's the CSS selector for this item?


问:
Is it possible to insert a column in a database table automatically using a variable in PHP?
I am trying to insert a column in a database table automatically using a variable.

I have a table named tbl_category, I want to let the user choose the sub category field by their own choice. So, from the dashboard, the user will insert 3/4 (or how many fields they would like to create) sub category fields.

I will take this value as $insert_sub_cat_count. So, when this info will hit the function named function save_category_info($data), the function will receive the value $insert_sub_cat_count as $data.

After that, this info have to implement in the table tbl_category and add 3/4 fields automatically according to the value $data.

If the user inputs 2, this will insert two columns automatically:

If the user inputs 3, this will insert 3 columns:

Is this possible? I don't know how to extend columns automatically or if there's any other way to do so.

答:
Insert is used to insert variables into an already existing column, you need to first create your column before filling it: </p>

```<code>ALTER TABLE `tbl_category` ADD `sub_category_one` VARCHAR(100) NOT NULL;
</code>```

Body:
Insert is used to insert variables into an already existing column, you need to first create your column before filling it:

ALTER TABLE `tbl_category` ADD `sub_category_one` VARCHAR(100) NOT NULL;


问:
can't initialize tomcat in Xampp
I'm trying to use xampp for a course but i can't make tomcat work correctly, the error i get is:

"Tomcat Started/Stopped with errors, return code: 1
Make sure you have Java JDK or JRE installed and the required ports are free
Check the "/xampp/tomcat/logs" folder for more information"

I've seeing many others with this problem but none of the advices they get helped me get rid of it.

i've already settled the enviroment variables like this:

CATALINA_HOME: C:\xampp\tomcat

CLASSPATH: C:\xampp\tomcat\lib\servlet-api.jar;C\xampp\tomcat\lib\jsp-api.jar

JAVA_HOME: C:\Program Files\Java\jdk-9

JRE_HOME: C:\Program Files\Java\jdk-9

path: C:\Program Files\Java\jdk-9\bin;C:\xampp\Tomcat\bin;C:\Program Files\Java\jre-9\bin

I've already set the port to 7070 (not sure if this is valid)

when i run CATALINA_START from cmd i got this:

```<code>C:\xampp\tomcat>catalina_start

[XAMPP]: Searching JDK HOME with reg query ...
'reg' is not recognized as an internal or external command, operable program or batch file.
'reg' is not recognized as an internal or external command, operable program or batch file.

[XAMPP]: Seems fine!
[XAMPP]: Set JAVA_HOME : C:\Program Files\Java\jdk-9
[XAMPP]: Set CATALINA_HOME : C:\xampp\tomcat

Using CATALINA_BASE:   "C:\xampp\tomcat"
Using CATALINA_HOME:   "C:\xampp\tomcat"
Using CATALINA_TMPDIR: "C:\xampp\tomcat\temp"
Using JRE_HOME:        "C:\Program Files\Java\jre-9"
Using CLASSPATH:       "C:\xampp\tomcat\bin\bootstrap.jar;C:\xampp\tomcat\bin\tomcat-juli.jar"
-Djava.endorsed.dirs=C:\xampp\tomcat\endorsed is not supported. Endorsed standards and standalone APIs
in modular form will be supported via the concept of upgradeable modules.
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.
</code>```

Apache and MySQL works just fine, but tomcat is giving headaches Does anyone know what can be wrong?

答: I uninstalled 1.9 and installed 1.8 and Tomcat started up and worked immediately. Another option would be to install Tomcat 9 outside xampp and run it with java 1.9, but for my purposes running tomcat 7 with java 1.8 is sufficient.</p>

Title: can't initialize tomcat in Xampp

Body:
I'm trying to use xampp for a course but i can't make tomcat work correctly, the error i get is:

"Tomcat Started/Stopped with errors, return code: 1
Make sure you have Java JDK or JRE installed and the required ports are free
Check the "/xampp/tomcat/logs" folder for more information"

I've seeing many others with this problem but none of the advices they get helped me get rid of it.

i've already settled the enviroment variables like this:

CATALINA_HOME: C:\xampp\tomcat

CLASSPATH: C:\xampp\tomcat\lib\servlet-api.jar;C\xampp\tomcat\lib\jsp-api.jar

JAVA_HOME: C:\Program Files\Java\jdk-9

JRE_HOME: C:\Program Files\Java\jdk-9

path: C:\Program Files\Java\jdk-9\bin;C:\xampp\Tomcat\bin;C:\Program Files\Java\jre-9\bin

I've already set the port to 7070 (not sure if this is valid)

when i run CATALINA_START from cmd i got this:

C:\xampp\tomcat>catalina_start

[XAMPP]: Searching JDK HOME with reg query ...
'reg' is not recognized as an internal or external command, operable program or batch file.
'reg' is not recognized as an internal or external command, operable program or batch file.

[XAMPP]: Seems fine!
[XAMPP]: Set JAVA_HOME : C:\Program Files\Java\jdk-9
[XAMPP]: Set CATALINA_HOME : C:\xampp\tomcat

Using CATALINA_BASE:   "C:\xampp\tomcat"
Using CATALINA_HOME:   "C:\xampp\tomcat"
Using CATALINA_TMPDIR: "C:\xampp\tomcat\temp"
Using JRE_HOME:        "C:\Program Files\Java\jre-9"
Using CLASSPATH:       "C:\xampp\tomcat\bin\bootstrap.jar;C:\xampp\tomcat\bin\tomcat-juli.jar"
-Djava.endorsed.dirs=C:\xampp\tomcat\endorsed is not supported. Endorsed standards and standalone APIs
in modular form will be supported via the concept of upgradeable modules.
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.

Apache and MySQL works just fine, but tomcat is giving headaches Does anyone know what can be wrong?


问:
How to play video after div display?

i have one div inside div a video.

default div is display hide

when show div display auto-play video (jquery)

all thing do with jquery/javascript

i have no code for this

i am trying to play video after display div. i have one Launch Invitation page with timer when timer finished then video will be play automatically.

Like this i have page

答:
One possible way of doing it, is to trigger a call when their is a changes on css style.

So it will be as:

```<code>var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutationRecord) {
        alert('play Video!');
    });
});

var target = document.getElementById('d1');
observer.observe(target, { attributes : true, attributeFilter : ['style'] });

$('#d1').css('display', 'block');
</code>```

Jsfiddle: https://jsfiddle.net/hs7ed3qb/1/

good luck :)

Title: How to play video after div display?

Body:
One possible way of doing it, is to trigger a call when their is a changes on css style.

So it will be as:

var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutationRecord) {
        alert('play Video!');
    });
});

var target = document.getElementById('d1');
observer.observe(target, { attributes : true, attributeFilter : ['style'] });

$('#d1').css('display', 'block');

Jsfiddle: https://jsfiddle.net/hs7ed3qb/1/

good luck :)


答:
You can't use "/" in class name.</p>

```<code><img class='icon weather mostlycloudy' ...>

img.weather {
    witdh:50px;
}
</code>```

Body:
sorry for this trivial question, but i just don't get it. I would like to set the witdh of this image:

I've tried things like

[class~="weather"] {
    witdh:50px;
}

.img.icon {
    witdh:50px;
}

and everything I could imagine, but the width attribute never appears if I check it with chromes inspect tool. I'm sure that I edit the correct .css file, because I can see the influence for other elements of that page. I surely am no html or css expert and maybe a bit dumb... Could you please help me?

Body:
You can't use "/" in class name.

<img class='icon weather mostlycloudy' ...>

img.weather {
    witdh:50px;
}


问:
chrome.app.window Alternative
so currently I have a packaged Chrome app, which uses chrome.app.window.create() to create frameless Notifications. Since Chrome Apps will be discontinued in the near future I am currently looking for alternatives.

I am trying now to emulate the same behavior in a Chrome Extension, but I have only found chrome.windows.create() where I can open popups, but they can't be made frameless apparently.

I have also tried chrome.notifications but they are not customizable enough for my needs.

Do any of you guys know a way to do this?

答:
No, that's about it. You can't emulate this behavior with extensions.

Add to that list a possibility to inject DOM in the currently opened page, which you can style, but it's complicated, requires very heavy permissions to do at will at any page, will be confined to the browser viewport and still won't work in some edge cases.

Title: chrome.app.window Alternative


问:
OOP design: class inherit class that contains field of class that inherit another class
Take a look at this code snippet:

```<code>public static class A {

    public void doA() {

    }

}

public static class B extends A {

    public void doB() {

    }

}

public static class AE {
    protected A field;

    public AE(A field) {
        this.field = field;
    }

    public void doStuff() {
        field.doA();
    }

}

public static class BE extends AE {

    // wanna have B field;

    public BE(B field) {
        super(field);
    }

    public void doAnotherStuff() {
        field.doA();
        field.doB(); // error here
    }

}
</code>```

What is the best solution for such design problem?
I see two options:
1) cast to B type field everytime when you need to call doB()

```<code>((B) field).doB();
</code>```

2) save B as another field fo BE class, and call this field when you need doB() functionality:

```<code>protected B field2;

    public BE(B field) {
        super(field);
        field2 = field;
    }
</code>```

Both solutions are obvious and isn't nice. In case 1) you lost performance on runtime casts, and cast field everytime looks like an error.
In case 2) we have two fields in class BE that contains pointers to exact same object B, differs only in type (field of class A and field2 of class B);
Is there any better solutions for this problem?

答:
As @Eran suggested  you can use generics or you can do something like this instead:

```<code>public static class AE {
    private A field;

    public AE(A field) {
        this.field = field;
    }
    public void doStuff() {
        field.doA();
    }

    protected A getField() {
        return field;
    }
}

public static class BE extends AE {

    public BE(B field) {
        super(field);
    }

    @Override
    protected B getField() {
        return (B) super.getField();
    }

    public void doAnotherStuff() {
        getField().doA();
        getField().doB(); // no error here
    }

}
</code>```

Adding a protected getter and overriding it in sub class. This way you would need to cast the type just once.

Body:
Take a look at this code snippet:

public static class A {

    public void doA() {

    }

}

public static class B extends A {

    public void doB() {

    }

}

public static class AE {
    protected A field;

    public AE(A field) {
        this.field = field;
    }

    public void doStuff() {
        field.doA();
    }

}

public static class BE extends AE {

    // wanna have B field;

    public BE(B field) {
        super(field);
    }

    public void doAnotherStuff() {
        field.doA();
        field.doB(); // error here
    }

}

What is the best solution for such design problem?
I see two options:
1) cast to B type field everytime when you need to call doB()

((B) field).doB();

2) save B as another field fo BE class, and call this field when you need doB() functionality:

protected B field2;

    public BE(B field) {
        super(field);
        field2 = field;
    }

Both solutions are obvious and isn't nice. In case 1) you lost performance on runtime casts, and cast field everytime looks like an error.
In case 2) we have two fields in class BE that contains pointers to exact same object B, differs only in type (field of class A and field2 of class B);
Is there any better solutions for this problem?

Body:
As @Eran suggested  you can use generics or you can do something like this instead:

public static class AE {
    private A field;

    public AE(A field) {
        this.field = field;
    }
    public void doStuff() {
        field.doA();
    }

    protected A getField() {
        return field;
    }
}

public static class BE extends AE {

    public BE(B field) {
        super(field);
    }

    @Override
    protected B getField() {
        return (B) super.getField();
    }

    public void doAnotherStuff() {
        getField().doA();
        getField().doB(); // no error here
    }

}

Adding a protected getter and overriding it in sub class. This way you would need to cast the type just once.


问:
Display an UIPopoverPresentationController from a UIControl?
I am writing a UIControl. I need to display a popover when the user touches an area of the control. But of course the usual code:

```<code>[self presentViewController:self.popover animated:YES completion:nil];
</code>```

does not work because we are in a UIControl, not in a UIViewController.
How can I display a popover from a UIControl?

答:
You should use rootViewController to present it.

Use UIApplication.sharedApplication.delegate.window.rootViewController instead of self

```<code>[UIApplication.sharedApplication.delegate.window.rootViewController presentViewController:self.popover animated:YES completion:nil];
</code>```

Body:
I am writing a UIControl. I need to display a popover when the user touches an area of the control. But of course the usual code:

[self presentViewController:self.popover animated:YES completion:nil];

does not work because we are in a UIControl, not in a UIViewController.
How can I display a popover from a UIControl?

Body:
You should use rootViewController to present it.

Use UIApplication.sharedApplication.delegate.window.rootViewController instead of self

[UIApplication.sharedApplication.delegate.window.rootViewController presentViewController:self.popover animated:YES completion:nil];