问:
Get value from a column with regex
I have lines of text similar to this:

value1|value2|value3 etc.

The values itself are not interesting. The type of delimeter is also unimportant, just like the number of fields. There could be 100 column, there could be only 5.

I would like to know what is the usual way to write a regexp which will put any given column's value into a capture group.

For example if I would like to get the content of the third field:

[^\|]+?\|[^\|]+?\|(?<capture_group>[^\|]+?)\|

Maybe a little bit nicer version:

(?:[^\|]+?\|){2}(?<capture_group>[^\|]+?)\|

But this could be the 7th, the 100th, the 1000th, it doesn't matter.

My problem is, that after a while I run into catastrophic backtracking or simply extremely low running times.

What is the usual way to solve a problem like this?

Edit:

For further clarification: this is a use case where further string operations are simply not permitted. Workarounds are not possible. I would like to know if there's a way simply based on regex or not.

答:
As you stated:

My problem is, that after a while I run into catastrophic backtracking
or simply extremely low running times.

What is the usual way to solve a problem like this?

IMHO, You should prefer to perform string operations when you have a predefined structure in string (like for your case | character is used as a separator) because string operations are faster than using Regex which is designed to find a pattern. Like, in case the separators may change and we have to identify it first and then split based on separator, here the need of a Regex comes.

e.g.,

```<code>value1|value2;value3-value4
</code>```

For your case, you can simply perform string split based on the separator character and access the respected index from an array.

EDIT:

If Regex is your only option then try using this regex:

```<code>^((.+?)\|){200}
</code>```

Here 200 is the element I wish to access and seems a bit less time consuming than yours.

Demo

Title: Get value from a column with regex

Body:
As you stated:

My problem is, that after a while I run into catastrophic backtracking
or simply extremely low running times.

What is the usual way to solve a problem like this?

IMHO, You should prefer to perform string operations when you have a predefined structure in string (like for your case | character is used as a separator) because string operations are faster than using Regex which is designed to find a pattern. Like, in case the separators may change and we have to identify it first and then split based on separator, here the need of a Regex comes.

e.g.,

value1|value2;value3-value4

For your case, you can simply perform string split based on the separator character and access the respected index from an array.

EDIT:

If Regex is your only option then try using this regex:

^((.+?)\|){200}

Here 200 is the element I wish to access and seems a bit less time consuming than yours.

Demo


来源: stackexchange

问:
MFC CFileDialog don't work correctly in Windows 2000
I develop with Visual Studio 2008 (Windows 7) and use

```<code>CFileDialog(TRUE, NULL, lastPath, NULL, szFilter);
</code>```

The important parameter is the third (lastPath) to get in a specific directory!
All works fine with Windows 7 but in Windows 2000 the Dialog only works if lastPath (LPCTSTR lpszFileName) is empty (otherwise the Dialog doesn't open)

Any ideas!?

Thanks and greets
leon22

答:
Ok, I have found the error:

don't set the initial directory with lpszFileName!

Right usage:

```<code>CFileDialog oDlg(TRUE, NULL, NULL, NULL, szFilter);
oDlg.m_ofn.lpstrInitialDir = lastPath.GetBuffer(0); // set initial dir
</code>```

greets leon22

ContentLicense: CC BY-SA 2.5

Body:
I develop with Visual Studio 2008 (Windows 7) and use

CFileDialog(TRUE, NULL, lastPath, NULL, szFilter);

The important parameter is the third (lastPath) to get in a specific directory!
All works fine with Windows 7 but in Windows 2000 the Dialog only works if lastPath (LPCTSTR lpszFileName) is empty (otherwise the Dialog doesn't open)

Any ideas!?

Thanks and greets
leon22

Body:
Ok, I have found the error:

don't set the initial directory with lpszFileName!

Right usage:

CFileDialog oDlg(TRUE, NULL, NULL, NULL, szFilter);
oDlg.m_ofn.lpstrInitialDir = lastPath.GetBuffer(0); // set initial dir

greets leon22


问:
Unable to store tweets in an sql database
Good morning,

I'm trying to write a short script in php which connect to the twitter API, download the tweets and store them into an sql database.
I'm using the 1.1 version of twitter API with TwitterOauth by Abraham

```<code>$connection = new TwitterOAuth($consumer_key,$consumer_secret,$access_token,$access_token_secret);
$tweet = $connection->get(
    'search/tweets',
    array("q" => "rome", "lang" => "it")
    );
$jsonData = json_decode($tweet);
</code>```

Using this code, the script succesfully connects to the twitter api, but the $jsonData created with json_decode is empty. I'd like to know why is this happening and if $tweet is in json format.

答:
var_dump() helps me a lot to give me information about a variabile.
In my project I have to manage some information in php an put in an sql table.
The  query I post store in $tweet a "tweet object" so I encode this object in json an then decode it in php. My code it's this:

$tweets = $connection->get(
    'search/tweets',
    array("q" => "florence", "count" => 500)
    );

$jsonData = json_encode($tweets);

$pData = json_decode($jsonData);

Now $pData contains the info I need in php.

ContentLicense: CC BY-SA 3.0

Body:
Good morning,

I'm trying to write a short script in php which connect to the twitter API, download the tweets and store them into an sql database.
I'm using the 1.1 version of twitter API with TwitterOauth by Abraham

$connection = new TwitterOAuth($consumer_key,$consumer_secret,$access_token,$access_token_secret);
$tweet = $connection->get(
    'search/tweets',
    array("q" => "rome", "lang" => "it")
    );
$jsonData = json_decode($tweet);

Using this code, the script succesfully connects to the twitter api, but the $jsonData created with json_decode is empty. I'd like to know why is this happening and if $tweet is in json format.


问:
Prestashop HelperForm: switch button
I am using Prestashop HelperForm to generate a switch button. The status of the button depends on data generated from database. The problem is that the button is always set to false.

Here is the code :

```<code>$fields_form = array(
        'form' => array(
            'legend' => array(
                'title' => $this->l('Champs pour feuille de soin'),
                'icon' => 'icon-pencil'
            ),

            'input' => array(
                array(
                    'type' => 'hidden',
                    'name' => 'id_product',
                ),
                array(
                    'type' => 'textarea',
                    'label' => $this->l('Label'),
                    'name' => 'contenu1'
                ),
                array(

                    'type' => 'hidden',
                    'name' => 'id_customization_field1',
                ),

                array(
                    'type' => 'radio',
                    'label' => $this->l('required'),
                    'name' => 'relab1',
                    'is_bool' => false,
                    'desc' => $this->l('required'),
                    'values' => array(
                        array(
                            'id' => 'label1_on',
                            'value' => 1,
                            'label' => $this->l('Enabled')
                        ),
                        array(
                            'id' => 'label1_off',
                            'value' => 0,
                            'label' => $this->l('Disabled')
                        )
                    )
                ),
                array(
                    'type' => 'textarea',
                    'label' => $this->l('Label'),
                    'name' => 'contenu2'
                ),
                array(

                    'type' => 'hidden',
                    'name' => 'id_customization_field2',
                ),
                array(
                    'type' => 'radio',
                    'label' => $this->l('required'),
                    'name' => 'relab2',
                    'is_bool' => false,
                    'desc' => $this->l('required'),
                    'values' => array(
                        array(
                            'id' => 'active_on',
                            'label' => $this->l('Enabled')
                        ),
                        array(
                            'id' => 'active_off',
                            'label' => $this->l('Disabled')
                        )
                    )
                ),

                array(
                    'type' => 'textarea',
                    'label' => $this->l('Label'),
                    'name' => 'contenu3'
                ),
                array(

                    'type' => 'hidden',
                    'name' => 'id_customization_field3',
                ),

                array(
                    'type' => 'switch',
                    'label' => $this->l('required'),
                    'name' => 'relab3',
                    'is_bool' => true,
                    'desc' => $this->l('required'),
                    'values' => array(
                        array(
                            'id' => 'label3_on',
                            'value' => 1,
                            'label' => $this->l('Enabled')
                        ),
                        array(
                            'id' => 'label3_off',
                            'value' => 0,
                            'label' => $this->l('Disabled')
                        )
                    )
                ),

                array(
                    'type' => 'textarea',
                    'label' => $this->l('Label'),
                    'name' => 'contenu4'
                ),
                array(

                    'type' => 'hidden',
                    'name' => 'id_customization_field4',
                ),

                array(
                    'type' => 'checkbox',
                    'label' => $this->l('Required'),
                    'name' => 'label4',
                    'class' => 't',
                    'multiple' => true,
                    'values' => array(
                        'query' => array($label3),
                        'id' => 'label4',
                        'name' => 'label4',
                        'expand' => array(
                            'default' => 'show',
                            'show' => array('text' => $this->l('show'), 'icon' => 'plus-sign-alt'),
                            'hide' => array('text' => $this->l('hide'), 'icon' => 'minus-sign-alt')
                        ),
                    )
                ),

            ),
            'submit' => array(
                'title' => $this->l('Save'),
                'name' => $this->l('submitAddproduct'),
            )
        ),
    );

    $helper = new HelperForm();
    $helper->show_toolbar = false;
    $helper->table = $this->table;
    $lang = new Language((int)Configuration::get('PS_LANG_DEFAULT'));
    $helper->default_form_language = $lang->id;
    $helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') ? Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') : 0;
    $helper->identifier = $this->identifier;
    $helper->submit_action = 'submitUpdate';
    $helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false) . '&configure=' . $this->name . '&tab_module=' . $this->tab . '&module_name=' . $this->name;
    $helper->token = Tools::getAdminTokenLite('AdminModules');
    $helper->tpl_vars = array(
        $helper->fields_value['id_product'] = Tools::getValue('id_product'),
        'relab4' => 1,

        'languages' => $this->context->controller->getLanguages(),
        'id_language' => $this->context->language->id
    );

    $helper->fields_value['contenu1'] = $contenu1;
    $helper->fields_value['contenu2'] = $contenu2;
    $helper->fields_value['contenu3'] = $contenu3;
    $helper->fields_value['contenu4'] = $contenu4;
    $helper->fields_value['relab1'] = (int)$relab1;
    $helper->fields_value['relab2'] = (int)$relab2;
    $helper->fields_value['relab3'] = (int)$relab3;
    $helper->fields_value['relab4'] = (int)$relab4;
    $helper->fields_value['id_customization_field1'] = $id_customization_field1;
    $helper->fields_value['id_customization_field2'] = $id_customization_field2;
    $helper->fields_value['id_customization_field3'] = $id_customization_field3;
    $helper->fields_value['id_customization_field4'] = $id_customization_field4;

    return $helper->generateForm(array($fields_form));
</code>```

答:
Hi I have had the same issue on prestashop 1.6 and 1.7 and I finally figured out the problem so I will share my findings with you guys.

So here is my switch :

```<code> array(
    'type' => 'switch',
    'label' => $this->trans('Captcha Test Mode', array(), 'Admin.Shipping.Feature'),
     'name' => 'CORE_CAPTCHA_TEST_MODE',
     'required' => false,
     'class' => 't',
     'is_bool' => true,
      'values' => array(
            array(
                'id' => 'active_on',
                'value' => 1,
                'label' => $this->trans('Enabled', array(), 'Admin.Global'),
                 ),
            array(
                'id' => 'active_off',
                'value' => 0,
                'label' => $this->trans('Disabled', array(), 'Admin.Global'),
                 ),
       ),
</code>```

As you can see it has to have an explicit name CORE_CAPTCHA_TEST_MODE.

Where things become interesting is in the getConfigFormValues() method :

```<code> protected function getConfigFormValues()
{
    return array(
        'CORE_CAPTCHA_TEST_MODE' => Tools::getValue('CORE_CAPTCHA_TEST_MODE', Configuration::get('CORE_CAPTCHA_TEST_MODE', true)),
    );
}
</code>```

Unlike any other type of field where a simple Configuration::get would be enough to set the value in the field when the form is loaded for a switch we need to add Tools::getValue(...

Title: Prestashop HelperForm: switch button

Body:
I am using Prestashop HelperForm to generate a switch button. The status of the button depends on data generated from database. The problem is that the button is always set to false.

Here is the code :

$fields_form = array(
        'form' => array(
            'legend' => array(
                'title' => $this->l('Champs pour feuille de soin'),
                'icon' => 'icon-pencil'
            ),

            'input' => array(
                array(
                    'type' => 'hidden',
                    'name' => 'id_product',
                ),
                array(
                    'type' => 'textarea',
                    'label' => $this->l('Label'),
                    'name' => 'contenu1'
                ),
                array(

                    'type' => 'hidden',
                    'name' => 'id_customization_field1',
                ),

                array(
                    'type' => 'radio',
                    'label' => $this->l('required'),
                    'name' => 'relab1',
                    'is_bool' => false,
                    'desc' => $this->l('required'),
                    'values' => array(
                        array(
                            'id' => 'label1_on',
                            'value' => 1,
                            'label' => $this->l('Enabled')
                        ),
                        array(
                            'id' => 'label1_off',
                            'value' => 0,
                            'label' => $this->l('Disabled')
                        )
                    )
                ),
                array(
                    'type' => 'textarea',
                    'label' => $this->l('Label'),
                    'name' => 'contenu2'
                ),
                array(

                    'type' => 'hidden',
                    'name' => 'id_customization_field2',
                ),
                array(
                    'type' => 'radio',
                    'label' => $this->l('required'),
                    'name' => 'relab2',
                    'is_bool' => false,
                    'desc' => $this->l('required'),
                    'values' => array(
                        array(
                            'id' => 'active_on',
                            'label' => $this->l('Enabled')
                        ),
                        array(
                            'id' => 'active_off',
                            'label' => $this->l('Disabled')
                        )
                    )
                ),

                array(
                    'type' => 'textarea',
                    'label' => $this->l('Label'),
                    'name' => 'contenu3'
                ),
                array(

                    'type' => 'hidden',
                    'name' => 'id_customization_field3',
                ),

                array(
                    'type' => 'switch',
                    'label' => $this->l('required'),
                    'name' => 'relab3',
                    'is_bool' => true,
                    'desc' => $this->l('required'),
                    'values' => array(
                        array(
                            'id' => 'label3_on',
                            'value' => 1,
                            'label' => $this->l('Enabled')
                        ),
                        array(
                            'id' => 'label3_off',
                            'value' => 0,
                            'label' => $this->l('Disabled')
                        )
                    )
                ),

                array(
                    'type' => 'textarea',
                    'label' => $this->l('Label'),
                    'name' => 'contenu4'
                ),
                array(

                    'type' => 'hidden',
                    'name' => 'id_customization_field4',
                ),

                array(
                    'type' => 'checkbox',
                    'label' => $this->l('Required'),
                    'name' => 'label4',
                    'class' => 't',
                    'multiple' => true,
                    'values' => array(
                        'query' => array($label3),
                        'id' => 'label4',
                        'name' => 'label4',
                        'expand' => array(
                            'default' => 'show',
                            'show' => array('text' => $this->l('show'), 'icon' => 'plus-sign-alt'),
                            'hide' => array('text' => $this->l('hide'), 'icon' => 'minus-sign-alt')
                        ),
                    )
                ),

            ),
            'submit' => array(
                'title' => $this->l('Save'),
                'name' => $this->l('submitAddproduct'),
            )
        ),
    );

    $helper = new HelperForm();
    $helper->show_toolbar = false;
    $helper->table = $this->table;
    $lang = new Language((int)Configuration::get('PS_LANG_DEFAULT'));
    $helper->default_form_language = $lang->id;
    $helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') ? Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') : 0;
    $helper->identifier = $this->identifier;
    $helper->submit_action = 'submitUpdate';
    $helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false) . '&configure=' . $this->name . '&tab_module=' . $this->tab . '&module_name=' . $this->name;
    $helper->token = Tools::getAdminTokenLite('AdminModules');
    $helper->tpl_vars = array(
        $helper->fields_value['id_product'] = Tools::getValue('id_product'),
        'relab4' => 1,

        'languages' => $this->context->controller->getLanguages(),
        'id_language' => $this->context->language->id
    );

    $helper->fields_value['contenu1'] = $contenu1;
    $helper->fields_value['contenu2'] = $contenu2;
    $helper->fields_value['contenu3'] = $contenu3;
    $helper->fields_value['contenu4'] = $contenu4;
    $helper->fields_value['relab1'] = (int)$relab1;
    $helper->fields_value['relab2'] = (int)$relab2;
    $helper->fields_value['relab3'] = (int)$relab3;
    $helper->fields_value['relab4'] = (int)$relab4;
    $helper->fields_value['id_customization_field1'] = $id_customization_field1;
    $helper->fields_value['id_customization_field2'] = $id_customization_field2;
    $helper->fields_value['id_customization_field3'] = $id_customization_field3;
    $helper->fields_value['id_customization_field4'] = $id_customization_field4;

    return $helper->generateForm(array($fields_form));

Body:
Hi I have had the same issue on prestashop 1.6 and 1.7 and I finally figured out the problem so I will share my findings with you guys.

So here is my switch :

 array(
    'type' => 'switch',
    'label' => $this->trans('Captcha Test Mode', array(), 'Admin.Shipping.Feature'),
     'name' => 'CORE_CAPTCHA_TEST_MODE',
     'required' => false,
     'class' => 't',
     'is_bool' => true,
      'values' => array(
            array(
                'id' => 'active_on',
                'value' => 1,
                'label' => $this->trans('Enabled', array(), 'Admin.Global'),
                 ),
            array(
                'id' => 'active_off',
                'value' => 0,
                'label' => $this->trans('Disabled', array(), 'Admin.Global'),
                 ),
       ),

As you can see it has to have an explicit name CORE_CAPTCHA_TEST_MODE.

Where things become interesting is in the getConfigFormValues() method :

 protected function getConfigFormValues()
{
    return array(
        'CORE_CAPTCHA_TEST_MODE' => Tools::getValue('CORE_CAPTCHA_TEST_MODE', Configuration::get('CORE_CAPTCHA_TEST_MODE', true)),
    );
}

Unlike any other type of field where a simple Configuration::get would be enough to set the value in the field when the form is loaded for a switch we need to add Tools::getValue(...


问:
Bars not showing when saving Bar Chart view
My chart shows up fine in my app, but when I save the chartView to camera roll or for use in another UIViewController the bars don't show up.

Fine in my app:

Bars don't show up when save the chartView to camera roll or for use in another UIViewController:

I've tried a few ways of doing this -specifically for saving the chartView to Camera Roll- like:

1)

```<code>    let image1 = chartView.getChartImage(transparent: false)
    UIImageWriteToSavedPhotosAlbum(image1!, nil, nil, nil)
</code>```

2)

```<code>    let image2 = captureScreen()
    UIImageWriteToSavedPhotosAlbum(image2!, nil, nil, nil)
</code>```

3)

```<code>extension UIImage {
    convenience init(view: UIView) {
        UIGraphicsBeginImageContext(view.frame.size)
        view.layer.render(in: UIGraphicsGetCurrentContext()!)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        self.init(cgImage: (image?.cgImage)!)
    }
}

    let image3 = UIImage(view: chartView)
    UIImageWriteToSavedPhotosAlbum(image3, nil, nil, nil)
</code>```

But nothing works for me. Any ideas why?  Thanks!

答:
I had the same issue when capturing image using getChartImage. So I made my own function for capturing Image.

Basically I make a UIView class and inherited LineChartView.
Made UIView extension for taking snapShot of my chartView.

Implement this function in UIView extension:

```<code>func snapShot() -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(self.frame.size , false, UIScreen.main.scale)
        self.layer.render(in: UIGraphicsGetCurrentContext()!)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return image
    }
</code>```

And call it like this

```<code>let image = chartView.snapShot()
</code>```

Hope this helps!!!

Body:
My chart shows up fine in my app, but when I save the chartView to camera roll or for use in another UIViewController the bars don't show up.

Fine in my app:

Bars don't show up when save the chartView to camera roll or for use in another UIViewController:

I've tried a few ways of doing this -specifically for saving the chartView to Camera Roll- like:

1)

    let image1 = chartView.getChartImage(transparent: false)
    UIImageWriteToSavedPhotosAlbum(image1!, nil, nil, nil)

2)

    let image2 = captureScreen()
    UIImageWriteToSavedPhotosAlbum(image2!, nil, nil, nil)

3)

extension UIImage {
    convenience init(view: UIView) {
        UIGraphicsBeginImageContext(view.frame.size)
        view.layer.render(in: UIGraphicsGetCurrentContext()!)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        self.init(cgImage: (image?.cgImage)!)
    }
}

    let image3 = UIImage(view: chartView)
    UIImageWriteToSavedPhotosAlbum(image3, nil, nil, nil)

But nothing works for me. Any ideas why?  Thanks!

Body:
I had the same issue when capturing image using getChartImage. So I made my own function for capturing Image.

Basically I make a UIView class and inherited LineChartView.
Made UIView extension for taking snapShot of my chartView.

Implement this function in UIView extension:

func snapShot() -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(self.frame.size , false, UIScreen.main.scale)
        self.layer.render(in: UIGraphicsGetCurrentContext()!)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return image
    }

And call it like this

let image = chartView.snapShot()

Hope this helps!!!


问:
Get id of clicked element without putting any js code in the html
I need to get the ID of an element that was clicked, but I need to to keep all my js and html separate. normally id just use 'this.id' in the html. Any other ways?</p>

答:
```<code>window.onclick = e => {
    console.log(e.target.id);
}
</code>```

to get element, tagname, classname , other attributes

```<code>window.onclick = e => {
    console.log(e.target);
    console.log(e.target.tagName);
    console.log(e.target.className);
    console.log(e.target.id);
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
window.onclick = e => {
    console.log(e.target.id);
}

to get element, tagname, classname , other attributes

window.onclick = e => {
    console.log(e.target);
    console.log(e.target.tagName);
    console.log(e.target.className);
    console.log(e.target.id);
}


问:
How use third-party plugins after install in npm?
I install plugin (for instance normalize.css or jQuery) with npm install command.

```<code>npm install normalize.css --save
npm install jquery --save
</code>```

I see them in package.json

```<code>  "dependencies": {
    "normalize.css": "^7.0.0"
  }
</code>```

What next? How i can use it in my project? I'm using gulp and I do not know what to do next.

答:
There are two main ways to make use of it.

Approach 1: use normalize.css as a starting point for your own project’s base CSS, customising the values to match the design’s requirements.

Approach 2: include normalize.css untouched and build upon it, overriding the defaults later in your CSS if necessary.

Body:
I install plugin (for instance normalize.css or jQuery) with npm install command.

npm install normalize.css --save
npm install jquery --save

I see them in package.json

  "dependencies": {
    "normalize.css": "^7.0.0"
  }

What next? How i can use it in my project? I'm using gulp and I do not know what to do next.


问:
issue with FILE
I'm getting the folowing error for below code,
"1506-221 (S) Initializer must be a valid constant expression"

```<code>FILE          *fp[] = {stdout, dump_f};
</code>```

is this acceptable? what is the proper way to achive this?

答:
The error suggests that on your system the stdout variable is in fact a #defined macro which expands to a function call.

Actually, as others have suggested, it's probably just that stdout is an extern declared variable whose value is not known at compile time and therefore can't be supplied in a static initializer.

Regardless of which, the solution should be the same - I'd try something like:

```<code>FILE *fp[2];

void init_fp()
{
    fp[0] = stdout;
    fp[1] = dump_f;
}
</code>```

OwnerDisplayName: Thi

Title: issue with FILE

Body:
I'm getting the folowing error for below code,
"1506-221 (S) Initializer must be a valid constant expression"

FILE          *fp[] = {stdout, dump_f};

is this acceptable? what is the proper way to achive this?

LastEditorDisplayName: strager

Body:
The error suggests that on your system the stdout variable is in fact a #defined macro which expands to a function call.

Actually, as others have suggested, it's probably just that stdout is an extern declared variable whose value is not known at compile time and therefore can't be supplied in a static initializer.

Regardless of which, the solution should be the same - I'd try something like:

FILE *fp[2];

void init_fp()
{
    fp[0] = stdout;
    fp[1] = dump_f;
}

OwnerDisplayName: Alnitak

LastEditorDisplayName: Alnitak


问:
Copy vars from table a to table b retaining b's existing keys
I am trying to copy the contents of the source table to the dest table, overwriting keys that are the same and leaving different keys intact. I've messed about with a few things but can't figure it out. Can somebody help me?</p>

```<code>local source = {
  version = 1,
  nest = {
    a = 5,
    b = 1,
    c = 0
    },
}

local dest = {
  version = 0,
  doesNotChange = 9,
  nest = {
    a = 0,
    b = 0,
    c = 0,
    d = "does not change"
  },
}
</code>```

答:
You can use a generic for statement to achieve what you want.

The loop will iterate over all keys in sourceTable and asign the respective value to destinationTable. As you only index keys of sourceTable you cannot overwrite fields of destinationTable that have unique keys but you overwrite fields that exist in both tables and add new fields that only exist in sourceTable.

```<code>for k,v in pairs(sourceTable) do

  destinationTable[k] = v

end
</code>```

Body:
I am trying to copy the contents of the source table to the dest table, overwriting keys that are the same and leaving different keys intact. I've messed about with a few things but can't figure it out. Can somebody help me?

local source = {
  version = 1,
  nest = {
    a = 5,
    b = 1,
    c = 0
    },
}

local dest = {
  version = 0,
  doesNotChange = 9,
  nest = {
    a = 0,
    b = 0,
    c = 0,
    d = "does not change"
  },
}

Body:
You can use a generic for statement to achieve what you want.

The loop will iterate over all keys in sourceTable and asign the respective value to destinationTable. As you only index keys of sourceTable you cannot overwrite fields of destinationTable that have unique keys but you overwrite fields that exist in both tables and add new fields that only exist in sourceTable.

for k,v in pairs(sourceTable) do

  destinationTable[k] = v

end


问:
C# Web API - POST Request doesn't get executed
I am trying to send a POST request from my ASP.NET Core Web API Project but the request is never sent. The method gets executed with no errors but the request never gets sent out from the async method.

My Implementation:

```<code>public async void notify(String message)
{
    String url = "MY_WEBSERVICE_URL";
    var client = new HttpClient();
    client.BaseAddress = new Uri(url);
    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "relativeAddress");
    request.Content = new StringContent("application/x-www-form-urlencoded;charset=UTF-8",
    Encoding.UTF8, "application/json");

    Byte[] byteArray = Encoding.UTF8.GetBytes("{\"text\":\"" + message + "\"}");
    request.Content.Headers.ContentLength = byteArray.Length;

    await client.SendAsync(request).ContinueWith(responseTask =>
    {
       Console.WriteLine("Response: {0}", responseTask.Result);
    });
}
</code>```

Is this the proper way of making a POST request from a Core Web API project? Thank you in advance

答:
First of all, there is a dedicated method PostAsync in the HttpClient class ( or even PostAsJsonAsync extension) which you can use to send POST requests without creating HttpRequstMessage manually.

Now about your code - I believe you want to post following JSON string:

```<code>{"text":"someMessage"}
</code>```

You should set this string as a content of StringContent which you are sending:

```<code>var json = "{\"text\":\"" + message + "\"}";
request.Content = new StringContent(json, Encoding.UTF8, "application/json");
</code>```

Currently you are trying to post mediatype string as a value to your API endpoint. Of course it cannot be deserialized into your model.

Note1: StringContent will automatically add Content-Length header with the appropriate value. You should not do that manually.

Note2: Unless this is an event handler, you should not use async void - use async Task instead.

Same task with PostAsJsonAsync usage will look like:

```<code>public async Task Notify(string message)
{
   var string url = "MY_WEBSERVICE_URL";
   var client = new HttpClient();
   client.BaseAddress = new Uri(url);
   var notification = new Notification { Text = message }; // use some model class
   var resonse = await client.PostAsJsonAsync("relativeAddress", notification);
   if (response.IsSuccessStatusCode)
   {
       var content = await response.Content.ReadAsStringAsync();
   }
}
</code>```

In this case, your model will be automatically serialized into JSON, appropriate content will be created and POST request will be sent.

Body:
I am trying to send a POST request from my ASP.NET Core Web API Project but the request is never sent. The method gets executed with no errors but the request never gets sent out from the async method.

My Implementation:

public async void notify(String message)
{
    String url = "MY_WEBSERVICE_URL";
    var client = new HttpClient();
    client.BaseAddress = new Uri(url);
    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "relativeAddress");
    request.Content = new StringContent("application/x-www-form-urlencoded;charset=UTF-8",
    Encoding.UTF8, "application/json");

    Byte[] byteArray = Encoding.UTF8.GetBytes("{\"text\":\"" + message + "\"}");
    request.Content.Headers.ContentLength = byteArray.Length;

    await client.SendAsync(request).ContinueWith(responseTask =>
    {
       Console.WriteLine("Response: {0}", responseTask.Result);
    });
}

Is this the proper way of making a POST request from a Core Web API project? Thank you in advance

Body:
First of all, there is a dedicated method PostAsync in the HttpClient class ( or even PostAsJsonAsync extension) which you can use to send POST requests without creating HttpRequstMessage manually.

Now about your code - I believe you want to post following JSON string:

{"text":"someMessage"}

You should set this string as a content of StringContent which you are sending:

var json = "{\"text\":\"" + message + "\"}";
request.Content = new StringContent(json, Encoding.UTF8, "application/json");

Currently you are trying to post mediatype string as a value to your API endpoint. Of course it cannot be deserialized into your model.

Note1: StringContent will automatically add Content-Length header with the appropriate value. You should not do that manually.

Note2: Unless this is an event handler, you should not use async void - use async Task instead.

Same task with PostAsJsonAsync usage will look like:

public async Task Notify(string message)
{
   var string url = "MY_WEBSERVICE_URL";
   var client = new HttpClient();
   client.BaseAddress = new Uri(url);
   var notification = new Notification { Text = message }; // use some model class
   var resonse = await client.PostAsJsonAsync("relativeAddress", notification);
   if (response.IsSuccessStatusCode)
   {
       var content = await response.Content.ReadAsStringAsync();
   }
}

In this case, your model will be automatically serialized into JSON, appropriate content will be created and POST request will be sent.


问:
HTML audio not stopping on variable count
It's a simple program which starts the audio in HTML as variable in betNo in javascript starts from 0.

But I am having trouble stopping the audio when variable reaches 10. I have reduced the original code to make it simpler. The counter is necessary for my program so removing it can't be an option. You can see the varible count in the console.

You can use jquery to solve as I am already using it.

Thank you in advance.

document.addEventListener('DOMContentLoaded', function(event) {
  var betNo = 0;
  var boxTimer = setInterval(function() {
    var myAudio = document.getElementById('songOne');
    var isPlaying = false;

    function togglePlay() {
      if (isPlaying) {
        myAudio.pause();
      } else {
        myAudio.play();
      }
    };
    myAudio.onplaying = function() {
      isPlaying = true;
    };
    myAudio.onpause = function() {
      isPlaying = false;
    };
    if ((betNo == 0) || (betNo == 10)) {
      togglePlay();
    }
    console.log(betNo);
    betNo++;
    if (betNo >= 20) {
      clearInterval(boxTimer);
    }
  }, 1000);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<audio id="songOne" src="http://www.sousound.com/music/healing/healing_01.mp3" preload="auto">
</audio></code>```

答:
I have edited my answer.
The button to start the timer will allow the sound to be played on safari mobile
The timer doesn't re-declare variables and functions like it did before
You could make it cleaner with less global variables but I don't know how the rest of your code would be affected by this so I didn't change it.</p>

```<code><button onclick=start()>start</button>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" ></script> <audio id = "songOne" src = "http://www.sousound.com/music/healing/healing_01.mp3" preload = "auto" > </audio>
<script>
// declaring variables
var betNo = 0 ;
var myAudio = document . getElementById ( 'songOne' );
var isPlaying =false;
var togglePlay=function(){
if (isPlaying) {
myAudio . pause (); }
else {
myAudio . play (); } };
myAudio . onplaying = function () { isPlaying = true ;};
myAudio . onpause = function () { isPlaying = false ;};
var start=function(){

// setTimer with only the necessary code inside so variables are not being declared more than once
boxTimer = setInterval ( function (){ if (( betNo == 0 )||( betNo == 10 )){
togglePlay (betNo); }
console . log ( betNo );
betNo ++; if ( betNo >= 20 ){
clearInterval ( boxTimer ); } }, 1000 ); }
</script>
</code>```

Body:
It's a simple program which starts the audio in HTML as variable in betNo in javascript starts from 0.

But I am having trouble stopping the audio when variable reaches 10. I have reduced the original code to make it simpler. The counter is necessary for my program so removing it can't be an option. You can see the varible count in the console.

You can use jquery to solve as I am already using it.

Thank you in advance.

document.addEventListener('DOMContentLoaded', function(event) {
  var betNo = 0;
  var boxTimer = setInterval(function() {
    var myAudio = document.getElementById('songOne');
    var isPlaying = false;

    function togglePlay() {
      if (isPlaying) {
        myAudio.pause();
      } else {
        myAudio.play();
      }
    };
    myAudio.onplaying = function() {
      isPlaying = true;
    };
    myAudio.onpause = function() {
      isPlaying = false;
    };
    if ((betNo == 0) || (betNo == 10)) {
      togglePlay();
    }
    console.log(betNo);
    betNo++;
    if (betNo >= 20) {
      clearInterval(boxTimer);
    }
  }, 1000);
});

<audio id="songOne" src="http://www.sousound.com/music/healing/healing_01.mp3" preload="auto">
</audio>

Body:
I have edited my answer.
The button to start the timer will allow the sound to be played on safari mobile
The timer doesn't re-declare variables and functions like it did before
You could make it cleaner with less global variables but I don't know how the rest of your code would be affected by this so I didn't change it.

<button onclick=start()>start</button>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" ></script> <audio id = "songOne" src = "http://www.sousound.com/music/healing/healing_01.mp3" preload = "auto" > </audio>
<script>
// declaring variables
var betNo = 0 ;
var myAudio = document . getElementById ( 'songOne' );
var isPlaying =false;
var togglePlay=function(){
if (isPlaying) {
myAudio . pause (); }
else {
myAudio . play (); } };
myAudio . onplaying = function () { isPlaying = true ;};
myAudio . onpause = function () { isPlaying = false ;};
var start=function(){

// setTimer with only the necessary code inside so variables are not being declared more than once
boxTimer = setInterval ( function (){ if (( betNo == 0 )||( betNo == 10 )){
togglePlay (betNo); }
console . log ( betNo );
betNo ++; if ( betNo >= 20 ){
clearInterval ( boxTimer ); } }, 1000 ); }
</script>


问:
Foreach cast skip?
I have a list of some List<Building> playersBuildings containing objects all deriving from Bulilding class and I came across something that is quite unintuitive to me.

The following code:

```<code>foreach (Factory f in playersBuildings) {
    f.Update (deltaTime);
}
</code>```

tries to cast every element of playersBuildings to Factory and yields InvalidCastException error. While it has some sense, while writing the code I hoped that foreach will just omit elements that does not match specified type.

My first thought of solution was this:

```<code>foreach (Building f in playersBuildings) {
    if ((f is Factory) == false)
        continue;
    (f as Factory).Update (deltaTime);
}
</code>```

but I don't like having to use as keyword. Need to type in additional +10 characters every time I want to do something with my f under it's iteration is frustrating.

Is there any more elegant way to skip elements not matching the right type?

答:
I suggest OfType() Linq method to filter out all Factory instances:

```<code>foreach (Factory f in playersBuildings.OfType<Factory>()) {
  f.Update(deltaTime);
}
</code>```

Non-Linq solution can be implemented with ?. operator:

```<code>foreach (Building b in playersBuildings) {
  (b as Factory)?.Update(deltaTime);
}
</code>```

Title: Foreach cast skip?

Body:
I have a list of some List<Building> playersBuildings containing objects all deriving from Bulilding class and I came across something that is quite unintuitive to me.

The following code:

foreach (Factory f in playersBuildings) {
    f.Update (deltaTime);
}

tries to cast every element of playersBuildings to Factory and yields InvalidCastException error. While it has some sense, while writing the code I hoped that foreach will just omit elements that does not match specified type.

My first thought of solution was this:

foreach (Building f in playersBuildings) {
    if ((f is Factory) == false)
        continue;
    (f as Factory).Update (deltaTime);
}

but I don't like having to use as keyword. Need to type in additional +10 characters every time I want to do something with my f under it's iteration is frustrating.

Is there any more elegant way to skip elements not matching the right type?

Body:
I suggest OfType() Linq method to filter out all Factory instances:

foreach (Factory f in playersBuildings.OfType<Factory>()) {
  f.Update(deltaTime);
}

Non-Linq solution can be implemented with ?. operator:

foreach (Building b in playersBuildings) {
  (b as Factory)?.Update(deltaTime);
}


问:
Clearing input field on firebase function after angular submit
The function works and submits the user input to my firebase "back-end" but I cannot figure out a clear function to empty out the input field after using ng-submit.  The input is tied to the var "emailInput" with ng-model.  Thanks for any suggestions!</p>

```<code>var newEmailref = new Firebase("https://nevermind.com");
$scope.email = $firebaseArray(newEmailref);
$scope.addEmail = function(email) {
    $scope.email.$add(email);
    $scope.emailInput = '';
};
</code>```

答:
Your code just needs a small modification to use $scope.email = ""; instead of $scope.emailInput = '';:

```<code>var newEmailref = new Firebase("https://nevermind.com");
$scope.email = $firebaseArray(newEmailref);
$scope.addEmail = function(email) {
  $scope.email.$add(email);
  $scope.email = '';
};
</code>```

Body:
The function works and submits the user input to my firebase "back-end" but I cannot figure out a clear function to empty out the input field after using ng-submit.  The input is tied to the var "emailInput" with ng-model.  Thanks for any suggestions!

var newEmailref = new Firebase("https://nevermind.com");
$scope.email = $firebaseArray(newEmailref);
$scope.addEmail = function(email) {
    $scope.email.$add(email);
    $scope.emailInput = '';
};

Body:
Your code just needs a small modification to use $scope.email = ""; instead of $scope.emailInput = '';:

var newEmailref = new Firebase("https://nevermind.com");
$scope.email = $firebaseArray(newEmailref);
$scope.addEmail = function(email) {
  $scope.email.$add(email);
  $scope.email = '';
};


问:
How to Subtract firebase timestamp with current time and check if it exceeds 5 minutes in Angular
I have a angular app in which i am storing records to firebase with the timestamp using firebase.database.ServerValue.TIMESTAMP

Now i want to check if the timestamp added to the database exceeds five minutes.

I tried using moment in my Component but it just dosent work . It is giving false data . I guess the data stored in Firebase is in epoch where as i am in india so how to make moment work in Angular .

I am using Angular 2 Moment.

This is what i tried

```<code>import * as moment from 'moment/moment';

      edit(i:number){
        const val = moment.unix(this.comments[0].createdAt);// the value is a epoch time that is the standard that is stored in firebase
        const present = moment().unix();

        console.log(moment.duration(val.diff(present)));
      }
</code>```

The Value of this.comments when using it in date

let ts = new Date(this.comments[0].createdAt * 1000); = Wed Aug 05 49474 20:09:20 GMT+0530 (India Standard Time)

where as for now its like -- Tue Jul 04 2017 14:56:46 GMT+0530 (India Standard Time)

Please help why its the comments data not is sink with the time it should be july 3 as it was added on that day on firebase

答:
```<code>const now = new Date();
const ts = new Date(this.comments[0].createdAt);
const diff = now.getTime() -  ts.getTime();

console.log(diff > 5 * 60 * 1000); // this will give you true or false
</code>```

Body:
I have a angular app in which i am storing records to firebase with the timestamp using firebase.database.ServerValue.TIMESTAMP

Now i want to check if the timestamp added to the database exceeds five minutes.

I tried using moment in my Component but it just dosent work . It is giving false data . I guess the data stored in Firebase is in epoch where as i am in india so how to make moment work in Angular .

I am using Angular 2 Moment.

This is what i tried

import * as moment from 'moment/moment';

      edit(i:number){
        const val = moment.unix(this.comments[0].createdAt);// the value is a epoch time that is the standard that is stored in firebase
        const present = moment().unix();

        console.log(moment.duration(val.diff(present)));
      }

The Value of this.comments when using it in date

let ts = new Date(this.comments[0].createdAt * 1000); = Wed Aug 05 49474 20:09:20 GMT+0530 (India Standard Time)

where as for now its like -- Tue Jul 04 2017 14:56:46 GMT+0530 (India Standard Time)

Please help why its the comments data not is sink with the time it should be july 3 as it was added on that day on firebase


问:
JQuery wrong ID in an inner click
I'm trying to make a colorpicker. Where you got a few colorcubes with the class colorcube.
When clicking, it opens a colorpicker with a few list items who all have a different color.
When clicking on a list items it should return de color/text to de colorcube.

The first colorpick after the document is ready works. But after that it doesnt work properly, because it remembers al the previous colorcube ID's so al the other cube's will also change :(

Is there a way to clear cache or something like that?

```<code>$('.colorcube').click(function() {
    var colorcubeid = $(this).attr("id");
    $('#choicecolor').show();

    $(".li_color").click(function() {
        var colorid = "#" + this.id;
        var colorli = $(colorid).text();
        $('#' + colorcubeid).text(colorli);
        $('#' + colorcubeid).css({ 'background-color': '' + colorli + '' });
        $('#choicecolor').hide();
        savecolor();
    });

});
</code>```

答:
You're assigning redundant click event handlers with every click on colorcube. You should assign the handlers only once.

It seems like you're doing this in order to reference the ID of the colorcube that was clicked. You could use a variable instead to track which was clicked.

```<code>var $currentCube,
    $choiceColor = $('#choicecolor');

$('.colorcube').click(function() {
    $currentCube = $(this);
    $choiceColor.show();
});

$(".li_color").click(function() {
    var colorli = $(this).text();
    $currentCube.text(colorli)
                .css({ 'background-color': colorli });
    $choiceColor.hide();
    savecolor();
});
</code>```

I made a number of changes as well.

Instead of referencing just the ID of the current color cube, I'm referencing the actual element wrapped in a jQuery object, so you can just call methods on it directly.

This code:

```<code>var colorid = "#" + this.id;
var colorli = $(colorid).text();
</code>```

...is much more complex than needed, since you can just do:

```<code>var colorli = $(this).text();
</code>```

...where this is the
 that was clicked.

You don't need:

```<code>'' + colorli + ''
</code>```

because colorli is already a String. Just do

```<code>.css({ 'background-color': colorli })
</code>```

As @Šime Vidas noted, you should cache the $('#choicecolor'); so that you're not constantly selecting it from the DOM.

```<code>var $currentCube,
    $choiceColor = $('#choicecolor');
</code>```

I also used chaining on this line. With jQuery you don't really need to separate your function calls against the same jQuery object. They can be chained together.

```<code>$currentCube.text(colorli)
            .css({ 'background-color': colorli });
</code>```

Title: JQuery wrong ID in an inner click

Body:
I'm trying to make a colorpicker. Where you got a few colorcubes with the class colorcube.
When clicking, it opens a colorpicker with a few list items who all have a different color.
When clicking on a list items it should return de color/text to de colorcube.

The first colorpick after the document is ready works. But after that it doesnt work properly, because it remembers al the previous colorcube ID's so al the other cube's will also change :(

Is there a way to clear cache or something like that?

$('.colorcube').click(function() {
    var colorcubeid = $(this).attr("id");
    $('#choicecolor').show();

    $(".li_color").click(function() {
        var colorid = "#" + this.id;
        var colorli = $(colorid).text();
        $('#' + colorcubeid).text(colorli);
        $('#' + colorcubeid).css({ 'background-color': '' + colorli + '' });
        $('#choicecolor').hide();
        savecolor();
    });

});

Body:
You're assigning redundant click event handlers with every click on colorcube. You should assign the handlers only once.

It seems like you're doing this in order to reference the ID of the colorcube that was clicked. You could use a variable instead to track which was clicked.

var $currentCube,
    $choiceColor = $('#choicecolor');

$('.colorcube').click(function() {
    $currentCube = $(this);
    $choiceColor.show();
});

$(".li_color").click(function() {
    var colorli = $(this).text();
    $currentCube.text(colorli)
                .css({ 'background-color': colorli });
    $choiceColor.hide();
    savecolor();
});

I made a number of changes as well.

Instead of referencing just the ID of the current color cube, I'm referencing the actual element wrapped in a jQuery object, so you can just call methods on it directly.

This code:

var colorid = "#" + this.id;
var colorli = $(colorid).text();

...is much more complex than needed, since you can just do:

var colorli = $(this).text();

...where this is the <li> that was clicked.

You don't need:

'' + colorli + ''

because colorli is already a String. Just do

.css({ 'background-color': colorli })

As @Šime Vidas noted, you should cache the $('#choicecolor'); so that you're not constantly selecting it from the DOM.

var $currentCube,
    $choiceColor = $('#choicecolor');

I also used chaining on this line. With jQuery you don't really need to separate your function calls against the same jQuery object. They can be chained together.

$currentCube.text(colorli)
            .css({ 'background-color': colorli });


问:
Query for Entity type (discriminator) with JPA and Spring Boot
I am trying to understand Spring Boot's and JPA's magics. I have the following classes:

Base Asset class (could also be abstract in my case)
Class Model inheriting from Asset.

```<code>// ASSET CLASS

import javax.persistence.DiscriminatorColumn;
import javax.persistence.DiscriminatorType;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;

@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "type", discriminatorType = DiscriminatorType.STRING)
@DiscriminatorValue(value = "asset")
public class Asset {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    private String name;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
</code>```

And my Model class.

```<code>// MODEL CLASS

import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;

@Entity
@DiscriminatorValue(value = "model")
public class Model extends Asset {

    private long version;

    public long getVersion() { return version; }

    public void setVersion(long version) { this.version = version; }
}
</code>```

I created a Repository where I want to query for findAllAssetsByType(), but I seems to do something completely wrong.
Here is the AssetRepository interface

```<code>//ASSET REPOSITORY

import assetservice.entity.Asset;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;

public interface AssetRepository extends JpaRepository<Asset, Long> {

    //big problem - store specific - if discriminiator changes this has to change too...
    //@Query("select a from Asset a where type = ?1")
    List<Asset> findAssetsByType(String type);
}
</code>```

I also wrote a little test, to illustrate what I want to do:

```<code>// TEST REPOSITORY
import static org.assertj.core.api.Assertions.assertThat;

import assetservice.core.AppLogger;
import assetservice.dao.AssetRepository;
import java.util.ArrayList;
import java.util.List;
import org.apache.logging.log4j.Logger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@DataJpaTest
public class TestAsset {

    private static final Logger logger = AppLogger.getLogger();

    @Autowired
    private AssetRepository ar;

    @Test
    public void doSomething1() {
        Asset expected = new Asset();
        expected.setName("MyTestAsset");
        ar.save(expected);
        Asset actual = this.ar.findOne(expected.getId());
        assertThat(actual).isEqualTo(expected);
    }

    @Test
    public void doSomething2() {
        Asset expected = new Model();
        expected.setName("MyTestModel");
        ar.save(expected);
        Asset actual = this.ar.findOne(expected.getId());
        assertThat(actual).isEqualTo(expected);
    }

    @Test
    public void doSomething3() {
        Asset expectedModel = new Model();
        Asset expectedAsset = new Asset();
        expectedModel.setName("MyTestModel");
        expectedAsset.setName("MyTestAsset");
        ar.save(expectedModel);
        ar.save(expectedAsset);
        Asset actualModel = this.ar.findOne(expectedModel.getId());
        assertThat(actualModel).isEqualTo(expectedModel);

        Asset actualAsset = this.ar.findOne(expectedAsset.getId());
        assertThat(actualAsset).isEqualTo(actualAsset);

        List<Asset> expectedAssetList = new ArrayList<>();
        expectedAssetList.add(this.ar.findOne(expectedModel.getId()));
        List<Asset> actualAssetList = this.ar.findAssetsByType("model");

        logger.info("\n\n\n\n\n\n\n\n");
        logger.info(expectedAssetList);
        logger.info(actualAssetList);
        logger.info("\n\n\n\n\n\n\n\n");
    }
}
</code>```

Test doSomething1 and doSomething2 work as expected. Test doSomething3 fails with

```<code>Failed to load ApplicationContext
java.lang.IllegalStateException: Failed to load ApplicationContext
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83)
    at org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener.prepareTestInstance(SpringBootDependencyInjectionTestExecutionListener.java:47)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.runTestClass(JUnitTestClassExecuter.java:114)
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.execute(JUnitTestClassExecuter.java:57)
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassProcessor.processTestClass(JUnitTestClassProcessor.java:66)
    at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:51)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:32)
    at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
    at com.sun.proxy.$Proxy1.processTestClass(Unknown Source)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:109)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:146)
    at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:128)
    at org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:404)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
    at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:46)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
    at java.lang.Thread.run(Thread.java:748)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'assetRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property type found for type Asset!
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:742)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:303)
    at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:120)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
    ... 47 more
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property type found for type Asset!
    at org.springframework.data.mapping.PropertyPath.<init>(PropertyPath.java:77)
    at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:329)
    at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:309)
    at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:272)
    at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:243)
    at org.springframework.data.repository.query.parser.Part.<init>(Part.java:76)
    at org.springframework.data.repository.query.parser.PartTree$OrPart.<init>(PartTree.java:247)
    at org.springframework.data.repository.query.parser.PartTree$Predicate.buildTree(PartTree.java:398)
    at org.springframework.data.repository.query.parser.PartTree$Predicate.<init>(PartTree.java:378)
    at org.springframework.data.repository.query.parser.PartTree.<init>(PartTree.java:89)
    at org.springframework.data.jpa.repository.query.PartTreeJpaQuery.<init>(PartTreeJpaQuery.java:64)
    at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:103)
    at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateIfNotFoundQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:214)
    at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$AbstractQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:77)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.<init>(RepositoryFactorySupport.java:436)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:221)
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.initAndReturn(RepositoryFactoryBeanSupport.java:277)
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:263)
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:101)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624)
    ... 62 more
</code>```

It seems to fail because of Caused by: org.springframework.data.mapping.PropertyReferenceException: No property type found for type Asset!.

My question is, do I get around custom queries or querydsl in this case? As you can see, I already got it working via @Query("select a from Asset a where type = ?1"), but that's not using Spring Boots automatic... Lets say I have more Asset Types it seems to me that querying for a specific type is quite cumbersome as I would need to instantiate the appropriate entity type for each query I want to do like:

```<code>@Autowire
private ModelRepository mr;

...
List<Model> models = mr.findAll();
</code>```

It would be much easier todo something like this:

```<code>@Autowire
private AssetRepository ar;

...
List<Model> models = ar.findAllByType("models");
</code>```

Should I use a EntityManager to query? Is there a better way than @Query? Should I just create a "Asset" table and use a column like "type" instead of defining all Entities?

答:
in your asset class you have not included the column type.
Thus, your class should look something like this

```<code>@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
private String type;

public long getId() {
    return id;
}

public void setId(long id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getType() {
    return type;
}

public void setType(String type) {
    this.type = type;
}
</code>```

Let me know if this fixed your problem.

Body:
I am trying to understand Spring Boot's and JPA's magics. I have the following classes:

Base Asset class (could also be abstract in my case)
Class Model inheriting from Asset.

// ASSET CLASS

import javax.persistence.DiscriminatorColumn;
import javax.persistence.DiscriminatorType;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;

@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "type", discriminatorType = DiscriminatorType.STRING)
@DiscriminatorValue(value = "asset")
public class Asset {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    private String name;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

And my Model class.

// MODEL CLASS

import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;

@Entity
@DiscriminatorValue(value = "model")
public class Model extends Asset {

    private long version;

    public long getVersion() { return version; }

    public void setVersion(long version) { this.version = version; }
}

I created a Repository where I want to query for findAllAssetsByType(), but I seems to do something completely wrong.
Here is the AssetRepository interface

//ASSET REPOSITORY

import assetservice.entity.Asset;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;

public interface AssetRepository extends JpaRepository<Asset, Long> {

    //big problem - store specific - if discriminiator changes this has to change too...
    //@Query("select a from Asset a where type = ?1")
    List<Asset> findAssetsByType(String type);
}

I also wrote a little test, to illustrate what I want to do:

// TEST REPOSITORY
import static org.assertj.core.api.Assertions.assertThat;

import assetservice.core.AppLogger;
import assetservice.dao.AssetRepository;
import java.util.ArrayList;
import java.util.List;
import org.apache.logging.log4j.Logger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@DataJpaTest
public class TestAsset {

    private static final Logger logger = AppLogger.getLogger();

    @Autowired
    private AssetRepository ar;

    @Test
    public void doSomething1() {
        Asset expected = new Asset();
        expected.setName("MyTestAsset");
        ar.save(expected);
        Asset actual = this.ar.findOne(expected.getId());
        assertThat(actual).isEqualTo(expected);
    }

    @Test
    public void doSomething2() {
        Asset expected = new Model();
        expected.setName("MyTestModel");
        ar.save(expected);
        Asset actual = this.ar.findOne(expected.getId());
        assertThat(actual).isEqualTo(expected);
    }

    @Test
    public void doSomething3() {
        Asset expectedModel = new Model();
        Asset expectedAsset = new Asset();
        expectedModel.setName("MyTestModel");
        expectedAsset.setName("MyTestAsset");
        ar.save(expectedModel);
        ar.save(expectedAsset);
        Asset actualModel = this.ar.findOne(expectedModel.getId());
        assertThat(actualModel).isEqualTo(expectedModel);

        Asset actualAsset = this.ar.findOne(expectedAsset.getId());
        assertThat(actualAsset).isEqualTo(actualAsset);

        List<Asset> expectedAssetList = new ArrayList<>();
        expectedAssetList.add(this.ar.findOne(expectedModel.getId()));
        List<Asset> actualAssetList = this.ar.findAssetsByType("model");

        logger.info("\n\n\n\n\n\n\n\n");
        logger.info(expectedAssetList);
        logger.info(actualAssetList);
        logger.info("\n\n\n\n\n\n\n\n");
    }
}

Test doSomething1 and doSomething2 work as expected. Test doSomething3 fails with

Failed to load ApplicationContext
java.lang.IllegalStateException: Failed to load ApplicationContext
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83)
    at org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener.prepareTestInstance(SpringBootDependencyInjectionTestExecutionListener.java:47)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.runTestClass(JUnitTestClassExecuter.java:114)
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.execute(JUnitTestClassExecuter.java:57)
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassProcessor.processTestClass(JUnitTestClassProcessor.java:66)
    at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:51)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:32)
    at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
    at com.sun.proxy.$Proxy1.processTestClass(Unknown Source)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:109)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:146)
    at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:128)
    at org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:404)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
    at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:46)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
    at java.lang.Thread.run(Thread.java:748)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'assetRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property type found for type Asset!
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:742)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:303)
    at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:120)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
    ... 47 more
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property type found for type Asset!
    at org.springframework.data.mapping.PropertyPath.<init>(PropertyPath.java:77)
    at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:329)
    at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:309)
    at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:272)
    at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:243)
    at org.springframework.data.repository.query.parser.Part.<init>(Part.java:76)
    at org.springframework.data.repository.query.parser.PartTree$OrPart.<init>(PartTree.java:247)
    at org.springframework.data.repository.query.parser.PartTree$Predicate.buildTree(PartTree.java:398)
    at org.springframework.data.repository.query.parser.PartTree$Predicate.<init>(PartTree.java:378)
    at org.springframework.data.repository.query.parser.PartTree.<init>(PartTree.java:89)
    at org.springframework.data.jpa.repository.query.PartTreeJpaQuery.<init>(PartTreeJpaQuery.java:64)
    at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:103)
    at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateIfNotFoundQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:214)
    at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$AbstractQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:77)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.<init>(RepositoryFactorySupport.java:436)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:221)
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.initAndReturn(RepositoryFactoryBeanSupport.java:277)
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:263)
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:101)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624)
    ... 62 more

It seems to fail because of Caused by: org.springframework.data.mapping.PropertyReferenceException: No property type found for type Asset!.

My question is, do I get around custom queries or querydsl in this case? As you can see, I already got it working via @Query("select a from Asset a where type = ?1"), but that's not using Spring Boots automatic... Lets say I have more Asset Types it seems to me that querying for a specific type is quite cumbersome as I would need to instantiate the appropriate entity type for each query I want to do like:

@Autowire
private ModelRepository mr;

...
List<Model> models = mr.findAll();

It would be much easier todo something like this:

@Autowire
private AssetRepository ar;

...
List<Model> models = ar.findAllByType("models");

Should I use a EntityManager to query? Is there a better way than @Query? Should I just create a "Asset" table and use a column like "type" instead of defining all Entities?

Body:
in your asset class you have not included the column type.
Thus, your class should look something like this

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
private String type;

public long getId() {
    return id;
}

public void setId(long id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getType() {
    return type;
}

public void setType(String type) {
    this.type = type;
}

Let me know if this fixed your problem.


问:
App Icon Missing in Google Drive Manage Apps
I have an android app that connects to Google Drive. I created a Chrome Web Store listing for this app using following manifest.json:

```<code>{
  "name": "App Name",
  "description": "App Description",
  "version": "2.4",
  "manifest_version": 2,
  "container": ["GOOGLE_DRIVE"],
  "api_console_project_id": "ID",
  "icons": {
    "128": "icon_128.png"
  }
}
</code>```

When I checked Google Drive - Settings - Manage Apps, for this particular app all other details showing except App Icon.

Please advise how to proceed on this?

答:
Your "icon_128.png" must be existing inside the compressed folder on where you placed your manifest file, so that it would return the image as your icon no matter where you place your application.

You can also go to your Chrome Webstore Dashboard, go to your app and click Edit. That will open a window where you can upload your 128px icon.

Body:
I have an android app that connects to Google Drive. I created a Chrome Web Store listing for this app using following manifest.json:

{
  "name": "App Name",
  "description": "App Description",
  "version": "2.4",
  "manifest_version": 2,
  "container": ["GOOGLE_DRIVE"],
  "api_console_project_id": "ID",
  "icons": {
    "128": "icon_128.png"
  }
}

When I checked Google Drive - Settings - Manage Apps, for this particular app all other details showing except App Icon.

Please advise how to proceed on this?


问:
It lags when i am using android studio
my laptop is i7 4510U , 4GB ram , Intel HD graphics 2gb , Nvidia GeForce 840m 4GB
why it's so laggy when Iam using android studio?</p>

答:
Your 4GB of ram is to blame,

to use well Android Studio, you need at least 8GB of RAM (more if intend to use emulators), just note that the GPU have no use here, and even the processor you just need a mid range processor to work well, but when compiling the more powerful processor you have the better.

Title: It lags when i am using android studio


问:
Best way to refactor more functions in pgadmin
I'm new in PostgreSQL, and i was lookinng for a good way to find and replace a word (the name of a function) in multiple functions.

I'm using the latest version of PostgreSQL.

Does someone knows how can I do it in a good manner?

Thanks

答:
pgadmin offers "Find and Replace" window for such operations. Staying neutral about the approach (if pgadmin offers - then I can't say it's a bad practice) you can copy all functions definitions from pg_catalog and use this approach for "bulk" object rename inside function bodies. Or select with replace and then run the changed definitions.

Here's why I would recommend not doing this. Let's say you want to change length( to new_length( in all functions. if you just

```<code>t=# select proname,replace(prosrc,'length(','new_length(') from pg_proc where prosrc like '%length(%' limit 3;
  proname   |                  replace
------------+--------------------------------------------
 bit_length | select pg_catalog.octet_new_length($1) * 8
 bit_length | select pg_catalog.octet_new_length($1) * 8
 bit_length | select pg_catalog.new_length($1)
(3 rows)
</code>```

As you see you affect more names then just length. Of course you can use .length( to avoid octet_length and bit_length, but there is no guarantee you dont use just length in your code (without pg_catalog.). and so on and so forth. So if you blindly replace all occurences you risk to brake the code. And if you check them all, you do one by one anyway. So maybe just go through every occurrence and check every one before changing?..

Lastly I'd use psql for such work, or at least mix it with pgadmin. As psql has a set of meta commands, very useful. Eg function definition can be get by just sf fn_name. Running the definition puts it to history, that can be comfortably edited in vim or any other editor and rerun with changed names. (vim offers :%s/oldname/newname/g which is same Find and Replace and so on...)

Body:
pgadmin offers "Find and Replace" window for such operations. Staying neutral about the approach (if pgadmin offers - then I can't say it's a bad practice) you can copy all functions definitions from pg_catalog and use this approach for "bulk" object rename inside function bodies. Or select with replace and then run the changed definitions.

Here's why I would recommend not doing this. Let's say you want to change length( to new_length( in all functions. if you just

t=# select proname,replace(prosrc,'length(','new_length(') from pg_proc where prosrc like '%length(%' limit 3;
  proname   |                  replace
------------+--------------------------------------------
 bit_length | select pg_catalog.octet_new_length($1) * 8
 bit_length | select pg_catalog.octet_new_length($1) * 8
 bit_length | select pg_catalog.new_length($1)
(3 rows)

As you see you affect more names then just length. Of course you can use .length( to avoid octet_length and bit_length, but there is no guarantee you dont use just length in your code (without pg_catalog.). and so on and so forth. So if you blindly replace all occurences you risk to brake the code. And if you check them all, you do one by one anyway. So maybe just go through every occurrence and check every one before changing?..

Lastly I'd use psql for such work, or at least mix it with pgadmin. As psql has a set of meta commands, very useful. Eg function definition can be get by just sf fn_name. Running the definition puts it to history, that can be comfortably edited in vim or any other editor and rerun with changed names. (vim offers :%s/oldname/newname/g which is same Find and Replace and so on...)


问:
Layout Designer - Drag and Drop in PHP
I  would like to build a Layout designer in PHP or would like to use a readymade script( even if it is a paid one )

Basically I would like to create a sort of Layout where users could choose fields to add from a "field chooser". Each field could be of any type... and we would like to provide a field group too, where the user could  choose the number of columns, and make the columns of this "panel" droppable.

We should drag a field from a list, and drop the field to a placeholder on a Form (Panel?).
Finally, is it possible to "read" the form layout in order to store it for later use?

thanks

kabir

答: Drag and drop isn't available in PHP. PHP is a server-side language; what you're asking for in client-side and would be accomplished using something like JavaScript. You would then use PHP to read the user's choices based on an event occuring, i.e. an item dropped or the user click a confirmation button.</p>

Title: Layout Designer - Drag and Drop in PHP


问:
Count unique values based on criteria given in another column
I have a list of machines with respective batches and part number being manufactured.

I need a unique count of a batches running in a machine. This long list is updated daily. I have attached an example here.

I have this rough code.

```<code>last_row = ws.Cells(Rows.Count,1).End(xlUp).Row
For Each M_cCell in M_cRange
    Counter = 0
    For i = 2 to last_row
        If Cells(1, 1).Value = M_cCell Then
            Counter = Counter + (1/(WorksheetFunction.CountIF _
            (Range(Cells(2,2),Cells(Last_row,2),M_ccell.Value)))
        End If
    Next i
Next M_cCell
</code>```

This gives an undesired result in decimal figures.

答:
I would approach to this by easier way. Without any code example. Just think about this:

Loop through all data and find uniques according to both columns - in this case you will get just 2 results. Each new result you will save to temp array.

Loop again through all data and compare every row with every field of stored temp array. Add counters for that and that's all.

Body:
I have a list of machines with respective batches and part number being manufactured.

I need a unique count of a batches running in a machine. This long list is updated daily. I have attached an example here.

I have this rough code.

last_row = ws.Cells(Rows.Count,1).End(xlUp).Row
For Each M_cCell in M_cRange
    Counter = 0
    For i = 2 to last_row
        If Cells(1, 1).Value = M_cCell Then
            Counter = Counter + (1/(WorksheetFunction.CountIF _
            (Range(Cells(2,2),Cells(Last_row,2),M_ccell.Value)))
        End If
    Next i
Next M_cCell

This gives an undesired result in decimal figures.


问:
Pasting artihmetic mean VBA
Let's say I have two Excel Workbooks(in reality I have one sheet results and maybe a hundered other workbooks containing data). I would like to create a macro that allows me to take the arithmetic mean of a selection and paste that into my active cell. I have written a macro that allows me to paste copied values between different workbooks, really simple:

```<code>Sub PasteVal()
    Selection.PasteSpecial xlPasteValues
End Sub
</code>```

Trying to do the arithmetic mean copying does not work, however:

```<code>Sub PasteMean()
     ActiveCell.PasteSpecial (Application.WorksheetFunction.Average(Selection))
End Sub
</code>```

Any help would be appreciated

Thanks.

答:
did you try ?
activecell.value=Application.WorksheetFunction.Average(Selection)

Title: Pasting artihmetic mean VBA

Body:
Let's say I have two Excel Workbooks(in reality I have one sheet results and maybe a hundered other workbooks containing data). I would like to create a macro that allows me to take the arithmetic mean of a selection and paste that into my active cell. I have written a macro that allows me to paste copied values between different workbooks, really simple:

Sub PasteVal()
    Selection.PasteSpecial xlPasteValues
End Sub

Trying to do the arithmetic mean copying does not work, however:

Sub PasteMean()
     ActiveCell.PasteSpecial (Application.WorksheetFunction.Average(Selection))
End Sub

Any help would be appreciated

Thanks.


问:
Subset df on string condition
I want to subset df on an unknown condition (say, randomly defined as in the example below):

```<code>df <- data.frame(a=1:10, b = 10:1)
condition <- paste0(sample(letters[1:2],1), sample(c("<",">"),1), sample(1:10,1))
</code>```

I can do this with eval, which, vox populi, is suboptimal:

```<code>subset(df, eval(parse(text=condition)))
</code>```

Is there an alternative to eval(parse)?

答:
Just one thought. There are other ways to keep the code dynamic without the (nasty) "character-expression", for example:</p>

```<code>df <- data.frame(a=1:10, b = 10:1)

mysubset <- function (f,x1,x2) {
  df[f(df[[x1]],x2),]
}

mycol <- sample(letters[1:2],1)
myfun <- sample(c("<",">"),1)
mylimit <- sample(1:10,1)

mysubset(.Primitive(myfun),mycol,mylimit) # in my mind just as dynamic as eval-parse ..

mysubset(`<`,"a",4)
</code>```

Title: Subset df on string condition

Body:
I want to subset df on an unknown condition (say, randomly defined as in the example below):

df <- data.frame(a=1:10, b = 10:1)
condition <- paste0(sample(letters[1:2],1), sample(c("<",">"),1), sample(1:10,1))

I can do this with eval, which, vox populi, is suboptimal:

subset(df, eval(parse(text=condition)))

Is there an alternative to eval(parse)?

Body:
Just one thought. There are other ways to keep the code dynamic without the (nasty) "character-expression", for example:

df <- data.frame(a=1:10, b = 10:1)

mysubset <- function (f,x1,x2) {
  df[f(df[[x1]],x2),]
}

mycol <- sample(letters[1:2],1)
myfun <- sample(c("<",">"),1)
mylimit <- sample(1:10,1)

mysubset(.Primitive(myfun),mycol,mylimit) # in my mind just as dynamic as eval-parse ..

mysubset(`<`,"a",4)


问:
How to get duplicate object array using lodash?
I have Json array like attached image.

multiple records

I want to find the name and get the value.
Currently i am using like this.

```<code>$scope.getDetailList = _.find(list, function(item) {
  return _.trim(item.name).toLowerCase() === _.trim(targetname).toLowerCase();
}
</code>```

but i always get first objects values.

答:
Use _.filter to filter array and give results. use JavaScript trim() function. _.trim is not there in lodash.</p>

```<code>$scope.getDetailList = _.filter(list, function(item) {
  return (item.name).trim().toLowerCase() === targetname.trim().toLowerCase();
}
</code>```

Body:
I have Json array like attached image.

multiple records

I want to find the name and get the value.
Currently i am using like this.

$scope.getDetailList = _.find(list, function(item) {
  return _.trim(item.name).toLowerCase() === _.trim(targetname).toLowerCase();
}

but i always get first objects values.

Body:
Use _.filter to filter array and give results. use JavaScript trim() function. _.trim is not there in lodash.

$scope.getDetailList = _.filter(list, function(item) {
  return (item.name).trim().toLowerCase() === targetname.trim().toLowerCase();
}


问:
Scala 2.8.1 implicitly convert to java.util.List<java.util.Map<String, Object>>
I have a Scala data structure created with the following:

```<code>List(Map[String, Anyref]("a" -> someFoo, "b" -> someBar))
</code>```

I would like to implicitly convert it (using scala.collection.JavaConversions or scala.collection.JavaConverters) to a java.util.List<java.util.Map<String, Object>> to be passed the a Java method that expects the latter.

Is this possible?

I have already created the following method that does it, but was wondering if it can be done automatically by the compiler?

```<code>import scala.collection.JavaConversions._
def convertToJava(listOfMaps: List[Map[String, AnyRef]]):
  java.util.List[java.util.Map[String, Object]] = {
  asJavaList(listOfMaps.map(asJavaMap(_)))
}
</code>```

答:
How about writing

```<code>implicit def convertToJava...
</code>```

?

Body:
I have a Scala data structure created with the following:

List(Map[String, Anyref]("a" -> someFoo, "b" -> someBar))

I would like to implicitly convert it (using scala.collection.JavaConversions or scala.collection.JavaConverters) to a java.util.List<java.util.Map<String, Object>> to be passed the a Java method that expects the latter.

Is this possible?

I have already created the following method that does it, but was wondering if it can be done automatically by the compiler?

import scala.collection.JavaConversions._
def convertToJava(listOfMaps: List[Map[String, AnyRef]]):
  java.util.List[java.util.Map[String, Object]] = {
  asJavaList(listOfMaps.map(asJavaMap(_)))
}

Body:
How about writing

implicit def convertToJava...

?